@nemos
2017-05-06T13:57:36.000000Z
字数 1967
阅读 1171
ml
import torch
x = torch.Tensor(5, 3)x.size() # 返回类元组对象
所有改变变量的操作会有_后缀,如x.add_(y)。
x = torch.Tensor(2, 2)y = torch.Tensor(2, 2)z = x + yz = torch.add(x, y)torch.add(x, y, out=z)# 注意这样操作会改变y的值y.add_(x)
类numpy的一些接口
x[:, 1] # 列索引x = torch.ones(5) # 初始化x.numpy() # 转化y = torch.from_numpy(x)
使用cuda
if torch.cuda.is_available():x = x.cuda()y = y.cuda()x + y
import torchfrom torch.autograd import Variable
Variable可视作Tensor封装的对象,包含三个部分。
Variable.data 返回 Tensor对象Variable.grad 返回梯度的 Tensor对象Variable.creator 返回创建变量的函数引用
x = Variable(torch.ones(2, 2), requires_grad=True)y = x + 2z = y * y * 3out = z.mean()out.backward() # 反向求导x.grad # 返回梯度的tensor
注意只有调用了backward()之后x中才有梯度
import torchfrom torch.autograd import Variableimport torch.nn as nnimport torch.nn.functional as Fimport torch.optim as optim
class Net(nn.Module):# 定义层的结构def __init__(self):super(Net, self).__init__()self.conv1 = nn.Conv2d(in_channels=1, out_channels=6, kernel_size=5)self.conv2 = nn.Conv2d(6, 16, 5)self.fc1 = nn.Linear(in_features=16 * 5 * 5, out_features=120)self.fc2 = nn.Linear(120, 84)self.fc3 = nn.Linear(84, 10)# 前向计算def forward(self, x):x = F.max_pool2d(input=F.relu(input=self.conv1(x)),kernel_size=(2, 2))# 如果size是方形的,直接传边长即可x = F.max_pool2d(F.relu(self.conv2(x)), 2)# 扁平处理x = x.view(-1, self.num_flat_features(x))x = F.relu(self.fc1(x))x = F.relu(self.fc2(x))x = self.fc3(x)return xdef num_flat_features(self, x):size = x.size()[1:] # 去掉batch的维度num_features = 1for s in size:num_features *= s# 返回单维的长度return num_features
net = Net() # 初始化# 随机生成一个输入和输出input = Variable(torch.randn(1, 1, 32, 32))target = Variable(torch.range(1, 10))# 计算输出out = net(input)net.zero_grad() # bp前先把参数清空并置0criterion = nn.MSELoss() # 平均均方误差loss = criterion(output, target)loss.backward()# 参数更新learning_rate = 0.01for f in net.parameters():f.data.sub_(f.grad.data * learning_rate)# 优化器optimizer = optim.SGD(net.parameters(), lr = 0.01)optimizer.zero_grad() # 等同net.zero_grad()optimizer.step() # 参数更新
print(net) # 显示网络结构params = list(net.parameters())print(len(params))params[0].size() # 第一层卷积权重的大小
官方文档-60分钟快速入门
等什么, 赶快抱紧 PyTorch 的大腿!
yunjey/pytorch-tutorial
新手如何入门pytorch
the-incredible-pytorch