1、張量的操作匯總
下面是 PyTorch 中常見的 張量操作方法匯總,包括 創建、索引、變換、數學運算、廣播機制、維度操作 等內容,并附上詳解和代碼示例,便于系統學習與實戰參考。
一、張量創建(torch.tensor
等)
import torch# 標量(0維張量)
a = torch.tensor(3.14)# 1維張量
b = torch.tensor([1.0, 2.0, 3.0])# 2維張量
c = torch.tensor([[1, 2], [3, 4]])# 全 0 / 全 1
zeros = torch.zeros((2, 3))
ones = torch.ones((3, 3))# 均勻分布隨機數
rand = torch.rand((2, 2))# 正態分布
normal = torch.randn(2, 3)# 固定范圍整數
int_rand = torch.randint(0, 10, (3, 3))
二、張量屬性(維度、形狀、類型)
x = torch.rand(2, 3)print(x.shape) # torch.Size([2, 3])
print(x.dtype) # torch.float32
print(x.ndim) # 2
print(x.size()) # same as x.shape
三、索引與切片(Indexing & Slicing)
x = torch.tensor([[1, 2, 3], [4, 5, 6]])print(x[0]) # 第0行 [1, 2, 3]
print(x[:, 1]) # 所有行的第1列 [2, 5]
print(x[1, 2]) # 第1行第2列 -> 6# 修改元素
x[0, 1] = 10
四、形狀變換(Reshape)
x = torch.arange(12) # [0, 1, ..., 11]
x = x.view(3, 4) # reshape 為 (3,4)x = x.reshape(2, 6) # reshape 新形狀
x = x.flatten() # 轉為 1D
x = x.unsqueeze(0) # 增加一維 (batch-like)
x = x.squeeze() # 去除多余維度
五、數學運算
元素級運算(+,-,*,/)
a = torch.tensor([1., 2., 3.])
b = torch.tensor([4., 5., 6.])print(a + b)
print(a * b)
print(torch.exp(a))
print(torch.sqrt(b))
矩陣運算
A = torch.tensor([[1., 2.], [3., 4.]])
B = torch.tensor([[5., 6.], [7., 8.]])# 點積/矩陣乘法
print(torch.matmul(A, B)) # 或 A @ B
六、廣播機制(Broadcasting)
a = torch.tensor([[1], [2], [3]]) # shape (3,1)
b = torch.tensor([10, 20, 30]) # shape (3,)# 廣播加法 => shape (3,3)
print(a + b)
七、維度操作:拼接、拆分、轉置
a = torch.ones((2, 3))
b = torch.zeros((2, 3))# 拼接
cat = torch.cat([a, b], dim=0) # shape (4, 3)# 拆分
split = torch.split(cat, 2, dim=0) # 拆成兩個 (2,3)# 轉置
x = torch.rand(2, 3)
print(x.T) # shape (3,2)
八、常用統計操作
x = torch.tensor([[1., 2.], [3., 4.]])print(x.sum()) # 所有元素求和
print(x.mean()) # 平均值
print(x.max(), x.min()) # 最大最小值
print(x.argmax(), x.argmin()) # 最大/最小索引
九、條件與掩碼操作(布爾索引)
x = torch.tensor([1, 2, 3, 4, 5])
mask = x > 3
print(x[mask]) # 輸出 [4, 5]
十、張量復制與共享
a = torch.tensor([1, 2, 3])
b = a.clone() # 拷貝,不共享內存
c = a # 共享內存
總結思維導圖(簡要)
張量操作:
├── 創建(tensor, zeros, randn, randint)
├── 屬性(shape, dtype, ndim)
├── 索引(x[i], x[:, j])
├── 運算(+ - * /, matmul, exp, log)
├── 廣播(自動擴展維度)
├── 變換(view, reshape, squeeze, unsqueeze)
├── 拼接/分割(cat, stack, split, chunk)
├── 統計分析(sum, mean, max, argmax)
├── 條件掩碼(mask, where)
└── 復制(clone, detach)
2、張量屬性匯總
PyTorch 中張量(Tensor)是數據的基本結構。每個張量都具有一組屬性(Attributes)來描述它的維度、數據類型、設備、存儲結構等信息。
張量的核心屬性匯總
屬性名 | 含義說明 | 示例值 |
---|---|---|
.shape / .size() | 張量的形狀(各維度大小) | torch.Size([3, 4]) |
.ndim | 張量的維度數(維度的數量) | 2 |
.dtype | 數據類型 | torch.float32 |
.device | 存儲設備:CPU 或 GPU | cpu , cuda:0 |
.requires_grad | 是否記錄梯度(用于自動求導) | True/False |
.is_leaf | 是否是葉子節點(可用于反向傳播分析) | True/False |
.grad | 梯度值(反向傳播后賦值) | None 或張量 |
.data | 原始數據(無梯度跟蹤) | 張量數據 |
.T | 轉置(僅適用于二維張量) | tensor.T |
.storage() | 存儲對象(高級屬性) | FloatStorage |
示例代碼:張量屬性全面演示
import torch# 創建張量
a = torch.randn(3, 4, dtype=torch.float32, requires_grad=True)print("張量 a:\n", a)
print("\n== 張量屬性 ==")
print("形狀 shape:", a.shape)
print("維度 ndim:", a.ndim)
print("數據類型 dtype:", a.dtype)
print("所在設備 device:", a.device)
print("是否需要梯度 requires_grad:", a.requires_grad)
print("是否為葉子節點 is_leaf:", a.is_leaf)
print("梯度 grad:", a.grad)
print("原始數據 data:\n", a.data)
print("轉置 T:\n", a.T)
print("存儲 storage:", a.storage())
進階示例:查看 GPU 張量屬性 + 修改屬性
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")b = torch.ones((2, 3), dtype=torch.float64, device=device)
print("\n張量 b 屬性:")
print("b.shape:", b.shape)
print("b.dtype:", b.dtype)
print("b.device:", b.device)# 修改數據類型和設備
b2 = b.to(dtype=torch.float32, device='cpu')
print("\n修改后:")
print("b2.dtype:", b2.dtype)
print("b2.device:", b2.device)
示例:grad 與 requires_grad 的關系
x = torch.tensor([1.0, 2.0, 3.0], requires_grad=True)
y = x ** 2
z = y.sum()print("z:", z)
z.backward()
print("x.grad:", x.grad) # dz/dx = 2x
Tips
.shape
和.size()
等價,都返回torch.Size
對象。.is_leaf
為 True 的張量通常是直接創建的變量,反向傳播時只保留其梯度。.data
會返回張量本身的數據,但不參與自動求導。