import math
import numpy as np
import random
def sigmod(a):
return 1/(1+math.exp(-a))
e0 = 0
e1 = 0
e2 = 0
w0 = random.random()
w1 = random.random()
w2 = random.random()
w = np.array([w1, w1])
x = np.array([[0,0],[0,1],[1,0],[1,1]])
t = np.array([0,1,1,1])
alpha = 0.001
eps = 1e-6
i = 0
while abs(e0) >= eps or abs(e1) >=eps or abs(e2)>= eps :
q = np.sum((x[i] * w))
e0 = (1 - sigmod(q + w0)) * sigmod(q + w0) * ((sigmod(q + w0) - t[i]))
e1 = (1 - sigmod(q + w0)) * sigmod(q + w0) * ((sigmod(q + w0) - t[i])) * x[i][0]
e2 = (1 - sigmod(q + w0)) * sigmod(q + w0) * ((sigmod(q + w0) - t[i])) * x[i][1]
i += 1
if i > 3 :
i = 0
w0 = w0 - alpha * e0
w1 = w1 - alpha * e1
w2 = w2 - alpha * e2
w = np.array([w1,w2])
print(w0,w1,w2)
print(sigmod(w0 + w1 * 0 + w2 * 0))
print(sigmod(w0 + w1 * 0 + w2 * 1))
print(sigmod(w0 + w1 * 1 + w2 * 0))
print(sigmod(w0 + w1 * 1 + w2 * 1))
运行结果如下图
?
|