建网赌网站流程,做网站注意什么,心理网站的建设与维护,怎么做网站从0做到权重7如是我闻#xff1a; Tensor 是我们接触Pytorch了解到的第一个概念#xff0c;这里是一个关于 PyTorch Tensor 主题的知识点总结#xff0c;涵盖了 Tensor 的基本概念、创建方式、运算操作、梯度计算和 GPU 加速等内容。 1. Tensor 基本概念
Tensor 是 PyTorch 的核心数据结…如是我闻 Tensor 是我们接触Pytorch了解到的第一个概念这里是一个关于 PyTorch Tensor 主题的知识点总结涵盖了 Tensor 的基本概念、创建方式、运算操作、梯度计算和 GPU 加速等内容。 1. Tensor 基本概念
Tensor 是 PyTorch 的核心数据结构类似于 NumPy 的 ndarray但支持 GPU 加速和自动求导。PyTorch 的 Tensor 具有 动态计算图可用于深度学习模型的前向传播和反向传播。
PyTorch Tensor vs. NumPy Array
特性PyTorch TensorNumPy Array支持 GPU✅❌自动求导✅ (requires_gradTrue)❌兼容性✅ (可转换为 NumPy)✅ (可转换为 Tensor) 2. Tensor 创建方式
2.1 直接创建 Tensor
import torch# 从列表创建
a torch.tensor([1, 2, 3])
b torch.tensor([[1.0, 2.0], [3.0, 4.0]], dtypetorch.float32)print(a, a.dtype) # 默认 int64
print(b, b.dtype) # float322.2 常见初始化方法
# 全零/全一 Tensor
x torch.zeros((3, 3))
y torch.ones((2, 2))# 随机初始化
z torch.rand((3, 3)) # [0, 1) 均匀分布
n torch.randn((2, 2)) # 标准正态分布# 单位矩阵
I torch.eye(3)# 创建指定范围的 Tensor
r torch.arange(0, 10, 2) # [0, 2, 4, 6, 8]
l torch.linspace(0, 1, 5) # [0.0, 0.25, 0.5, 0.75, 1.0]2.3 通过 NumPy 互转
import numpy as np# NumPy - PyTorch
np_array np.array([[1, 2], [3, 4]])
tensor_from_np torch.from_numpy(np_array)# PyTorch - NumPy
tensor torch.tensor([[1.0, 2.0], [3.0, 4.0]])
np_from_tensor tensor.numpy()3. Tensor 形状操作
3.1 维度变换
x torch.randn(2, 3, 4)# 改变形状
y x.view(6, 4) # 使用 view 改变形状 (必须保证数据连续存储)
z x.reshape(6, 4) # reshape 不受数据存储方式限制# 维度扩展
x_exp x.unsqueeze(0) # 在第 0 维添加一个维度
x_squeeze x_exp.squeeze(0) # 去除维数为 1 的维度3.2 维度交换
x torch.rand(2, 3, 4)x_t x.permute(2, 0, 1) # 交换维度
x_t2 x.transpose(1, 2) # 交换 1 和 2 维4. Tensor 运算
4.1 逐元素运算
x torch.tensor([1, 2, 3])
y torch.tensor([4, 5, 6])# 逐元素运算
add x y # 或 torch.add(x, y)
sub x - y # 或 torch.sub(x, y)
mul x * y # 或 torch.mul(x, y)
div x / y # 或 torch.div(x, y)# 指数、对数、幂运算
exp torch.exp(x)
log torch.log(y)
pow_2 x.pow(2) # 平方4.2 线性代数运算
A torch.tensor([[1, 2], [3, 4]])
B torch.tensor([[5, 6], [7, 8]])# 矩阵乘法
C torch.mm(A, B) # 矩阵乘法
D A B # 矩阵乘法 (等价于 mm)# 逆矩阵
A_inv torch.inverse(A.float())# 计算特征值和特征向量
eigenvalues, eigenvectors torch.eig(A.float(), eigenvectorsTrue)4.3 统计运算
x torch.randn(3, 3)mean_x x.mean() # 均值
std_x x.std() # 标准差
sum_x x.sum() # 总和
max_x x.max() # 最大值
argmax_x x.argmax() # 最大值索引5. Tensor 计算图和自动求导
5.1 计算梯度
x torch.tensor(2.0, requires_gradTrue)y x**2 3*x 1 # 计算 y
y.backward() # 计算梯度print(x.grad) # dy/dx 2x 3 - 2*2 3 75.2 阻止梯度计算
x torch.tensor(2.0, requires_gradTrue)with torch.no_grad():y x**2 3*x 1 # 计算过程中不记录梯度6. GPU 计算
6.1 设备选择
device torch.device(cuda if torch.cuda.is_available() else cpu)6.2 在 GPU 上创建 Tensor
x torch.randn(3, 3, devicedevice)6.3 在 CPU 和 GPU 之间转换
x_cpu x.to(cpu) # 移回 CPU
x_gpu x.to(cuda) # 移至 GPU7. 总的来说
主题关键知识点Tensor 创建torch.tensor()、torch.zeros()、torch.rand()NumPy 互转torch.from_numpy()、.numpy()形状变换.view()、.reshape()、.unsqueeze()运算逐元素计算、矩阵运算、统计运算自动求导requires_gradTrue、.backward()GPU 加速torch.device(cuda)、.to(cuda) 以上