序言:常言道,在实践中学习,在理论中提升。辗辗转转看了几本神经网络的书,磕磕绊绊地了解了一些概念,对于神经网络还是懵懵懂懂。在matlab里跑代码,纯调用库函数,真的是闭着眼睛开车。幸运的是,赶巧遇到了以下两本神作,对神经网络的本质算是一知半解。
Python神经网络编程,塔里克.拉希德著,人民邮电出版社出版。
深度学习图解,安德鲁.特拉斯克著,清华大学出版社出版。
对于神经网络来说,选择一个好的评估函数、训练函数、传递函数后,使用合适的大量的训练数据训练则成为关键。学习的关键在于调整网络的权值使误差最小。
看书至今,由于懒,代码不曾写过一行。今天是周日,桂林天寒地冻,山里风大。看到了《深度学习图解》的第6章,勾起了兴趣,瞧一瞧书本上的样例程序,照葫芦画瓢,越画越像。
抛去所有背景知识,直接上代码。在书本的范例基础上,引入了函数。模块化编程,简单就是美。
# 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))
# 训练函数,迭代次数可自定义
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("请输入网络训练迭代次数:")
iteration_times = int(input_str)
if iteration_times>0 :
train(iteration_times)
else:
print("迭代次数输入有误,程序终止!")
return
#训练完成,提示用户使用训练好的网络
while(True):
a,b,c = input("输入信号灯状态,用逗号,隔开:").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()