前段时间看完了《人工智能》这本书,其中对神经网络和遗传算法比较感兴趣,所以就试着回过头去仔细认真的看,并总结归纳
今天用python,按照书上介绍的感知机的步骤敲了代码,初步实现了,但是由于太久没敲代码加上刚接触python,代码难看的不行,大神勿喷哈哈哈,下面是代码
def stepFunc(x): #定义阶跃函数
if x > 0:
return 1
else:
return 0
def trainning():
#初始化权重、阈值和学习速度
weight = [0.5,0.5]
threshold = 0.2
learning_rate = 0.1
#设置训练数据
trainning_X = [[0,0],[0,1],[1,0],[1,1]]
trainning_Y = [0,0,0,1]
#误差总和变量
bias = 1
y = 0 #记录实际输出
p = 1 #记录迭代次数
while bias != 0:
print("第",p,"次迭代")
bias = 0
e = 0
i = 0
for x in trainning_X:
X = x[0] * weight[0] + x[1] * weight[1] - threshold
y = stepFunc(X)
#误差e = 期望输出 - 实际输出
e = trainning_Y[i] - y
if e != 0:
# 调整权重
weight[0] += learning_rate * x[0] * e
weight[1] += learning_rate * x[1] * e
bias += abs(e)
i += 1
print("x:", x, " y:", y, " 误差:", e," 修改后权重:w1:",weight[0]," w2:",weight[1])
print("此次迭代误差总和为",bias)
p += 1
print("训练结束")
return weight,threshold
def predict(test_X):
print("测试数据:",test_X)
print("预测如下:")
for x in test_X:
X = x[0] * weight[0] + x[1] * weight[1] - threshold
y = stepFunc(X)
print("x:", x, " y:", y)
weight,threshold = trainning()
test_X = [[1,0],[0,1],[1,1],[0,0]] #测试数据
predict(test_X)
实验结果:
记录总结一下这个过程,明天试着写写多层神经网络(后向传送训练算法)