Torch或Numpy

1.什么是Numpy
Numpy系统是Python的一种开源的数值计算扩展,用python实现的科学计算包。这种工具可用来存储和处理大型矩阵,包括强大的N维数组对象Array,比较成熟的函数库等。numpy和稀疏矩阵运算包scipy配合使用更加方便。

2.用Numpy还是Torch
Torch自称为神经网络界的Numpy,它能将torch产生的tensor放在GPU中加速运算,就想Numpy会把array放在CPU中加速运算。所以在神经网络中,用Torch的tensor形式更优。

但是为了减少用户的学习成本,Torch对Numpy实现了很好的兼容。可以用如下形式在numpy array和torch tensor之间自由转换。

import torch
import numpy as np

np_data = np.arange(6).reshape((2, 3))
torch_data = torch.from_numpy(np_data)
tensor2array = torch_data.numpy()
print(
'\nnumpy array:', np_data, # [[0 1 2], [3 4 5]]
'\ntorch tensor:', torch_data, # 0 1 2 \n 3 4 5 [torch.LongTensor of size 2x3]
'\ntensor to array:', tensor2array, # [[0 1 2], [3 4 5]]
)

3.Torch中的数学运算

torch中的tensor运算和numpy的array运算很相似,具体参看下面的代码:

# abs 绝对值计算
data = [-1, -2, 1, 2]
tensor = torch.FloatTensor(data) # 转换成32位浮点 tensor
print(
'\nabs',
'\nnumpy: ', np.abs(data), # [1 2 1 2]
'\ntorch: ', torch.abs(tensor) # [1 2 1 2]
)

# sin 三角函数 sin
print(
'\nsin',
'\nnumpy: ', np.sin(data), # [-0.84147098 -0.90929743 0.84147098 0.90929743]
'\ntorch: ', torch.sin(tensor) # [-0.8415 -0.9093 0.8415 0.9093]
)

# mean 均值
print(
'\nmean',
'\nnumpy: ', np.mean(data), # 0.0
'\ntorch: ', torch.mean(tensor) # 0.0
)

numpy和torch的矩阵乘法还是有点不同的,下面将对其区别进行展示:

扫描二维码关注公众号,回复: 5258071 查看本文章

# matrix multiplication 矩阵点乘
data = [[1,2], [3,4]]
tensor = torch.FloatTensor(data) # 转换成32位浮点 tensor
# correct method
print(
'\nmatrix multiplication (matmul)',
'\nnumpy: ', np.matmul(data, data), # [[7, 10], [15, 22]]
'\ntorch: ', torch.mm(tensor, tensor) # [[7, 10], [15, 22]]
)

# !!!! 下面是错误的方法 !!!!
# 注意这里要转换成array,因为data原来是list对象,其没有.dot操作
data = np.array(data)
print(
'\nmatrix multiplication (dot)',
'\nnumpy: ', data.dot(data), # [[7, 10], [15, 22]] 在numpy 中可行
'\ntorch: ', tensor.dot(tensor) # torch 会转换成 [1,2,3,4].dot([1,2,3,4]) = 30.0
)

猜你喜欢

转载自www.cnblogs.com/pythonClub/p/10412937.html