莫烦 Pytorch

Numpy Torch对比Pytorch

import torch
import numpy as np

numpy_data = np.arange(6).reshape([2, 3])       # create a numpy
torch_data = torch.from_numpy(numpy_data)       # numpy--->torch
tensor2array = torch_data.numpy()               # tensor--->numpy

print(
    '\nnumpy_data:', numpy_data,
    '\ntorch_data:', torch_data,                # the type of output is tensor
    '\ntensor2array:', tensor2array,
)
'''
运行结果:
numpy_data: [[0 1 2]
 [3 4 5]] 
torch_data: tensor([[0, 1, 2],
        [3, 4, 5]], dtype=torch.int32) 
tensor2array: [[0 1 2]
 [3 4 5]]
'''
import torch
import numpy as np

data = [-1, -2, 1, 2]
tensor = torch.FloatTensor(data)        # 32bits

print(
    '\nabs',
    '\nnumpy', np.abs(data),
    '\ntorch', torch.abs(tensor),
)
print(
    '\nsin',
    '\nnumpy', np.sin(data),
    '\ntorch', torch.sin(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])
'''
import torch
import numpy as np

data = [[-1, -2], [1, 2]]
tensor = torch.FloatTensor(data)        # 转换成tensor的形式,32-bit

print(
    '\nnumpy:', np.matmul(data, data),
    '\ntorch:', torch.mm(tensor, tensor),
)
'''
运行结果:
numpy: [[-1 -2]
 [ 1  2]] 
torch: tensor([[-1., -2.],
        [ 1.,  2.]])
'''
posted @ 2020-03-21 09:36  旅人_Eric  阅读(93)  评论(0编辑  收藏  举报