AI人工智能 單層神經網絡

2020-09-24 10:57 更新

在這個例子中,我們來創(chuàng)建一個單層神經網絡,它由獨立的神經元組成,這些神經元在輸入數(shù)據(jù)上起作用以產生輸出。 請注意,這里使用 neural_simple.txt 文件作為輸入。

如下所示導入所需的軟件包 -

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. import neurolab as nl

加載數(shù)據(jù)集如下代碼 -

  1. input_data = np.loadtxt(“/Users/admin/neural_simple.txt')

以下是我們要使用的數(shù)據(jù)。 請注意,在此數(shù)據(jù)中,前兩列是特征,最后兩列是標簽。

  1. array([[2. , 4. , 0. , 0. ],
  2. [1.5, 3.9, 0. , 0. ],
  3. [2.2, 4.1, 0. , 0. ],
  4. [1.9, 4.7, 0. , 0. ],
  5. [5.4, 2.2, 0. , 1. ],
  6. [4.3, 7.1, 0. , 1. ],
  7. [5.8, 4.9, 0. , 1. ],
  8. [6.5, 3.2, 0. , 1. ],
  9. [3. , 2. , 1. , 0. ],
  10. [2.5, 0.5, 1. , 0. ],
  11. [3.5, 2.1, 1. , 0. ],
  12. [2.9, 0.3, 1. , 0. ],
  13. [6.5, 8.3, 1. , 1. ],
  14. [3.2, 6.2, 1. , 1. ],
  15. [4.9, 7.8, 1. , 1. ],
  16. [2.1, 4.8, 1. , 1. ]])

現(xiàn)在,將這四列分成2個數(shù)據(jù)列和2個標簽 -

  1. data = input_data[:, 0:2]
  2. labels = input_data[:, 2:]

使用以下命令繪制輸入數(shù)據(jù) -

  1. plt.figure()
  2. plt.scatter(data[:,0], data[:,1])
  3. plt.xlabel('Dimension 1')
  4. plt.ylabel('Dimension 2')
  5. plt.title('Input data')

現(xiàn)在,為每個維度定義最小值和最大值,如下所示 -

  1. dim1_min, dim1_max = data[:,0].min(), data[:,0].max()
  2. dim2_min, dim2_max = data[:,1].min(), data[:,1].max()

接下來,如下定義輸出層中神經元的數(shù)量 -

  1. nn_output_layer = labels.shape[1]

現(xiàn)在,定義一個單層神經網絡 -

  1. dim1 = [dim1_min, dim1_max]
  2. dim2 = [dim2_min, dim2_max]
  3. neural_net = nl.net.newp([dim1, dim2], nn_output_layer)

訓練神經網絡的時代數(shù)和學習率如下所示 -

  1. error = neural_net.train(data, labels, epochs = 200, show = 20, lr = 0.01)

現(xiàn)在,使用以下命令可視化并繪制訓練進度 -

  1. plt.figure()
  2. plt.plot(error)
  3. plt.xlabel('Number of epochs')
  4. plt.ylabel('Training error')
  5. plt.title('Training error progress')
  6. plt.grid()
  7. plt.show()

現(xiàn)在,使用上述分類器中的測試數(shù)據(jù)點 -

  1. print('\nTest Results:')
  2. data_test = [[1.5, 3.2], [3.6, 1.7], [3.6, 5.7],[1.6, 3.9]] for item in data_test:
  3. print(item, '-->', neural_net.sim([item])[0])

下面是測試結果 -

  1. [1.5, 3.2] --> [1. 0.]
  2. [3.6, 1.7] --> [1. 0.]
  3. [3.6, 5.7] --> [1. 1.]
  4. [1.6, 3.9] --> [1. 0.]

您可以看到迄今為止討論的代碼的輸出圖表 -

img

img

以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號