Tensor Operations
8 methods张量创建、设备迁移、自动求导与模型训练的核心 API。
torch.tensor(data, dtype=None)从 Python 列表或数值创建张量。
Parameters
| Name | Type | Description |
|---|---|---|
| data | list | array_like | 输入数据 |
| dtype | torch.dtype | 数据类型,如 torch.float32 |
Returns
Tensor — 张量
Example
pytorch
import torch
x = torch.tensor([[1, 2], [3, 4]], dtype=torch.float32)
print(x, x.dtype)torch.zeros(*size) / torch.ones(*size)创建指定形状的全零或全一张量。
Parameters
| Name | Type | Description |
|---|---|---|
| size | tuple[int] | 张量各维度大小 |
Returns
Tensor — 全零/全一张量
Example
pytorch
import torch
z = torch.zeros(3, 4)
o = torch.ones(2, 2)
print(z.shape, o.shape)torch.randn(*size)创建服从标准正态分布 N(0,1) 的随机张量。
Parameters
| Name | Type | Description |
|---|---|---|
| size | tuple[int] | 张量各维度大小 |
Returns
Tensor — 标准正态分布随机张量
Example
pytorch
import torch
x = torch.randn(2, 3)
print(x.mean().item(), x.std().item())tensor.to(device)将张量或模块迁移到指定设备(CPU/GPU)。
Parameters
| Name | Type | Description |
|---|---|---|
| device | torch.device | str | 目标设备,如 'cuda' |
Returns
Tensor — 迁移后的张量
Example
pytorch
import torch
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
x = torch.randn(4, 4).to(device)
print(x.device)tensor.requires_grad_(bool)原地设置张量是否需要追踪梯度用于自动求导。
Parameters
| Name | Type | Description |
|---|---|---|
| requires_grad | bool | 是否记录梯度 |
Returns
Tensor — 自身(原地修改)
Example
pytorch
import torch
x = torch.tensor([1.0, 2.0, 3.0], requires_grad=True)
y = (x ** 2).sum()
y.backward()
print(x.grad) # tensor([2., 4., 6.])torch.nn.Linear(in_features, out_features)创建一个线性全连接层:y = xW^T + b。
Parameters
| Name | Type | Description |
|---|---|---|
| in_features | int | 输入特征维度 |
| out_features | int | 输出特征维度 |
Returns
Linear — 线性层模块
Example
pytorch
import torch.nn as nn
fc = nn.Linear(10, 5)
import torch
out = fc(torch.randn(3, 10))
print(out.shape) # torch.Size([3, 5])loss.backward()对损失张量进行反向传播,自动计算各参数梯度。
Returns
None — 梯度累积到 .grad 属性
Example
pytorch
import torch
x = torch.tensor(2.0, requires_grad=True)
y = x ** 2
y.backward()
print(x.grad) # 4.0optimizer.step()根据当前梯度执行一步参数更新。
Returns
None — 原地更新模型参数
Example
pytorch
import torch
w = torch.tensor(1.0, requires_grad=True)
opt = torch.optim.SGD([w], lr=0.1)
loss = (w - 3) ** 2
loss.backward()
opt.step()
opt.zero_grad()
print(w.item())