PyTorch-Numpy和Torch对比

  1. 两者的相互转换
  2. 运算异同
import torch as t
import numpy as np

np_data = np.arange(6).reshape(2,3)
torch_data = t.from_numpy(np_data) #  将array类型转化成tensor类型
tensor2array = torch_data.numpy(); #  将tensor类型转化成array类型

print("----------------类型转换--------------")
print(np_data)
print(torch_data)
print(tensor2array)

# abs
data = [-1,-2,1,2]
tensor = t.FloatTensor(data)  # 32bit
print("----------------abs--------------")
print(np.abs(data))
print(t.abs(tensor))
print("----------------sin--------------")
print(np.sin(data))
print(t.sin(tensor))

data = [[1,2],[3,4]]
tensor = t.FloatTensor(data) # 32-bit floating point

print("----------------矩阵相乘--------------")
print(np.matmul(data,data))
print(t.mm(tensor,tensor))


结果:

----------------类型转换--------------
[[0 1 2]
 [3 4 5]]
tensor([[0, 1, 2],
        [3, 4, 5]], dtype=torch.int32)
[[0 1 2]
 [3 4 5]]
----------------abs--------------
[1 2 1 2]
tensor([1., 2., 1., 2.])
----------------sin--------------
[-0.84147098 -0.90929743  0.84147098  0.90929743]
tensor([-0.8415, -0.9093,  0.8415,  0.9093])
----------------矩阵相乘--------------
[[ 7 10]
 [15 22]]
tensor([[ 7., 10.],
        [15., 22.]])

你可能感兴趣的:(PyTorch)