import numpy as np
# 样本和标签
X = np.array([[3, 3],
[4, 3],
[1, 1]])
y = np.array([1, 1, -1])
# 初始化
w = np.array([3.0, 3.0])
b = -1.0
eta = 1 # 学习率
def predict(x):
return np.sign(np.dot(w, x) + b)
iteration = 0
while True:
error_count = 0
for i in range(len(X)):
if y[i] * (np.dot(w, X[i]) + b) <= 0: # 误分类
w = w + eta * y[i] * X[i]
b = b + eta * y[i]
iteration += 1
print(f"迭代{iteration}: w={w}, b={b}")
error_count += 1
if error_count == 0:
print("训练收敛!")
break
print(f"最终结果: w={w}, b={b}")
文章字数:393
阅读时间: 1 分钟
等 人表示很赞
评论