搭建簡單的神經網絡:進行回歸分析
import torch 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) y = x.pow(2) + 0.2*torch.rand(x.size()) # noisy y data (tensor), shape=(100, 1) # [1,2,3,4,5,6,7,8,9]---一維數據 [[1,2,3,4,5,6,7,8,9]]---二維數據 # torch只會處理二維及以上數據 # 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() # 建立神經網絡 # 先定義所有的層屬性(__init__()), 然后再一層層搭建(forward(x))層於層的關系鏈接 class Net(torch.nn.Module): # 繼承 torch 的 Module def __init__(self, n_feature, n_hidden, n_output): super(Net, self).__init__() # 繼承 __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): # 這同時也是 Module 中的 forward 功能 # 正向傳播輸入值, 神經網絡分析出輸出值 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 == 顯示神經網絡結構 # Net( # (hidden): Linear(in_features=1, out_features=10, bias=True) # (predict): Linear(in_features=10, out_features=1, bias=True) # ) # 搭建完神經網絡后,對 神經網路參數(net.parameters()) 進行優化 # (1.選擇優化器 optimizer 是訓練的工具 optimizer = torch.optim.SGD(net.parameters(), lr=0.15) # 傳入 net 的所有參數, 學習率 # (2.選擇優化的目標函數 loss_func = torch.nn.MSELoss() # this is for regression mean squared loss # 預測值和真實值的誤差計算公式 (均方差) plt.ion() # something about plotting # (3.開始訓練網絡 for t in range(200): prediction = net(x) # input x and predict based on x # 喂給 net 訓練數據 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 # 將參數更新值施加到 net 的 parameters 上 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()