Python-pytorch-基础入门
·
PyTorch 基础入门:张量(Tensor)
🔥 什么是张量?
张量(Tensor)是 PyTorch 的核心数据结构,你可以把它理解为可以在 GPU 上加速运算的多维数组。它和 NumPy 的 ndarray 非常相似,但多了三个关键能力:
- 自动求导(Autograd)——自动计算梯度
- GPU 加速——张量可以搬到 GPU 上,实现百倍级提速
- 动态计算图——每次前向传播都是一张新图,调试方便
| 术语 | 维度 | 示例 |
|---|---|---|
| 标量(Scalar) | 0 维 | torch.tensor(3.14) |
| 向量(Vector) | 1 维 | torch.tensor([1, 2, 3]) |
| 矩阵(Matrix) | 2 维 | torch.randn(3, 4) |
| 张量(Tensor) | ≥3 维 | torch.randn(2, 3, 4, 5) |
📦 创建张量
import torch
import numpy as np
从数据创建
# 从列表
x = torch.tensor([1, 2, 3])
# tensor([1, 2, 3])
# 从嵌套列表(2D)
x = torch.tensor([[1, 2], [3, 4], [5, 6]])
# tensor([[1, 2],
# [3, 4],
# [5, 6]])
# 从 NumPy 数组
arr = np.array([1, 2, 3])
x = torch.from_numpy(arr) # 共享内存
x = torch.tensor(arr) # 复制数据
# 指定数据类型
x = torch.tensor([1, 2, 3], dtype=torch.float32)
特殊张量
# 全零 / 全一
x = torch.zeros(3, 4) # (3, 4) 的全零矩阵
x = torch.ones(3, 4) # (3, 4) 的全一矩阵
x = torch.zeros_like(y) # 和 y 形状相同的全零
# 单位矩阵
x = torch.eye(3) # 3x3 单位矩阵
# 未初始化(效率更高,但需立即赋值)
x = torch.empty(3, 4)
# 全填充
x = torch.full((3, 4), 7) # 全为 7 的 (3, 4) 矩阵
序列张量
# 等差
x = torch.arange(0, 10, 2) # tensor([0, 2, 4, 6, 8])
x = torch.arange(5) # tensor([0, 1, 2, 3, 4])
# 等分
x = torch.linspace(0, 1, 5) # 0 到 1 均匀取 5 个点
# tensor([0.0000, 0.2500, 0.5000, 0.7500, 1.0000])
# 对数等分
x = torch.logspace(-2, 2, 5) # 10^-2 到 10^2
随机张量 ⭐
# 均匀分布 [0, 1)
x = torch.rand(3, 4)
# 标准正态分布 N(0, 1)
x = torch.randn(3, 4)
# 整数随机 [low, high)
x = torch.randint(0, 10, (3, 4))
# 正态分布 N(mean, std)
x = torch.normal(mean=0, std=1, size=(3, 4))
# 随机排列
x = torch.randperm(10) # 0-9 的随机排列
# 固定随机种子(可复现)
torch.manual_seed(42)
📐 张量属性
x = torch.randn(2, 3, 4)
print(x.shape) # torch.Size([2, 3, 4])
print(x.size()) # 同上,可以传入 dim: x.size(0) → 2
print(x.ndim) # 维度数: 3
print(x.dtype) # 数据类型: torch.float32
print(x.device) # 所在设备: cpu / cuda:0
print(x.numel()) # 总元素数: 24
print(x.requires_grad) # 是否需要梯度
🔢 数据类型(dtype)
| 类型 | 别名 | 说明 |
|---|---|---|
torch.float32 |
torch.float |
32 位浮点(默认) |
torch.float64 |
torch.double |
64 位双精度 |
torch.float16 |
torch.half |
16 位半精度 |
torch.int64 |
torch.long |
64 位整数 |
torch.int32 |
torch.int |
32 位整数 |
torch.int8 |
— | 8 位整数(量化用) |
torch.bool |
— | 布尔型 |
torch.bfloat16 |
— | Brain 浮点(训练用) |
# 类型转换
x = torch.tensor([1, 2, 3], dtype=torch.int64)
x = x.float() # → float32
x = x.double() # → float64
x = x.to(torch.float16) # → float16
x = x.type(torch.int32) # → int32
# 创建时指定
x = torch.tensor([1.0, 2.0], dtype=torch.float64)
⚙️ 基本运算
算术运算
a = torch.tensor([1, 2, 3], dtype=torch.float32)
b = torch.tensor([4, 5, 6], dtype=torch.float32)
# 逐元素运算(支持广播)
print(a + b) # tensor([5., 7., 9.])
print(a - b) # tensor([-3., -3., -3.])
print(a * b) # tensor([4., 10., 18.]) 逐元素乘法!
print(a / b) # tensor([0.2500, 0.4000, 0.5000])
print(a ** 2) # tensor([1., 4., 9.])
# 原地操作(名称后带 _ 下划线)
a.add_(1) # a += 1,直接修改 a
a.mul_(2) # a *= 2
矩阵运算
A = torch.randn(3, 4)
B = torch.randn(4, 5)
# 矩阵乘法
C = A @ B # 推荐写法
C = torch.mm(A, B) # 只支持 2D
C = torch.matmul(A, B) # 支持广播
# 批矩阵乘法
A = torch.randn(10, 3, 4) # batch=10
B = torch.randn(10, 4, 5)
C = torch.bmm(A, B) # (10, 3, 5)
# 转置
print(A.T) # 2D 转置
print(A.transpose(0, 1)) # 交换两个维度
print(A.permute(1, 0, 2)) # 任意维度重排
# 点积 / 外积
v1, v2 = torch.randn(3), torch.randn(3)
dot = torch.dot(v1, v2) # 内积(点积)
outer = torch.outer(v1, v2) # 外积
统计运算
x = torch.randn(3, 4)
print(x.sum()) # 所有元素求和
print(x.sum(dim=0)) # 沿行求和(压缩行)→ (4,)
print(x.sum(dim=1)) # 沿列求和(压缩列)→ (3,)
print(x.mean()) # 均值
print(x.std()) # 标准差
print(x.var()) # 方差
print(x.max()) # 最大值
print(x.min()) # 最小值
print(x.argmax()) # 最大值索引(展平后)
print(x.argmax(dim=1)) # 每行最大值索引 → (3,)
比较运算
x = torch.tensor([1, 2, 3, 4, 5])
print(x > 3) # tensor([False, False, False, True, True])
print(x == 3) # tensor([False, False, True, False, False])
print((x > 2) & (x < 5)) # tensor([False, False, True, True, False])
print(torch.any(x > 3)) # True
print(torch.all(x > 0)) # True
🎯 索引与切片
x = torch.randn(4, 5)
# 基本索引
print(x[0]) # 第 0 行 → (5,)
print(x[0, 1]) # 第 0 行第 1 列 → 标量
print(x[:, 0]) # 第 0 列 → (4,)
# 切片
print(x[:2]) # 前 2 行
print(x[1:3, 2:4]) # 行 1-2, 列 2-3
print(x[::2]) # 每隔一行
# 高级索引
indices = torch.tensor([0, 2, 3])
print(x[indices]) # 取第 0, 2, 3 行
print(x[[0, 2], [1, 3]]) # 取 (0,1) 和 (2,3) 两个元素
# 布尔索引
mask = x > 0
print(x[mask]) # 所有 >0 的元素(展平为一维)
🔧 形状操作
x = torch.randn(2, 3, 4)
# view / reshape
y = x.view(-1, 4) # 自动推导第一维 → (6, 4)
y = x.reshape(6, 4) # 同上,但 view 要求内存连续
# 升维 / 降维
y = x.unsqueeze(0) # 在第 0 维前插入 → (1, 2, 3, 4)
y = x.unsqueeze(-1) # 在最后一维后插入 → (2, 3, 4, 1)
y = x.squeeze() # 删除所有长度为 1 的维度
# 展平
y = x.flatten() # 完全展平 → (24,)
y = x.flatten(start_dim=1) # 从第 1 维开始展平 → (2, 12)
# 拼接与堆叠
a, b = torch.randn(2, 3), torch.randn(2, 3)
c = torch.cat([a, b], dim=0) # 沿 dim=0 拼接 → (4, 3)
c = torch.cat([a, b], dim=1) # 沿 dim=1 拼接 → (2, 6)
c = torch.stack([a, b], dim=0) # 新维度堆叠 → (2, 2, 3)
# 分割
chunks = torch.chunk(x, chunks=3, dim=1) # 均分为 3 块
parts = torch.split(x, split_size_or_sections=2, dim=0) # 每块 2 行
↔️ NumPy 互转
# Tensor → NumPy
x = torch.randn(3, 4)
arr = x.numpy() # CPU 上直接转换(共享内存!)
arr = x.cpu().detach().numpy() # GPU 张量安全转换
# NumPy → Tensor
arr = np.array([1, 2, 3])
x = torch.from_numpy(arr) # 共享内存
x = torch.tensor(arr) # 复制一份新数据
⚠️
torch.from_numpy()和张量调用.numpy()是共享内存的,改一个另一个也会变!
🖥️ 设备管理
# 查看可用设备
print(torch.cuda.is_available()) # 是否有 GPU
print(torch.cuda.device_count()) # GPU 数量
# 创建时指定设备
x = torch.randn(3, 4, device='cuda') # 直接在 GPU 上创建
x = torch.randn(3, 4, device='cuda:0') # 指定 GPU 编号
# 移动张量
x = x.to('cuda') # 移到 GPU
x = x.cuda() # 同上
x = x.to('cpu') # 移回 CPU
x = x.cpu() # 同上
# 设备无关代码
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
x = torch.randn(3, 4).to(device)
📝 速查表
| 需求 | 代码 |
|---|---|
| 创建列表张量 | torch.tensor([1, 2, 3]) |
| 全零 | torch.zeros(3, 4) |
| 全一 | torch.ones(3, 4) |
| 标准正态随机 | torch.randn(3, 4) |
| 均匀随机 | torch.rand(3, 4) |
| 等差数列 | torch.arange(0, 10, 2) |
| 等分数列 | torch.linspace(0, 1, 10) |
| 矩阵乘法 | A @ B |
| 转置 | x.T / x.transpose(0, 1) |
| 改变形状 | x.view(-1, 4) / x.reshape(6, 4) |
| 插入维度 | x.unsqueeze(0) |
| 删除1维 | x.squeeze() |
| 展平 | x.flatten() |
| 拼接 | torch.cat([a, b], dim=0) |
| 堆叠 | torch.stack([a, b], dim=0) |
| 沿轴求和 | x.sum(dim=0) |
| NumPy→Tensor | torch.from_numpy(arr) |
| Tensor→NumPy | x.numpy() |
| 移到GPU | x.to('cuda') |
| 数据类型 | x.float() / x.long() |
[[pytorch-总览|← 返回总览]]
更多推荐



所有评论(0)