莫烦 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.]])
'''
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值