深度學習 pytorch實戰 神經網絡分類任務

本文主要介紹如何使用Pytorch進行神經網絡的搭建,從而完成分類的任務。

原始待分類的數據如下


深度學習 pytorch實戰 神經網絡分類任務

原始分類數據

我們採用批訓練的方式,共訓練10代,每一批次為30個數據。這次我們沒有采用繼承的方式來搭建網絡,而直接使用torch.nn.Sequential來搭建網絡。

代碼如下:

<code>import torchimport torch.nn.functional as Fimport torch.utils.data as Dataimport matplotlib.pyplot as plt# 假數據n_data = torch.ones(200, 2)         # 數據的基本形態x0 = torch.normal(3*n_data, 1)      # 類型0 x data (tensor), shape=(100, 2)y0 = torch.zeros(200)               # 類型0 y data (tensor), shape=(100, )x1 = torch.normal(1*n_data, 1)     # 類型1 x data (tensor), shape=(100, 1)y1 = torch.ones(200)                # 類型1 y data (tensor), shape=(100, )# 注意 x, y 數據的數據形式是一定要像下面一樣 (torch.cat 是在合併數據)x = torch.cat((x0, x1), 0).type(torch.FloatTensor)  # FloatTensor = 32-bit floatingy = torch.cat((y0, y1), ).type(torch.LongTensor)    # LongTensor = 64-bit integernet=torch.nn.Sequential(        torch.nn.Linear(2, 10),  torch.nn.ReLU(),  torch.nn.Linear(10, 2)    )BATCH_SIZE=30torch_dataset = Data.TensorDataset(x, y)loader = Data.DataLoader(    dataset=torch_dataset,      # torch TensorDataset format      batch_size=BATCH_SIZE,      # mini batch size      shuffle=True,               # random shuffle for training)optimizer = torch.optim.SGD(net.parameters(), lr=0.02)loss_func = torch.nn.CrossEntropyLoss()  # the target label is NOT an one-hottedplt.ion()   # something about plottingfor epoch in range(10):   # train entire dataset 3 times    for step, (batch_x, batch_y) in enumerate(loader):  # for each training step            out = net(batch_x)  # input x and predict based on x                        loss = loss_func(out, batch_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 gradient        # plot and show learning process        plt.cla()        out=net(x)        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, 3, 'Accuracy=%.2f' % accuracy, fontdict={'size': 20, 'color': 'red'})        plt.pause(0.1)plt.ioff()plt.show()/<code>

使用單層網絡的訓練結果:


深度學習 pytorch實戰 神經網絡分類任務

單層神經網絡


深度學習 pytorch實戰 神經網絡分類任務

雙層神經網絡

可以看到擬合這樣簡單的分類任務,網絡層數對預測的結果影響不大。但是當我們進行多特徵分類任務時,就需要增加網絡層數。


分享到:


相關文章: