# Pytorch学习笔记 1.3：Numpy和Torch函数的对比

2021/01/25 08:16

## torch_data.numpy()

import torch
import numpy as np

# 把numpy数据转换为torch数据
np_data = np.arange(6).reshape(2, 3)
torch_data = torch.from_numpy(np_data)  # 转换成torch的tensor数据

# 把torch数据转换为numpy数据
tensor2array = torch_data.numpy()
print(
'\nnumpy', np_data,
'\ntorch', torch_data,
'\ntensor2array', tensor2array,

)


## torch求均值：torch.mean(tensor)

import torch
import numpy as np

# abs
data = [-1, -2, 1, 2]
tensor = torch.FloatTensor(data)  # 转换为32bit的tensor浮点型

print(
'\nnbs',
'\nnumpy:', np.abs(data),  # [1 2 1 2]
'\ntorch:', torch.abs(tensor)  # [1 2 1 2]
)

# sin
print(
'\nsin',
'\nnumpy:', np.sin(data),  # [1 2 1 2]
'\ntorch:', torch.sin(tensor)  # [1 2 1 2]
)

# mean
print(
'\nmean',
'\nnumpy:', np.mean(data),  # [1 2 1 2]
'\ntorch:', torch.mean(tensor)  # [1 2 1 2]
)


## torch张量形式矩阵的乘法：torch.mm(tensor1, tensor1)

import torch
import numpy as np
# 矩阵形式的运算
data1 = [[1, 2], [3, 4]]
tensor1 = torch.FloatTensor(data1)

print(
'\nnumpy:', np.matmul(data1, data1),
'\ntorch:', torch.mm(tensor1, tensor1)
)


0 评论
0 收藏
0