import numpy as np
a = 0.001
w0 = 0.6
w1 = 0.6
x1 = np.array([0,0,1,1])
x2 = np.array([0,1,0,1])
t = np.array([0,0,0,1])
y = np.array([0,1,1,1])
def mysum(x1,x2):
sum = w0 * x1 + w1 * x2
return sum
def activity():
if (mysum(x1,x2) > 0):
return 1
else:
return 0
for i in range(1000): # 迭代循环1000次
w0 = w0 - (mysum(x1[i % 4], x2[i % 4]) - t[i % 4]) * x1[i % 4] * a
w1 = w1 - (mysum(x1[i % 4], x2[i % 4]) - t[i % 4]) * x2[i % 4] * a
g0 = mysum(x1[i % 4], x2[i % 4]) - t[i % 4]
g1 = (mysum(x1[i % 4], x2[i % 4]) - t[i % 4]) * x1[i % 4]
g2 = (mysum(x1[i % 4], x2[i % 4]) - t[i % 4]) * x2[i % 4]
avg = (abs(g0) + abs(g1) + abs(g2)) * 1/3
while abs(g0) < a and abs(g1) < a and abs(g2) < a :
print(g0, g1, g2) # 输出最终的梯度g0,g1,g2
print('平均误差为:' + str(avg))
break