import numpy as np
def func(x1, x2, y):
global w0, w1, w2, n0, n1, n2
a = 0.01
w0, w1, w2 = 1, 1, 1
n0, n1, n2 = 1, 1, 1
for i in range(200):
w0 = w0 - a * (summ(x1[i % 4], x2[i % 4]) - y[i % 4])
w1 = w1 - a * (summ(x1[i % 4], x2[i % 4]) - y[i % 4]) * x1[i % 4]
w2 = w2 - a * (summ(x1[i % 4], x2[i % 4]) - y[i % 4]) * x2[i % 4]
n0 = (summ(x1[i % 4], x2[i % 4]) - y[i % 4])
n1 = (summ(x1[i % 4], x2[i % 4]) - y[i % 4]) * x1[i % 4]
n2 = (summ(x1[i % 4], x2[i % 4]) - y[i % 4]) * x2[i % 4]
if (abs(n0) < 0.01 and abs(n1) < 0.01 and abs(n2) < 0.01):
print(w0, w1, w2)
print(n0, n1, n2)
break
def summ(x1, x2):
return w0 + w1 * x1 + w2 * x2
if __name__ == '__main__':
x1 = np.array([0, 0, 1, 1])
x2 = np.array([0, 1, 0, 1])
y = np.array([0, 0, 0, 1])
func(x1, x2, y)
运行结果: