莫烦python的pytorch的学习。
pytorch里的variable,tensor和numpy格式的转化和使用
numpy:矩阵格式,仅是存储数据,
tensor是pytorch网络格式,要传入网络的格式,
variable是tenso+梯度,需要计算梯度时才需要。。。。。。
a:variable格式
a.data:tensor格式
a.data.numpy():numpy格式
tensor和numpy的实验。
import torch
import numpy as np
# details about math operation in torch can be found in: http://pytorch.org/docs/torch.html#math-operations
print(torch.__version__) # 1.2.0
# exit(0)
# convert numpy to tensor or vise versa
np_data = np.arange(6).reshape((2, 3))
torch_data = torch.from_numpy(np_data)
tensor2array = torch_data.numpy()
# print("torch_data ", type(torch_data)) #
# print('tensor2array ', type(tensor2array)) #
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]]
)
# exit(0)
# abs
data = [-1, -2, 1, 2]
tensor = torch.FloatTensor(data) # 32-bit floating point
# torch.FloatTensor()
print(
'\nabs',
'\nnumpy: ', np.abs(data), # [1 2 1 2]
'\ntorch: '