回归函数

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)   #torch.linspace本身是一维向量,unsqueeze是增加维度,把一维化为二维
y=x.pow(2)+0.2*torch.rand(x.size())   #0.2*torch.rand(x.size())相当于给散点图加噪声
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)
        self.predict=torch.nn.Linear(n_hidden,n_output)
    def forward(self, x):
        x = F.relu(self.hidden(x))  # activation function for hidden layer  ,x为隐藏层输出
        x = self.predict(x)  # linear output   ,输出层不采用激活函数的原因是激活函数会截断。
        return x
net=Net(n_feature=1,n_hidden=10,n_output=1)
# print(net)   #输出神经网络结构
optimizer=torch.optim.SGD(net.parameters(),lr=0.2)  #神经网络的优化函数
loss_func=torch.nn.MSELoss()    #均方根损失函数
plt.ion()   #开启交互模式
for t in range(200):        #训练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:    #每5次显示一副图像
        # 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()

运行程序会出现一个动图,表示回归的过程。

转自莫烦大神。

posted @ 2018-12-25 10:55  小小小小小码农  阅读(578)  评论(0编辑  收藏  举报