我们学习pytorch的目的是进行深度学习,而深度学习可以干哪些事呢?主要有两个:1)回归问题,2)分类问题。何谓回归,线性回归大家一定都学过,通俗来讲就是给定坐标系下一些点,来用一条曲线进行拟合,以描绘这些样本点的变化趋势,这就是回归。
下面就通过代码实例来学习,通过一些数据来拟合一条回归曲线。具体讲解请参考莫烦pythons(代码来源)
# 首先导入所需要的模块
import torch
from torch.autograd import Variable
import torch.nn.functional as F
import matplotlib.pyplot as plt
# 构建数据
x = torch.unsqueeze(torch.linspace(-1, 1, 100), dim=1) # x data (tensor), shape=(100, 1)
# 因为在torch中数据是有维度的,通过linspace生成的是[-1, 1]之间的100个一维数据格式为[1, 2, 3]这样的,通过unaqueeze可以使这些数据有维度,通过dim=1参数设定这些数在列上,如果设定dim=0则设定这些数在行上,此时这100个数为一列,它的shape为(100, 1),形式是[[1], [2]]这样的,这一操作是必须的,可以死记住
y = x.pow(2) + 0.2*torch.rand(x.size()) # noisy y data (tensor), shape=(100, 1)
# torch can only train on Variable, so convert them to Variable
# The code below is deprecated in Pytorch 0.4. Now, autograd directly supports tensors
# x, y = Variable(x), Variable(y)
# plt.scatter(x.data.numpy(), y.data.numpy())
# plt.show()
class Net(torch.nn.Module):
def __init__(self, n_feature, n_hidden, n_output):
super(Net, self).__init__()
self.hidden = torch.nn.Linear(n_feature, n_hidden) # hidden layer
self.predict = torch.nn.Linear(n_hidden, n_output) # output layer
def forward(self, x):
x = F.relu(self.hidden(x)) # activation function for hidden layer
x = self.predict(x) # linear output
return x
net = Net(n_feature=1, n_hidden=10, n_output=1) # define the network
print(net) # net architecture
optimizer = torch.optim.SGD(net.parameters(), lr=0.2)
loss_func = torch.nn.MSELoss() # this is for regression mean squared loss
plt.ion() # something about plotting
for t in range(200):
prediction = net(x) # input x and predict based on x
loss = loss_func(prediction, y) # must be (1. nn output, 2. target)
optimizer.zero_grad() # clear gradients for next train
loss.backward() # backpropagation, compute gradients
optimizer.step() # apply gradients
if t % 5 == 0:
# plot and show learning process
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.numpy(), fontdict={'size': 20, 'color': 'red'})
plt.pause(0.1)
plt.ioff()
plt.show()