pytorch&numpy

Torch 自称为神经网络界的 Numpy,两者可以很好的兼容,我们可以在numpy array和torch tensor之间轻松的转换。

1、torch和numpy之间的转换

import torch
import numpy as np

np_data = np.arange(6).reshape((2,3)) #numpy数据
torch_data = torch.from_numpy(np_data) #将numpy数据转换成torch数据
tensor2array = torch_data.numpy() #将torch的数据转换成numpy的数据

print('\nnumpy',np_data,
      '\ntorch',torch_data,
      '\ntensor to array:', tensor2array)
结果如下:
numpy [[0 1 2] [3 4 5]] torch tensor([[0, 1, 2], [3, 4, 5]]) tensor to array: [[0 1 2] [3 4 5]]

2、Torch中的数学运算

torch中的数学运算和numpy差不多 

注意:torch运算中数据必须是tensor形式

import torch
import numpy as np

#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.)

接下来看一下矩阵形式的运算:

import torch
import numpy as np

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

#wrong method
data = np.array(data)
print(
    '\nnumpy: ', data.dot(data),        # [[7, 10], [15, 22]] 在numpy 中可行
    '\ntorch: ', tensor.dot(tensor)     #此处会报错 torch.dot只支持一维数组运算
)
结果如下
numpy: [[ 7 10] [15 22]] torch: tensor([[ 7., 10.], [15., 22.]]) numpy: [[ 7 10] [15 22]]

猜你喜欢

转载自www.cnblogs.com/funnything/p/11018237.html