import numpy as np
w0 = 0.3
w1 = 0.3
w2 = 0.4
a = 0.01
x1 = np.array([2.104, 1.600, 2.400, 1.416, 3.000])
x2 = np.array([3, 3, 3, 2, 4])
y1 = np.array([4.00, 3.30, 3.69, 2.32, 5.40])
def my(x1, x2):
return w0 + w1 * x1 + w2 * x2
for i in range(1000):
w0 = w0 - a * (my(x1[i % 5], x2[i % 5]) - y1[i % 5])
w1 = w1 - a * (my(x1[i % 5], x2[i % 5]) - y1[i % 5]) * x1[i % 5]
w2 = w2 - a * (my(x1[i % 5], x2[i % 5]) - y1[i % 5]) * x2[i % 5]
gred0 = (my(x1[i % 5], x2[i % 5]) - y1[i % 5])
gred1 = (my(x1[i % 5], x2[i % 5]) - y1[i % 5]) * x1[i % 5]
gred2 = (my(x1[i % 5], x2[i % 5]) - y1[i % 5]) * x2[i % 5]
if (abs(gred0) < 0.01 and abs(gred1) < 0.01 and abs(gred2) < 0.01):
print(w0, w1, w2)
print(gred0, gred1, gred2)
break
(w0w1w2权值相加为1)
运行结果: