1、創建tensor
??常見創建 tensor 的方法
函數 | 作用 |
torch.Tensor(*size) | 通過指定尺寸,生成一個 值全為 0 的 tensor |
torch.tensor(*list) | 直接通過指定數據,生成tensor,支持 List、Numpy數組 |
torch.eye(row, column) | 按照指定的行列數,生成二維單位tensor |
torch.rand(*size) | 從 (0, 1) 之間,進行均勻分布采樣,生成指定size 的tensor |
torch.randn(*size) | 從標準正態分布中采樣,生成指定size 的tensor |
torch.ones(*size) | 按照指定 size,生成 值全為1 的 tensor |
torch.zeros(*size) | 按照指定 size,生成 值全為0 的 tensor |
torch.ones_like(t) | 返回尺寸與 t 相同的,值全為1 的 tensor |
torch.zeros_like(t) | 返回尺寸與 t 相同的,值全為0 的 tensor |
torch.arange(start, end, step) | 在區間[start, end) 上,每間隔 step 生成一個序列張量 |
torch.linspace(start, end, steps) | 從 start 到 end,均勻切分成 steps 份 |
torch.from_Numpy(ndarray) | 根據 ndarray 生成 tensor |
??你可以將如下生成的 tensor,逐個打印,進行觀察
import numpy as np
import torcha = torch.Tensor(2, 3)
b = torch.tensor([[1, 2, 3], [4, 5, 6]])c = torch.eye(3, 3)d = torch.rand(2, 3)
e = torch.randn(2, 3)f = torch.ones(3, 2)
g = torch.zeros(2, 3)
h = torch.ones_like(b)
i = torch.zeros_like(b)j = torch.linspace(1, 10, 4)
k = torch.arange(1, 5, 2)l = np.arange(1, 5)
m = torch.from_numpy(l)
2、查看 tensor 的形狀
函數 | 作用 |
tensor.numel() | 統計 tensor 元素的個數 |
tensor.size() | 獲取 tensor的尺寸, |
tensor.shape | 獲取 tensor的尺寸, |
import torcha = torch.tensor([[1, 2, 3], [4, 5, 6]])
print(a.numel())
print(a.size())
print(a.shape)
?
3、修改 tensor 形狀
函數 | 作用 |
tensor.view(*size) | 修改 tensor 的尺寸,返回的對象 與 源tensor 共享內存(修改一個,另一個也會被修改) |
tensor.resize(*size) | 修改 tensor 的尺寸,類似于view,但在size 超出時會重新分配內存空間 |
tensor.reshape(*size) | 修改 tensor 的尺寸,返回的對象是一個新生成的tensor,且不要求源tensor 是連續的 |
tensor.flatten() | 將張量扁平化為一維張量 |
torch.unsqueeze(dim) | 在指定維度增加一個 “1” |
torch.squeeze(dim) | 在指定維度刪除一個 “1” |
tensor.transpose(dim0, dim1) | 交換 dim0 和 dim1 指定的兩個維度,返回一個新的張量而不修改原始張量 |
tensor.permute(dims) | 按照 dims 指定的順序重新排列張量的維度,返回一個新的張量而不修改原始張量 |
import torcha = torch.tensor([[1, 2, 3], [4, 5, 6]])print(a.view(3, 2))
print(a.resize(3, 2))
print(a.reshape(3, 2))
print(a.flatten())
import torcha = torch.tensor([[[1, 2, 3], [4, 5, 6]]])
print(a.shape)b = torch.unsqueeze(a, 0)
print(b.shape)c = torch.squeeze(b, 0)
print(c.shape)
?
import torcha = torch.tensor([[1, 2, 3], [4, 5, 6]])
b = a.transpose(dim0=0, dim1=1)
print(a.shape)
print(b.shape)c = torch.tensor([[[1, 2, 2], [3, 4, 3]]])
d = c.permute(1, 2, 0)
print(c.shape)
print(d.shape)
4、按條件篩選
函數 | 作用 |
torch.index_select(input, dim, index) | 從輸入張量中按索引選擇某些元素 |
torch.nonzero(input) | 獲取張量中非零元素的索引 |
torch.masked_select(input, masked) | 根據掩碼(mask)從輸入張量中選擇元素 |
torch.gather(input, dim, index) | 在指定維度上根據索引從輸入張量中選擇元素 |
torch.scatter(input, dim, index, src) | 在指定維度(dim)上根據指定的索引(index),將源張量(src)的值散射到目標張量(input)中 |
?1)index_select
torch.index_select(input, dim, index)
: 從輸入張量中按索引選擇某些元素,并返回一個新的張量
import torchtensor = torch.tensor([[1, 2, 3],[4, 5, 6],[7, 8, 9]])# 創建一個要選擇的索引張量
indices = torch.tensor([0, 2])# 在第0維上使用index_select選擇索引為0和2的行
selected_rows = torch.index_select(tensor, 0, indices)print("Selected rows:\n", selected_rows)
2)nonzero
torch.nonzero(input)
: 獲取張量中非零元素的索引
import torchtensor = torch.tensor([[0, 1, 0],[2, 0, 3],[0, 4, 0]])# 獲取非零元素的索引
nonzero_indices = torch.nonzero(tensor)
print("Non-zero indices:\n", nonzero_indices)
?
3)masked_select
torch.masked_select(input, masked)
: 根據掩碼(mask)從輸入張量中選擇元素
import torch# 創建一個示例張量
input_tensor = torch.tensor([[1, 2, 3],[4, 5, 6],[7, 8, 9]])# 創建一個掩碼張量
mask_tensor = torch.tensor([[0, 1, 0],[1, 0, 1],[0, 1, 0]], dtype=torch.bool)# 使用掩碼選擇張量中的元素
selected_tensor = torch.masked_select(input_tensor, mask_tensor)
print("Selected tensor:\n", selected_tensor)
4)gather
torch.gather(input, dim, index)
: 在指定維度上根據索引從輸入張量中選擇元素。若 dim=n :
-
要求除了第n個維度,input_tensor 和 index_tensor 其他維度數量一致
-
在第n個維度上,通過 index_tensor 指定的索引,從 input_tensor 中取出對應位置的元素。
import torch# 創建一個示例張量
input_tensor = torch.tensor([[1, 2, 3],[4, 5, 6],[7, 8, 9]])# 創建一個示例索引張量
index_tensor = torch.tensor([[0, 2],[1, 0],[2, 1]])# 在第1維度上使用索引張量收集值
gathered_tensor = torch.gather(input_tensor, 1, index_tensor)print("Gathered tensor:\n", gathered_tensor)
?
5)scatter
torch.scatter(input, dim, index, src)
:在指定維度(dim)上根據指定的索引(index),將源張量(src)的值放到目標張量(input)中
-
src 的形狀 和 index的形狀 必須保持一致,否則會報錯
import torch# 創建一個示例目標張量
input_tensor = torch.zeros((4, 4), dtype=torch.int32)# 創建一個示例索引張量
index_tensor = torch.tensor([[0, 1],[2, 3]], dtype=torch.long)# 創建一個示例源張量
src_tensor = torch.tensor([[1, 2],[3, 4]], dtype=torch.int32)# 在第1維度上使用索引張量散射值
scattered_tensor = torch.scatter(input_tensor, 1, index_tensor, src_tensor)
print("Scattered tensor:\n", scattered_tensor)
?
No. 1
-
src_tensor 第0行第0列的值為“1”
-
index_tensor 第0行第0列的值為“0”, dim=1 表示 “0” 是列索引
-
將 “1” 放到 input_tensor 中,對應行第“0”列的位置上
No. 2
-
src_tensor 第0行第1列的值為“2”,
-
index_tensor 第0行第1列的值為“1”,dim=1 表示 “1” 是列索引
-
將 “2” 放到 input_tensor 中,對應行第“1”列的位置上
No. 3
-
src_tensor 第1行第0列的值為“3”,
-
index_tensor 第1行第0列的值為“2”,dim=1 表示 “2” 是列索引
-
將 “3” 放到 input_tensor 中,對應行第“2”列的位置上
No. 4
-
src_tensor 第1行第1列的值為“4”,
-
index_tensor 第1行第1列的值為“3”,dim=1 表示 “3” 是列索引
-
將 “4” 放到 input_tensor 中,對應行第“3”列的位置上
5、運算操作
函數 | 作用 |
torch.abs() | 取絕對值 |
torch.add() | 相加 |
torch.addcdiv(input, tensor1, tensor2, value) | result =input + value * tensor1 / tensor2 |
torch.addcmul(input, tensor1, tensor2, value) | result =input + value * tensor1 * tensor2 |
torch.ceil() | 向上取整 |
torch.floor() | 向下取整 |
torch.clamp(input, min, max) | 對張量的元素進行截斷操作,將超出指定范圍的元素限制在指定范圍內 |
torch.exp() / torch.log() / torch.pow | 指數 / 對數 / 冪 |
torch.mul() | 逐元素乘法,效果和 * 一樣 |
torch.neg() | 取反 |
torch.sqrt() | 開根號 |
torch.sign() | 取符號 |
?1)abs
import torchx = torch.arange(-5, 5)
y = torch.abs(x)
print(y)
2)add
import torchx = torch.arange(2, 5)
y = torch.arange(4, 7)
z = torch.add(x, y)
print(z)
?
3)addcdiv
??torch.addcdiv(input, tensor1, tensor2, value)
result =input + value * tensor1 / tensor2
import torcht = torch.randn(1, 3)
t1 = torch.randn(3, 1)
t2 = torch.randn(1, 3)a = t + 0.1 *(t1 / t2)
print(a)b = torch.addcdiv(t, t1, t2, value=0.1)
print(b)
?
4)addcmul
torch.addcmul(input, tensor1, tensor2, value)
result =input + value * tensor1 * tensor2
import torcht = torch.randn(1, 3)
t1 = torch.randn(3, 1)
t2 = torch.randn(1, 3)a = t + 0.1 * t1 * t2
print(a)b = torch.addcmul(t, t1, t2, value=0.1)
print(b)
?
5)ceil、floor
-
torch.ceil(input) :向上取整
-
torch.floor(input) :向下取整
import torchtorch.manual_seed(8)
x = torch.randn(3) * 10
y = torch.ceil(x)
z = torch.floor(x)
print(x)
print(y)
print(z)
6)clamp
??將張量元素大小限制在指定區間范圍內
import torchx = torch.arange(1, 8)
y = torch.clamp(x, 2, 5)
print(y)
?
7)exp、log、pow
import torchtorch.manual_seed(8)
x = torch.arange(3)
print(x)
print(torch.exp(x))
print(torch.log(x)) # 以e為底
print(torch.pow(x, 3))
8)mul
??逐元素乘法,效果和 * 一樣
import torcha = torch.tensor([[2, 2, 2],[2, 3, 4]])b = torch.tensor([[3, 3, 3],[4, 5, 6]])print(torch.mul(a,b))
print(a*b)
?
9)neg、sqrt、sign
-
torch.neg() 取反
-
torch.sqrt() 開根號
-
torch.sign() 取符號
import torcha = torch.tensor([[2, -2, 2], [2, -3, 4]])print(torch.neg(a)) print(torch.sqrt(a))print(torch.sign(a))
6、統計操作
函數 | 作用 |
torch.sum() / torch.prod() | 求和 / 求積 |
torch.cumsum() / torch.cumprod() | 在指定維度上進行累加 / 在指定維度上進行累乘 |
torch.mean()、torch.median() | 均值 / 中位數 |
torch.std() / torch.var() | 標準差 / 方差 |
torch.norm(t, p) | t 的 p階范數 |
torch.dist(a, b, p) | a,b 之間的 p階范數 |
1)sum、prod、cumsum、cumprod
import torcha = torch.linspace(0, 10, 6).view(2, 3)
print(a)b = a.sum(dim=0)
c = torch.cumsum(a, dim=0)
print('\n維度0上求和 與 累加')
print(b)
print(c)d = a.prod(dim=1)
e = torch.cumprod(a, dim=1)
print('\n維度0上求積 與 累積')
print(d)
print(e)
?
2)mean、median
import torcha = torch.tensor([[2., 2., 5.],[3., 3., 8.],[4., 4., 4.]])print('求均值')
print(torch.mean(a))
print(torch.mean(a, 0))
print(torch.mean(a, 1))print('\n求中位數')
print(torch.median(a))
print(torch.median(a, 0))
print(torch.median(a, 1))
3)std、var
import torch# 創建示例張量
a = torch.tensor([[1.0, 2.0],[3.0, 4.0]])# 計算張量的標準差
std_value = torch.std(a)
print("Standard deviation:", std_value)# 計算張量的方差
var_value = torch.var(a)
print("Variance:", var_value)
?
4)norm、dist
-
torch.norm(t, p)
:t 的 p階范數 -
torch.dist(a, b, p)
:a,b 之間的 p階范數
import torch# 創建示例張量
tensor1 = torch.tensor([1.0, 2.0, 3.0])
tensor2 = torch.tensor([4.0, 5.0, 6.0])# 使用 torch.norm() 計算張量的范數
norm_value = torch.norm(tensor1)
print("tensor1 的L2范數:", norm_value)# 使用 torch.dist() 計算兩個張量的范數
dist_value = torch.dist(tensor1, tensor2)
print("tensor1 和 tensor2 之間的L2范數:", dist_value)
7、比較操作
函數 | 作用 |
torch.eq | 比較 tensor 是否相等 (支持 broadcast) |
torch.equal | 比較 tensor 是否有相同的 shape 與 值 |
torch.gt / torch.lt | 大于 / 小于 gt : great than ; lt : less than |
torch.ge / torch.le | 大于等于 / 小于等于 ge : greater than or equal to ; le : less than or equal to |
torch.max / torch.min(t,axis) | 最大值 / 最小值 |
torch.topk(t, k, axis) | 在指定維度上(axis)取最高的 k個值 |
?1)eq、 equal
import torch# 示例張量
t = torch.tensor([[1, 2, 3],[4, 5, 6]])# 使用eq()比較張量中的元素是否等于2
result_eq = torch.eq(t, 2)
print("Result of eq():\n", result_eq)# 使用equal()比較兩個張量是否相等
t1 = torch.tensor([[1, 2, 3],[4, 5, 6]])
t2 = torch.tensor([[1, 2, 3],[4, 5, 6]])
result_equal = torch.equal(t1, t2)
print("\nResult of equal():", result_equal)
2)gt、 lt、ge、 le
import torch# 示例張量
t = torch.tensor([[1, 2, 3],[4, 5, 6]])# 使用gt()比較張量中的元素是否大于3
result_gt = torch.gt(t, 3)
print("Result of gt():\n", result_gt)# 使用lt()比較張量中的元素是否小于3
result_lt = torch.lt(t, 3)
print("\nResult of lt():\n", result_lt)# 使用gt()比較張量中的元素是否大于等于3
result_ge = torch.ge(t, 3)
print("\nResult of ge():\n", result_ge)# 使用le()比較張量中的元素是否小于等于3
result_le = torch.le(t, 3)
print("\nResult of le():\n", result_le)
?
3)max、min
import torch# 示例張量
t = torch.tensor([[1, 2, 3],[4, 5, 6]])# 計算張量的最大值和最小值
max_value = torch.max(t)
min_value = torch.min(t)
print("Max value:", max_value)
print("Min value:", min_value)# 沿著指定維度計算張量的最大值和最小值
max_value_axis_0 = torch.max(t, axis=0)
min_value_axis_1 = torch.min(t, axis=1)
print("\n沿0維上的最大值:", max_value_axis_0.values)
print("沿0維上的最大值索引:", max_value_axis_0.indices)
print("沿1維上的最小值:", min_value_axis_1.values)
print("沿1維上的最小值索引:", min_value_axis_1.indices)
4)topk
import torch# 示例張量
t = torch.tensor([[1, 2, 3],[4, 5, 6]])# 沿著指定維度獲取張量中最大的兩個值及其索引
topk_values, topk_indices = torch.topk(t, k=2, dim=1)
print("沿維度1上的最大的2個值:\n", topk_values)
print("\n沿維度1上的最大的2個值的索引:\n", topk_indices)
?
8、矩陣操作
函數 | 作用 |
torch.dot(t1, t2) | 計算 1維張量的內積或點積 |
torch.mul(t1, t2) | 逐元素相乘 |
torch.mm(t1, t2) / torch.mv(t, v) | 計算矩陣乘法 / 計算矩陣t與向量v 的乘法 |
bmm | 含 batch 的 3D 矩陣乘法 |
svd | 計算 t 的 SVD分解 |
?1)dot
??Torch的 dot 只能對兩個 一維張量 進行點積運算,否則會報錯;Numpy中的dot無此限制。
import torcha = torch.tensor([2, 3])
b = torch.tensor([3, 4])print(torch.dot(a, b))
import torcha = torch.tensor([[2, 3],[3, 4]])b = torch.tensor([[3, 4],[1, 2]])print(torch.dot(a, b))
2)mul
-
a 和 b 必須尺寸相同。
-
torch.mul(a, b) 和 a * b 效果一樣
-
torch.mul(a, b) 是逐元素相乘,torch.mm(a, b) 是矩陣相乘
import torcha = torch.tensor([[2, 3],[3, 4]])b = torch.tensor([[3, 4],[1, 2]])print(torch.mul(a, b))
print(a * b)
print(torch.mm(a, b))
?
3)mm、mv
-
torch.mm(t1, t2) 是矩陣相乘, torch.mv(t, v) 矩陣與向量乘法
-
torch.mv(t, v) , 矩陣t為第一個參數,向量v為第二個參數,位置不能換,否則會報錯
import torcha = torch.tensor([[1, 2, 3],[2, 3, 4]])b = torch.tensor([[1, 2],[1, 2],[3, 4]])c = torch.tensor([1, 2, 3])print(torch.mm(a, b))
print(torch.mv(a, c))
?
4)bmm?
import torchbatch1 = torch.tensor([[[1, 2], [3, 4]], [[5, 6], [7, 8]]], dtype=torch.float32) # Shape: (2, 2, 2)
batch2 = torch.tensor([[[2, 0], [0, 2]], [[1, 0], [0, 1]]], dtype=torch.float32) # Shape: (2, 2, 2)result = torch.bmm(batch1, batch2)
print("Result:\n", result)
5)svd
import torcha = torch.randn(2, 3)
print(torch.svd(a))