pytorch vs numpy

pytorch vs numpy

以下代码比较pytorch和numpy的基本运算功能:

import numpy as np
import torch

np_data = np.arange(6).reshape((2, 3))
print('numpy data:', np_data)
torch_data = torch.from_numpy(np_data)
print('\nnumpy data -> torch data:', torch_data)
torch2np_data = torch_data.numpy()
print('\ntorch data -> numpy data:', torch2np_data)


data = [-1, -2, 1, 2]
tensor = torch.FloatTensor(data)
print('\noriginal data:', data)
print('abs of numpy:', np.abs(data))
print('abs of torch:', torch.abs(tensor))
print('sin of numpy:', np.sin(data))
print('sin of torch:', torch.sin(tensor))
print('mean of numpy:', np.mean(data))
print('mean of torch:', torch.mean(tensor))


data = [[1,2],[3,4]]
tensor = torch.FloatTensor(data)
print('\nmultiply of numpy:', np.matmul(data,data))
print('\nmultiply of torch:', torch.mm(tensor,tensor))
data = np.array(data)
print('\ndot_multiply of numpy:', data.dot(data))
print('\ndot_multiply of torch:', tensor.mm(tensor))

输出结果:

numpy data: [[0 1 2]
 [3 4 5]]

numpy data -> torch data: tensor([[0, 1, 2],
        [3, 4, 5]], dtype=torch.int32)

torch data -> numpy data: [[0 1 2]
 [3 4 5]]

original data: [-1, -2, 1, 2]
abs of numpy: [1 2 1 2]
abs of torch: tensor([1., 2., 1., 2.])
sin of numpy: [-0.84147098 -0.90929743  0.84147098  0.90929743]
sin of torch: tensor([-0.8415, -0.9093,  0.8415,  0.9093])
mean of numpy: 0.0
mean of torch: tensor(0.)

multiply of numpy: [[ 7 10]
 [15 22]]

multiply of torch: tensor([[ 7., 10.],
        [15., 22.]])

dot_multiply of numpy: [[ 7 10]
 [15 22]]

dot_multiply of torch: tensor([[ 7., 10.],
        [15., 22.]])

pytorch与 numpy基本运算相似。

posted on 2021-09-02 16:46  菜小疯  阅读(199)  评论(0编辑  收藏  举报