🧠 什么是张量?
张量可以理解为多维数组,是 PyTorch 中用于存储和操作数据的基本单位。它类似于 NumPy 中的 ndarray
,但张量还支持 GPU 加速 和 自动求导。
类型 | 示例 |
---|
标量(0维) | torch.tensor(3.14) |
向量(1维) | torch.tensor([1, 2, 3]) |
矩阵(2维) | torch.tensor([[1, 2], [3, 4]]) |
高阶张量 | 三维、四维… |
🛠️ 张量的创建方式
基本创建
import torch
# 直接指定值
a = torch.tensor([1.0, 2.0, 3.0])
# 全零、全一、单位矩阵
b = torch.zeros(2, 3)
c = torch.ones(3, 3)
d = torch.eye(4) # 单位矩阵
# 指定形状的随机数
e = torch.rand(2, 2) # 均匀分布
f = torch.randn(2, 2) # 正态分布
从 NumPy 转换
import numpy as np
np_array = np.array([[1, 2], [3, 4]])
tensor = torch.from_numpy(np_array) # 共享内存
创建与其他张量相同形状的张量
x = torch.ones(3, 4)
y = torch.zeros_like(x)
z = torch.randn_like(x)
📐 张量的属性和常用操作
t = torch.tensor([[1, 2], [3, 4]])
print(t.shape) # 输出:torch.Size([2, 2])
print(t.dtype) # 输出:torch.int64(默认)
print(t.device) # 显示张量所在设备(CPU 或 CUDA)
数据类型转换
float_tensor = t.float()
int_tensor = float_tensor.int()
🔁 张量的运算
基本数学运算
a = torch.tensor([1.0, 2.0, 3.0])
b = torch.tensor([3.0, 2.0, 1.0])
print(a + b) # 加法
print(a * b) # 乘法
print(torch.dot(a, b)) # 点积
广播机制
a = torch.ones(3, 1)
b = torch.ones(1, 4)
print(a + b) # 自动广播成 (3, 4)
📏 维度操作(变换张量形状)
t = torch.randn(2, 3)
# 改变形状
reshaped = t.view(3, 2) # 不改变内存
reshaped2 = t.reshape(3, 2)
# 添加/删除维度
t_unsqueezed = t.unsqueeze(0) # shape: (1, 2, 3)
t_squeezed = t_unsqueezed.squeeze() # 回到 (2, 3)
# 转置
t_T = t.T # 或者 t.transpose(0, 1)
🧮 索引与切片
x = torch.tensor([[1, 2, 3], [4, 5, 6]])
print(x[0, 0]) # 第一行第一列
print(x[:, 1]) # 所有行的第二列
print(x[1, :2]) # 第二行前两列
📡 张量与 GPU
将张量移动到 GPU
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
x = torch.rand(2, 2)
x = x.to(device) # 移动到 GPU
🔁 常用函数速查表
功能 | 函数 |
---|
创建张量 | tensor() 、ones() 、zeros() |
随机数 | rand() 、randn() |
改变形状 | view() 、reshape() |
添加维度 | unsqueeze() |
删除维度 | squeeze() |
转置 | transpose() 、.T |
数据类型 | float() 、int() |
GPU 加速 | .to("cuda") |
🧪 示例:从创建到计算
a = torch.randn(3, 3)
b = torch.ones(3, 3)
c = a + b
print(c.sum())
print(c.mean())
📘 推荐练习
- 创建一个三维张量(形状为
2x3x4
),对其中元素进行求和与平均。
- 实现两个二维张量的矩阵乘法。
- 模拟神经网络中的一个线性变换:
y = Wx + b
。
发表回复