Torch 自称为神经网络界的 Numpy,因为它能将 torch 产生的 tensor 放在 GPU 中加速运算 (前提是你有合适的 GPU), 就像 Numpy 会把 array 放在 CPU 中加速运算。所以神经网络的话, 当然是用 Torch 的 tensor 形式数据最好咯。就像 Tensorflow 当中的 tensor 一样。当然,我们对 Numpy 还是爱不释手的,因为我们太习惯 numpy 的形式了。不过 torch 看出来我们的喜爱,它把 torch 做的能与 numpy 很好的兼容。比如:
No.1 自由地转换 numpy array 和 torch tensor :
import torch
import numpy as np
np_data = np.arange(8).reshape((2,4))
torch_data = torch.from_numpy(np_data)
tensor2arry = torch_data.numpy()
print(
'\nnp_data:',np_data,
'\ntorch_data',torch_data,
'\tensor2arry',tensor2arry,
)
运行结果:
np_data: [[0 1 2 3]
[4 5 6 7]]
torch_data tensor([[0, 1, 2, 3],
[4, 5, 6, 7]], dtype=torch.int32) ensor2arry [[0 1 2 3]
[4 5 6 7]]
No.2 Torch中的数学运算:
其实 torch 中 tensor 的运算和 numpy array 的如出一辙,我们就以对比的形式来看。
# abs 绝对值计算
data = [-1, -2, 1, 2]
tensor = torch.FloatTensor(data) # 转换成32位浮点 tensor
print(
'\nabs',
'\nnumpy: ', np.abs(data),
'\ntorch: ', torch.abs(tensor)
)
# sin 三角函数 sin
print(
'\nsin',
'\nnumpy: ', np.sin(data),
'\ntorch: ', torch.sin(tensor)
)
# mean 均值
print(
'\nmean',
'\nnumpy: ', np.mean(data),
'\ntorch: ', torch.mean(tensor)
)
运行结果:
abs
numpy: [1 2 1 2]
torch: tensor([1., 2., 1., 2.])
sin
numpy: [-0.84147098 -0.90929743 0.84147098 0.90929743]
torch: tensor([-0.8415, -0.9093, 0.8415, 0.9093])
mean
numpy: 0.0
torch: tensor(0.)
除了简单的计算, 矩阵运算才是神经网络中最重要的部分,所以我们展示下矩阵的乘法。注意一下包含了一个 numpy 中可行, 但是 torch 中不可行的方式。
# matrix multiplication 矩阵乘法
data = [[1,2], [3,4]]
tensor = torch.FloatTensor(data) #转换成32位浮点 tensor
# correct method
print(
'\矩阵乘法 (matmul)',
'\nnumpy: ', np.matmul(data, data),
'\ntorch: ', torch.mm(tensor, tensor)
)
运行结果:
\矩阵乘法 (matmul)
numpy: [[ 7 10]
[15 22]]
torch: tensor([[ 7., 10.],[15., 22.]])
Numpy 中文参考手册:https://www.numpy.org.cn/index.html