PyTorch-基本数据操作(Numpy)
硬件:NVIDIA-GTX1080
软件:Windows7、python3.6.5、pytorch-gpu-0.4.1
一、基础知识
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]]
)
三、参考:
任何问题请加
唯一
QQ
2258205918
(名称
samylee
)!
或
唯一
VX:samylee_csdn