天天看點

Pytorch實作線性回歸并實時顯示拟合過程(6)

本代碼通過使用Pytorch動态實作線性回歸:

import torch
import torch.nn.functional as F
from torch.autograd import Variable
import matplotlib.pyplot as plt

'''
先看torch.squeeze() 這個函數主要對資料的次元進行壓縮,去掉維數為1的的次元,比如是一行或者一列這種,一個一行三列(1,3)的數去掉第一個維數為一的次元之後就變成(3)行。squeeze(a)就是将a中所有為1的次元删掉。不為1的次元沒有影響。a.squeeze(N) 就是去掉a中指定的維數為一的次元。還有一種形式就是b=torch.squeeze(a,N) a中去掉指定的定的維數為一的次元。

再看torch.unsqueeze()這個函數主要是對資料次元進行擴充。給指定位置加上維數為一的次元,比如原本有個三行的資料(3),在0的位置加了一維就變成一行三列(1,3)。a.squeeze(N) 就是在a中指定位置N加上一個維數為1的次元。還有一種形式就是b=torch.squeeze(a,N) a就是在a中指定位置N加上一個維數為1的次元

'''
x = torch.unsqueeze(torch.linspace(-1, 1, 100), dim=1)  # x data (tensor), shape=(100, 1)
y = x.pow(2) + 0.2*torch.rand(x.size())                 # noisy y data (tensor), shape=(100, 1)


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()   # 打開互動模式

for t in range(300):
    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:
        #繪制和顯示學習率
        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()      

顯示拟合結果:

Pytorch實作線性回歸并實時顯示拟合過程(6)

繼續閱讀