# PyTorch-基本数据操作（Numpy）

PyTorch-基本数据操作（Numpy）

1、Torch 为神经网络界的 Numpy，torch.from_numpy() torch_data.numpy() 即可完成torch数据和numpy数据的相互转化

2、Torch 浮点数接收方式，torch.FloatTensor()，数据计算方式和numpy相似，如abs, sin, mean...

3、Torch 矩阵点乘方式，torch.mm(tensor, tensor)，与numpy.matmul(data, data) 类似

Example1:

import torch
import numpy as np

np_data = np.arange(6).reshape((2, 3))
torch_data = torch.from_numpy(np_data)
tensor2array = torch_data.numpy()
print(
'\nnumpy array:', np_data,          # [[0 1 2], [3 4 5]]
'\ntorch tensor:', torch_data,      #  0  1  2 \n 3  4  5    [torch.LongTensor of size 2x3]
'\ntensor to array:', tensor2array, # [[0 1 2], [3 4 5]]
)

Example2:

import torch
import numpy as np

# abs 绝对值计算
data = [-1, -2, 1, 2]
tensor = torch.FloatTensor(data)  # 转换成32位浮点 tensor
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
)

Example3：

import torch
import numpy as np

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

https://morvanzhou.github.io/

11-26 2088

04-04 1万+
07-28 1万+
08-03 4238
08-31 5851
06-25 4738