import random
import math
import numpy as np
rate = 0.0001
X = [[1, 1, 1],
[1, 0, 0],
[1, 1, 0],
[1, 0, 1]]
t = [1, 0, 0, 0]
m = len(X)
weights = [random.random(), random.random(), random.random()]
delta = [5, 5, 5]
epsilon = 1e-6
# 计算样本值
def predict(i):
res = 0
res = X[i][0] * weights[0] + X[i][1] * weights[1] + X[i][2] * weights[2]
return res
# 激活函数
def sigmoid(x):
return 1.0 / (1.0 + math.pow(math.e, -x))
count = 0
for j in range(1000):
flag = False
for i in range(3):
if delta[i] < epsilon:
flag = True
break
if flag:
break
count += 1
print("迭代%d次" % count)
for i in range(m):
for j in range(3):
delta[j] = 2 * (sigmoid(predict(i)) - t[i]) * sigmoid(predict(i)) * (1 - sigmoid(predict(i))) * (
X[i][0] + X[i][1] + X[i][2])
weights[0] = weights[0] - rate * delta[0]
weights[1] = weights[1] - rate * delta[1]
weights[2] = weights[2] - rate * delta[2]
for i in range(3):
print(weights[i])
08-22
689
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
04-09