基本概念
Tensors:
Tensors和Numpy’s的ndarrys相似,可以在GPU上使用Tensors来加速计算。
构建矩阵(不初始化):
x = torch.Tensor(5, 3)
print(x)
构建矩阵(随机初始化):
x = torch.rand(5, 3)
Get its size
print(x.size())
加法操作(addition):
第一种方式:print(x + y)
第二种方式:print(torch.add(x, y))
第三种方式:
result = torch.Tensor(5, 3)
torch.add(x, y, out=result)
print(result)
第四种方式(adds x to y):y.add_(x)
切片操作,跟numpy基本一样:
print(x[1,:])
resize/reshape:
x = torch.randn(4, 4)
y = x.view(16)
z = x.view(-1, 8)
numpy和tensor转换:(共享内存,所以转换后进行操作二个会同时更新)
tensor–>numpy
a = torch.ones(5)
b = a.numpy()
a.add_(1)
print(a)
print(b)
numpy–>tensor
import numpy as np
a = np.ones(5)
b = torch.from_numpy(a)
np.add(a, 1, out=a)
更多操作:http://pytorch.org/docs/master/torch.html
Autograd: automatic differentiation
Autograd 包为Tensors上的所有操作提供自动微分。
Variable
Autograd.Variable是包的核心类。它包装一个张量,支持几乎所有在其上定义的操作。 一旦你完成你的计算,你可以调用.backward()并自动计算所有的梯度。您可以通过.data属性访问原始张量,.grad得到梯度。
创建:
x = Variable(torch.ones(2, 2), requires_grad=True)
print(x)
Gradients
梯度,通过.backward()使用。
参考:
1.http://pytorch.org/tutorials/beginner/deep_learning_60min_blitz.html