Torch与Numpy简单比较(5)

 (1)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("\nnp_data:\n",np_data, "\ntorch_data:\n",torch_data, "\ntensor2array:\n", tensor2array)

(2)numpy与torch数学运算

#绝对值计算
import torch
import numpy as np
data = [-1, -2, 1, 2]
tensor = torch.FloatTensor(data) #转换成32位浮点 tensor

print("\nabs\n",'\nnumpy: \n', np.abs(data), '\ntorch:\n', torch.abs(tensor))

#sin 三角函数 sin
print("\nsin\n",'\nnumpy: \n', np.sin(data),
       '\ntorch: \n', torch.sin(tensor))

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

(3)numpy与torch矩阵运算

import numpy as np
import torch
data  = [[1,2], [3,4]]
tensor = torch.FloatTensor(data)
print('\nmatrix multiplication\n','\nnumpy: \n',np.matmul(data, data),
    '\ntorch:\n', torch.mm(tensor, tensor))

注:文章内容主要引用:https://www.pytorchtutorial.com/

你可能感兴趣的:(Pytorch)