Pytorch与Numpy学习笔记

Torch 自称为神经网络界的 Numpy,因为它能将 torch 产生的 tensor 放在 GPU 中加速运算 (前提是你有合适的 GPU), 就像 Numpy 会把 array 放在 CPU 中加速运算。所以神经网络的话, 当然是用 Torch 的 tensor 形式数据最好咯。就像 Tensorflow 当中的 tensor 一样。当然,我们对 Numpy 还是爱不释手的,因为我们太习惯 numpy 的形式了。不过 torch 看出来我们的喜爱,它把 torch 做的能与 numpy 很好的兼容。比如:


No.1 自由地转换 numpy array 和 torch tensor :

import torch
import numpy as np

np_data = np.arange(8).reshape((2,4))
torch_data = torch.from_numpy(np_data)
tensor2arry = torch_data.numpy()
print(
     '\nnp_data:',np_data,
     '\ntorch_data',torch_data,
     '\tensor2arry',tensor2arry,
)

运行结果:

np_data: [[0 1 2 3]
 [4 5 6 7]] 
torch_data tensor([[0, 1, 2, 3],
        [4, 5, 6, 7]], dtype=torch.int32) 	ensor2arry [[0 1 2 3]
 [4 5 6 7]]

No.2 Torch中的数学运算:

其实 torch 中 tensor 的运算和 numpy array 的如出一辙,我们就以对比的形式来看。

# abs 绝对值计算
data = [-1, -2, 1, 2]
tensor = torch.FloatTensor(data)  # 转换成32位浮点 tensor
print(
    '\nabs',
    '\nnumpy: ', np.abs(data),       
    '\ntorch: ', torch.abs(tensor)      
)

# sin 三角函数 sin
print(
    '\nsin',
    '\nnumpy: ', np.sin(data),      
    '\ntorch: ', torch.sin(tensor)  
)

# mean 均值
print(
    '\nmean',
    '\nnumpy: ', np.mean(data),        
    '\ntorch: ', torch.mean(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])

mean 
numpy:  0.0 
torch:  tensor(0.)

除了简单的计算, 矩阵运算才是神经网络中最重要的部分,所以我们展示下矩阵的乘法。注意一下包含了一个 numpy 中可行, 但是 torch 中不可行的方式。

# matrix multiplication 矩阵乘法
data = [[1,2], [3,4]]
tensor = torch.FloatTensor(data)  #转换成32位浮点 tensor
# correct method
print(
    '\矩阵乘法 (matmul)',
    '\nnumpy: ', np.matmul(data, data),     
    '\ntorch: ', torch.mm(tensor, tensor)   
)

运行结果:

\矩阵乘法 (matmul) 
numpy:  [[ 7 10]
         [15 22]] 
torch:  tensor([[ 7., 10.],[15., 22.]])

Numpy 中文参考手册:https://www.numpy.org.cn/index.html

Torch API:https://pytorch.org/docs/stable/torch.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Le_ander

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值