@nemos
2017-05-06T13:57:36.000000Z
字数 1967
阅读 1125
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 + y
z = 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 torch
from 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 + 2
z = y * y * 3
out = z.mean()
out.backward() # 反向求导
x.grad # 返回梯度的tensor
注意只有调用了backward()
之后x
中才有梯度
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
import 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 x
def num_flat_features(self, x):
size = x.size()[1:] # 去掉batch的维度
num_features = 1
for 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前先把参数清空并置0
criterion = nn.MSELoss() # 平均均方误差
loss = criterion(output, target)
loss.backward()
# 参数更新
learning_rate = 0.01
for 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