pytorch:numpy运算转换为torch运算

np_data=np.arange(6).reshape((2,3))

1.#由numpy转换为torch数据

numpy [[0 1 2]
 [3 4 5]] 
torch_data=torch.from_numpy(np_data)

2.#由tensor数据转换为numpy数据

torch tensor([[0, 1, 2],
        [3, 4, 5]], dtype=torch.int32)
tensor2array=torch_data.numpy()
tensor2array [[0 1 2]
 [3 4 5]]

3.abs函数

data=[-1,-2,1,2]
tensor=torch.FloatTensor(data)
print(
    '\nabs',
    '\nnumpy',np.abs(data),
    '\ntorch',torch.abs(tensor)
)
abs 
numpy [1 2 1 2] 
torch tensor([1., 2., 1., 2.])

torch.abs要处理的数据必须是tensor,而不能是list。torch .abs等同于numpy.abs函数

4.#sin如abs一样

data=[-1,-2,1,2]
tensor=torch.FloatTensor(data)
print(
    '\nsin',
    '\nnumpy',np.sin(data),
    '\ntorch',torch.sin(tensor)
)
sin 
numpy [-0.84147098 -0.90929743  0.84147098  0.90929743] 
torch tensor([-0.8415, -0.9093,  0.8415,  0.9093])

其他的函数也如同numpy类似,需要可以百度查询
5.#矩阵相乘

data=[[1,2],[3,4]]
tensor=torch.FloatTensor(data)
print(
    '\nnumpy矩阵相乘:',np.matmul(data,data),
    '\ntorch矩阵相乘:',torch.mm(tensor,tensor)
)
numpy矩阵相乘: [[ 7 10]
 [15 22]] 
torch矩阵相乘: tensor([[ 7., 10.],
        [15., 22.]])
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值