用pytorch1.0搭建簡單的神經網絡:進行多分類分析
import torch import torch.nn.functional as F # 包含激勵函數 import matplotlib.pyplot as plt # 假數據 # make fake data n_data = torch.ones(100, 2) x0 = torch.normal(2*n_data, 1) # class0 x data (tensor), shape=(100, 2) y0 = torch.zeros(100) # class0 y data (tensor), shape=(100, 1) x1 = torch.normal(-2*n_data, 1) # class1 x data (tensor), shape=(100, 2) y1 = torch.ones(100) # class1 y data (tensor), shape=(100, 1) # 注意 x, y 數據的數據形式是一定要像下面一樣 (torch.cat 是合並數據) x = torch.cat((x0, x1), 0).type(torch.FloatTensor) # shape (200, 2) FloatTensor = 32-bit floating y = torch.cat((y0, y1), ).type(torch.LongTensor) # shape (200,) LongTensor = 64-bit integer # 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()[:, 0], x.data.numpy()[:, 1], c=y.data.numpy(), s=100, lw=0, cmap='RdYlGn') plt.show() # 建立神經網絡 # 先定義所有的層屬性(__init__()), 然后再一層層搭建(forward(x))層於層的關系鏈接 class Net(torch.nn.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.out = 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.out(x) return x net = Net(n_feature=2, n_hidden=10, n_output=2) # define the network print(net) # net architecture == 顯示神經網絡結構 # Net( # (hidden): Linear(in_features=2, out_features=10, bias=True) # (out): Linear(in_features=10, out_features=2, bias=True) # ) # 搭建完神經網絡后,對 神經網路參數(net.parameters()) 進行優化 # (1.選擇優化器 optimizer 是訓練的工具 optimizer = torch.optim.SGD(net.parameters(), lr=0.02) # 傳入 net 的所有參數, 學習率 # (2.選擇優化的目標函數 loss_func = torch.nn.CrossEntropyLoss() # the target label is NOT an one-hotted plt.ion() # something about plotting # (3.開始訓練網絡 for t in range(100): out = net(x) # input x and predict based on x # 喂給 net 訓練數據 x, 輸出預測值 loss = loss_func(out, y) # must be (1. nn output, 2. target), the target label is NOT one-hotted # 計算兩者的誤差 optimizer.zero_grad() # clear gradients for next train # 清空上一步的殘余更新參數值 loss.backward() # backpropagation, compute gradients # 誤差反向傳播, 計算參數更新值 optimizer.step() # apply gradients # 將參數更新值施加到 net 的 parameters 上 if t % 2 == 0: # plot and show learning process plt.cla() # 過了一道 softmax 的激勵函數后的最大概率才是預測值 prediction = torch.max(out, 1)[1] pred_y = prediction.data.numpy() target_y = y.data.numpy() plt.scatter(x.data.numpy()[:, 0], x.data.numpy()[:, 1], c=pred_y, s=100, lw=0, cmap='RdYlGn') accuracy = float((pred_y == target_y).astype(int).sum()) / float(target_y.size) # 預測中有多少和真實值一樣 plt.text(1.5, -4, 'Accuracy=%.2f' % accuracy, fontdict={'size': 20, 'color': 'red'}) plt.pause(0.1) plt.ioff() plt.show()