注意广播的计算:
#coco
#广播机制
import torch
import numpy as np
A = np.arange(0, 40, 10).reshape(4, 1)
print(A)
# [[ 0]
# [10]
# [20]
# [30]]
B = np.arange(0, 3)
print(B)
# [0 1 2]
# 把ndarray转换为Tensor
A1 = torch.from_numpy(A) # 形状为4x1
print(A1)
# tensor([[ 0],
# [10],
# [20],
# [30]], dtype=torch.int32)
B1 = torch.from_numpy(B) # 形状为3
print(B1)
# tensor([0, 1, 2], dtype=torch.int32)
# Tensor自动实现广播
C = A1 + B1
print(C)
# tensor([[ 0, 1, 2],
# [10, 11, 12],
# [20, 21, 22],
# [30, 31, 32]], dtype=torch.int32)
# 我们可以根据广播机制,手工进行配置
# 根据规则1,B1需要向A1看齐,把B变为(1,3)
B2 = B1.unsqueeze(0) # B2的形状为1x3
print(B2)
# tensor([[0, 1, 2]], dtype=torch.int32)
# 使用expand函数重复数组,分别的4x3的矩阵
A2 = A1.expand(4, 3)
print(A2)
# tensor([[ 0, 0, 0],
# [10, 10, 10],
# [20, 20, 20],
# [30, 30, 30]], dtype=torch.int32)
B3 = B2.expand(4, 3)
print(B3)
# tensor([[0, 1, 2],
# [0, 1, 2],
# [0, 1, 2],
# [0, 1, 2]], dtype=torch.int32)
# 然后进行相加,C1与C结果一致
C1 = A2 + B3
做不到的话,就做到能做到为止;做到后,就继续做到完美为 止;做到完美之后,就继续做到无论做几次都能完美为止。
——羽生结弦