ITPub博客

首页 > IT职业 > IT职场 > python3+pytorch之numpy与Torch对比

python3+pytorch之numpy与Torch对比

IT职场 作者:54xx 时间:2021-09-09 09:10:12 0 删除 编辑

首先,其实torch中的tensor和numpy中的array运算是差不多滴,所以我们就做一个简单的对比。
1、简单运算

import numpy as np
import torch

data = [-1, -2, 1, 2]
tensor = torch.FloatTensor(data)  # 转换成32位浮点 tensor
#abs    绝对值运算
print(
    'nabs',
    'nnumpy: ', np.abs(data),          # [1 2 1 2]
    'ntorch: ', torch.abs(tensor)      # [1 2 1 2]
)
# sin   三角函数 sin
print(
    'nsin',
    'nnumpy: ', np.sin(data),      # [-0.84147098 -0.90929743  0.84147098  0.90929743]
    'ntorch: ', torch.sin(tensor)  # [-0.8415 -0.9093  0.8415  0.9093]
)

# mean  均值
print(
    'nmean',
    'nnumpy: ', np.mean(data),         # 0.0
    'ntorch: ', torch.mean(tensor)     # 0.0
)

2、矩阵运算

import numpy as np
import torch

data = [[1,2], [3,4]]
tensor = torch.FloatTensor(data)  # 转换成32位浮点 tensor

# matrix multiplication 矩阵点乘
# correct method
print(
    'nmatrix multiplication (matmul)',
    'nnumpy: ', np.matmul(data, data),     # [[7, 10], [15, 22]]
    'ntorch: ', torch.mm(tensor, tensor)   # [[7, 10], [15, 22]]
)

#wrong method !!!!  下面是错误的方法 !!!!
data = np.array(data)
print(
    'nmatrix multiplication (dot)',
    'nnumpy: ', data.dot(data),        # [[7, 10], [15, 22]] 在numpy 中可行
    'ntorch: ', torch.dot(tensor.dot(tensor))     # torch 会转换成 [1,2,3,4].dot([1,2,3,4) = 30.0(版本

最后呢,其实在pytorch官网上有很多的资料和文档,对于这一个部分呢,连接就放在这里咯链接描述

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/1976/viewspace-2799778/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-04-16

  • 博文量
    226
  • 访问量
    1612