序言:常言道,在實(shí)踐中學(xué)習(xí),在理論中提升。輾輾轉(zhuǎn)轉(zhuǎn)看了幾本神經(jīng)網(wǎng)絡(luò)的書,磕磕絆絆地了解了一些概念,對(duì)于神經(jīng)網(wǎng)絡(luò)還是懵懵懂懂。在matlab里跑代碼,純調(diào)用庫函數(shù),真的是閉著眼睛開車。幸運(yùn)的是,趕巧遇到了以下兩本神作,對(duì)神經(jīng)網(wǎng)絡(luò)的本質(zhì)算是一知半解。
Python神經(jīng)網(wǎng)絡(luò)編程,塔里克.拉希德著,人民郵電出版社出版。
深度學(xué)習(xí)圖解,安德魯.特拉斯克著,清華大學(xué)出版社出版。
對(duì)于神經(jīng)網(wǎng)絡(luò)來說,選擇一個(gè)好的評(píng)估函數(shù)、訓(xùn)練函數(shù)、傳遞函數(shù)后,使用合適的大量的訓(xùn)練數(shù)據(jù)訓(xùn)練則成為關(guān)鍵。學(xué)習(xí)的關(guān)鍵在于調(diào)整網(wǎng)絡(luò)的權(quán)值使誤差最小。
看書至今,由于懶,代碼不曾寫過一行。今天是周日,桂林天寒地凍,山里風(fēng)大。看到了《深度學(xué)習(xí)圖解》的第6章,勾起了興趣,瞧一瞧書本上的樣例程序,照葫蘆畫瓢,越畫越像。
拋去所有背景知識(shí),直接上代碼。在書本的范例基礎(chǔ)上,引入了函數(shù)。模塊化編程,簡(jiǎn)單就是美。
# streetlightlearning.py
# Create a backprogation network to learn a streetlights
# author: andrew W.Trask & Icefish
import numpy as np
weights = np.array([0.5, 0.48, -0.7])
alpha = 0.1
# define input as streetlights and output as walk_vs_stop
streetlights = np.array([[1, 0, 1],
[0, 1, 1],
[0, 0, 1],
[1, 1, 1],
[0, 1, 1],
[1, 0, 1]])
walk_vs_stop = np.array([[0],
[1],
[0],
[1],
[1],
[0]])
##input_data = streetlights[0]
##goal_prediction = walk_vs_stop[0]
##
##for iteration in range(1000):
## prediction = input_data.dot(weights)
## error = (goal_prediction - prediction)**2
## delta = prediction - goal_prediction
## weights = weights - (alpha*(input_data*delta))
## print("Error:"+str(error)+"Prediction:"+str(prediction))
# 訓(xùn)練函數(shù),迭代次數(shù)可自定義
def train(iteration_times):
global weights
global streetlights
global walk_vs_stop
for iteration in range(iteration_times):
error_for_all_lights = 0
for row_index in range(len(walk_vs_stop)):
input_data = streetlights[row_index]
goal_prediction = walk_vs_stop[row_index]
prediction = input_data.dot(weights) # output of the network
error = (prediction - goal_prediction)**2
error_for_all_lights = error_for_all_lights + error
delta = prediction - goal_prediction
weights = weights - (alpha*(input_data*delta))
print("Prediction:"+str(prediction))
print("Error:"+str(error_for_all_lights)+"\n")
def sim(streetlights_input):
global weights;
return streetlights_input.dot(weights)
def main():
input_str = input("請(qǐng)輸入網(wǎng)絡(luò)訓(xùn)練迭代次數(shù):")
iteration_times = int(input_str)
if iteration_times>0 :
train(iteration_times)
else:
print("迭代次數(shù)輸入有誤,程序終止!")
return
#訓(xùn)練完成,提示用戶使用訓(xùn)練好的網(wǎng)絡(luò)
while(True):
a,b,c = input("輸入信號(hào)燈狀態(tài),用逗號(hào),隔開:").split(',')
a = int(a)
b = int(b)
c = int(c)
input_data = np.array([a,b,c])
prediction = sim(input_data)
status = int(round(prediction,0))
print("Prediction:"+str(status)+"\n")
if status == 1:
print("walk now is safe.\n")
else:
print("stop,or walk to hell.\n")
if __name__ == '__main__':
main()

運(yùn)行OK