NumPy和Torch对比
- NumPy中ndarray和Torch中tensor的相互转化
# NumPy中ndarray和Torch中tensor的相互转化
numpyData = numpy.arange(6).reshape(2, 3)
# ndarray到tensor
torchData = torch.from_numpy(numpyData)
# tensor到ndarray
tensor2array = torchData.numpy()
print(
"\nnumpy array:\n", numpyData,
"\ntorch tensor:\n", torchData,
"\ntensor to array\n", tensor2array
)
运行结果
numpy array:
[[0 1 2]
[3 4 5]]
torch tensor:
tensor([[0, 1, 2],
[3, 4, 5]])
tensor to array
[[0 1 2]
[3 4 5]]
- 数学运算
- 绝对值
# 绝对值计算abs
data = [-1, -2, 1, 2]
tensor = torch.FloatTensor(data) # 32位
print(
'\nabs',
'\nnumpy:\n', numpy.abs(data),
'\ntorch:\n', torch.abs(tensor)
)
运行结果
abs
numpy:
[1 2 1 2]
torch:
tensor([1., 2., 1., 2.])
- sin
# 三角函数sin
print(
'\nsin',
'\nnumpy:\n', numpy.sin(data),
'\ntorch:\n', torch.sin(tensor)
)
运行结果
sin
numpy:
[-0.84147098 -0.90929743 0.84147098 0.90929743]
torch:
tensor([-0.8415, -0.9093, 0.8415, 0.9093])
- 平均值
# 平均值
print(
'\nmean',
'\nnumpy:\n', numpy.mean(data),
'\ntorch:\n', torch.mean(tensor)
)
运行结果
mean
numpy:
0.0
torch:
tensor(0.)
- 矩阵乘法
# 矩阵乘法
data = [[1, 2],
[3, 4]]
tensor = torch.FloatTensor(data)
print(
'\n叉乘',
'\nnumpy:\n', numpy.matmul(data, data),
'\ntorch:\n', torch.mm(tensor, tensor)
)
print(
'\n点乘',
'\nnumpy:\n', numpy.multiply(data, data),
'\ntorch:\n', torch.mul(tensor, tensor)
)
运行结果
叉乘
numpy:
[[ 7 10]
[15 22]]
torch:
tensor([[ 7., 10.],
[15., 22.]])
点乘
numpy:
[[ 1 4]
[ 9 16]]
torch:
tensor([[ 1., 4.],
[ 9., 16.]])