神经网络Python实现(9行代码)
1.?神經網絡簡介
神經網絡由輸入層、輸出層和之間若干層(一層或多層)隱含層構成,每一層可以有若干個節點。層與層之間節點的連接狀態通過權重來體現。
?下面介紹一下單個神經元:
輸入節點:x1,x2
權重:w1,w2
偏置:b
激活函數:h()
輸出結果:y
a = x1*w1 + x2*w2 + b
?2. 代碼解釋
這段代碼是在GitHub上找到的,鏈接如下:
https://github.com/miloharper/simple-neural-network
作者這樣描述這段代碼:
A neural network written in Python, consisting of a single neuron that uses gradient descent to learn.
一種用Python編寫的神經網絡,它是由一個使用梯度下降學習的神經元組成。
from numpy import exp, array, random, dot training_set_inputs = array([[0, 0, 1], [1, 1, 1], [1, 0, 1], [0, 1, 1]]) training_set_outputs = array([[0, 1, 1, 0]]).T random.seed(1) synaptic_weights = 2 * random.random((3, 1)) - 1 for iteration in range(10000):output = 1 / (1 + exp(-(dot(training_set_inputs, synaptic_weights))))synaptic_weights += dot(training_set_inputs.T, (training_set_outputs - output) * output * (1 - output)) print( 1 / (1 + exp(-(dot(array([1, 0, 0]), synaptic_weights)))))① from numpy import exp, array, random, dot
#從Numpy庫中調用exp(指數函數)、array(數組)、random(隨機函數)、dot(矩陣相乘函數)
② training_set_inputs = array([[0, 0, 1], [1, 1, 1], [1, 0, 1], [0, 1, 1]])
#神經網絡訓練部分的輸入
③ training_set_outputs = array([[0, 1, 1, 0]]).T
#神經網絡訓練部分的輸出,.T表示矩陣轉置
④ random.seed(1)
#使用隨機函數生成隨機數(這一行代碼可以省略,目的只是保證測試結果與作者一致)
⑤ synaptic_weights = 2 * random.random((3, 1)) – 1
⑥ for iteration in range(10000):
⑦? ?output = 1 / (1 + exp(-(dot(training_set_inputs, synaptic_weights))))
#使用for語句循環10000次,將訓練集的輸入和權重采用.dot進行矩陣相乘,將相乘得到的結果輸入到sigmoid函數,然后將得到的結果賦值給output
⑧?? synaptic_weights += dot(training_set_inputs.T, (training_set_outputs - output) * output * (1 - output))
#權重的調整采用“誤差加權導數”公式(梯度下降)
⑨ print (1 / (1 + exp(-(dot(array([1, 0, 0]), synaptic_weights)))))?#[0.99993704]
#synaptic_weights是調整之后的最終權重,數組(矩陣)[1,0,0]與這個權重矩陣通過dot函數進行相乘,將相乘的結果作為輸入引入到sigmoid函數,得到最終的結果
這段代碼的模型如下圖所示,有三個輸入,一個輸出,簡單來說,神經網絡就是一個通過訓練集輸入的數據不斷地迭代更新權重的模型,使之輸出更接近“標準答案”,這里推薦看一下B站上的一個有關神經網絡的短視頻:
一分鐘告訴你什么是神經網絡
?這9行代碼就是把上圖的1~4組數據作為訓練集進行模型訓練,不斷地更新權重使其輸出更接近訓練集中給出的輸出標簽(標準答案),然后將最后一組數據當做測試集來檢測模型的準確度,它最后的結果輸出是0.99993704,也是約等于1,其實不難發現,4組測試數據的輸出都與第一個輸入數據相同,所以說神經網絡模型測試得到了正確的結果,這也是說明神經網絡有預測結果的作用。
總結
以上是生活随笔為你收集整理的神经网络Python实现(9行代码)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Cocos2dx 小技巧(一)预定义文件
- 下一篇: python 给定n个整数,请统计出每个