import torch
from torch.autograd import Variable
imgL = Variable(torch.FloatTensor(imgL))
imgR = Variable(torch.FloatTensor(imgR))
disp_L = Variable(torch.FloatTensor(disp_L))
1.数据计算
Torch 自称为神经网络界的 Numpy, 因为他能将 torch 产生的 tensor 放在 GPU 中加速运算 (前提是你有合适的 GPU), 就像 Numpy 会把 array 放在 CPU 中加速运算。Torch和Numpy之间可以进行自由的切换:
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]]
)
Pytorch中的数学计算:
Pytorch中很多的数学计算与numpy中的数学计算函数是相同的:
# 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
)
# 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]]
)
更多Pytorch中的数据计算函数,可以查看以下文档(torch.Tensor):
http://pytorch.org/docs/tensors.html#
2.Variable 变量
Pytorch的Variable相当于一个Wraper,如果你想将数据传送到Pytorch构建的图中,就需要先将数据用Variable进行包装,包装后的Variable有三个attribute:data,creater,grad:(如下图所示)
其中data就是我们被包裹起来的数据,creator是用来记录通过何种计算得到当前的variable,grad则是在进行反向传播的时候用来记录数据的梯度的。
import torch
from torch.autograd import Variable
x = Variable(torch.ones(2, 2), requires_grad=True)
print(x)
print(x.data)
print(x.creator)
print(x.grad)
y = x + 2
print(y)
print(y.creator)
z = y * y * 3
out = z.mean()
print(z, out)
out.backward()
print(x.grad)