PyTorch基本用法(四)——回归
2017-09-19 本文已影响27人
SnailTyan
文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
本文主要是关于PyTorch的一些用法。
import torch
import torch.nn.functional as F
import matplotlib.pyplot as plt
from torch.autograd import Variable
# 生成数据
x = torch.unsqueeze(torch.linspace(-1, 1, 100), dim = 1)
y = x.pow(2) + 0.2 * torch.rand(x.size())
# 变为Variable
x, y = Variable(x), Variable(y)
# 绘制数据图像
plt.scatter(x.data.numpy(), y.data.numpy())
plt.show()
png
# 定义pytorch网络
class Net(torch.nn.Module):
def __init__(self, n_features, n_hidden, n_output):
super(Net, self).__init__()
self.hidden = torch.nn.Linear(n_features, n_hidden)
self.predict = torch.nn.Linear(n_hidden, n_output)
def forward(self, x):
x = F.relu(self.hidden(x))
y = self.predict(x)
return y
# 构建网络
net = Net(1, 10, 1)
print net
Net (
(hidden): Linear (1 -> 10)
(predict): Linear (10 -> 1)
)
# 选择优化方法
optimizer = torch.optim.SGD(net.parameters(), lr = 0.5)
# 选择损失函数
loss_func = torch.nn.MSELoss()
plt.ion()
# 训练
for i in xrange(100):
# 对x进行预测
prediction = net(x)
# 计算损失
loss = loss_func(prediction, y)
# 每次迭代清空上一次的梯度
optimizer.zero_grad()
# 反向传播
loss.backward()
# 更新梯度
optimizer.step()
if i % 5 == 0:
plt.cla()
plt.scatter(x.data.numpy(), y.data.numpy())
plt.plot(x.data.numpy(), prediction.data.numpy(), 'r-', lw = 5)
plt.text(0.5, 0, 'Loss=%.4f' % loss.data[0], fontdict={'size': 10, 'color': 'red'})
plt.pause(0.1)
plt.ioff()
plt.show()
png
# unsqueeze用法, 一维变二维
x = torch.Tensor([1, 2, 3, 4])
print x
print torch.unsqueeze(x, 0)
print torch.unsqueeze(x, 1)
1
2
3
4
[torch.FloatTensor of size 4]
1 2 3 4
[torch.FloatTensor of size 1x4]
1
2
3
4
[torch.FloatTensor of size 4x1]
# rand用法, rand返回的是[0,1)之间的均匀分布
print torch.rand(4)
print torch.rand(2, 3)
0.8473
0.2252
0.0599
0.0777
[torch.FloatTensor of size 4]
0.2864 0.1693 0.1261
0.9013 0.2009 0.9854
[torch.FloatTensor of size 2x3]