标签:pytorch、tensor、张量、cuda
前言
在PyTorch中,所有神经网络的输入、权重、梯度,全部都是Tensor(张量) 。
可以简单理解:
- 0维张量:标量(单个数字)
- 1维张量:向量(一维数组)
- 2维张量:矩阵(二维数组)
- 3维/4维张量:深度学习最常用,比如图像
[N, C, H, W]批次、通道、高、宽
一、导入包
python
import torch
二、张量的创建方式
1. 直接从列表创建
python
# 一维
t1 = torch.tensor([1,2,3])
# 二维
t2 = torch.tensor([[1,2],[3,4]])
print(t1)
print(t2)
2. 创建特殊张量
python
# 全0
t_zeros = torch.zeros(2,3)
# 全1
t_ones = torch.ones(2,3)
# 随机 [0,1)
t_rand = torch.rand(2,3)
# 标准正态分布(均值0,方差1)
t_randn = torch.randn(2,3)
# 单位矩阵
t_eye = torch.eye(3)
3. 从numpy数组转换
python
import numpy as np
arr = np.array([1,2,3])
t = torch.from_numpy(arr)
# 张量转numpy
arr2 = t.numpy()
⚠️ 注意:共享内存,一方修改另一方也会变。
三、张量的属性(重点)
python
t = torch.rand(2,3)
print(t.shape) # 形状,推荐用这个
print(t.size()) # 和shape等价
print(t.dtype) # 数据类型
print(t.device) # 所在设备 cpu / cuda:0
常用dtype
| 类型 | 说明 |
|---|---|
| torch.float32 / torch.float | 浮点,模型训练默认 |
| torch.float64 / torch.double | 双精度,很少用 |
| torch.int64 / torch.long | 长整型,索引、标签常用 |
| torch.int32 / torch.int | 普通int |
指定类型创建:
python
t = torch.tensor([1,2,3], dtype=torch.float32)
四、CPU / GPU 设备切换
python
# 方式1 .to()
t = torch.tensor([1,2,3])
if torch.cuda.is_available():
t = t.to("cuda")
# 切回cpu
t = t.to("cpu")
# 方式2 .cuda() / .cpu()
if torch.cuda.is_available():
t = t.cuda()
t = t.cpu()
坑:CPU张量和GPU张量不能直接运算!
五、基础运算
python
a = torch.tensor([1,2,3])
b = torch.tensor([4,5,6])
print(a + b)
print(a - b)
print(a * b) # 逐元素相乘,不是矩阵乘法
print(a / b)
# 矩阵乘法 @ / matmul
m1 = torch.rand(2,3)
m2 = torch.rand(3,4)
res = m1 @ m2
# res = torch.matmul(m1, m2)
六、形状修改 view / reshape
python
t = torch.rand(6)
t2 = t.view(2,3)
t3 = t.reshape(3,2)
view要求内存连续;reshape更通用,优先记住reshape。
七、索引和切片(和numpy类似)
python
t = torch.rand(3,4)
print(t[0]) # 第0行
print(t[:,0]) # 所有行,第0列
print(t[1:3,:]) # 1~2行,所有列
八、小结
- Tensor是PyTorch的基础单元,神经网络所有数据都是张量
- 核心属性:
shape、dtype、device - 运算默认逐元素 ,矩阵乘法用
@/matmul - 张量分CPU/GPU,跨设备不能直接计算