import numpy as np
def model(X, y, alpha):
#计算X的维度
n, m = np.shape(X)
t = m
#给w,b赋予初值为0
w = (np.zeros(m)).reshape(m,1)
b = 0
print('w, b初始值:\nw = {0}, b = {1}'.format(w.ravel(),b))
#迭代
i = np.random.randint(m)
print('选择误分类点: X' + str(i+1))
num = 1
while m>0:
w = w + alpha * y[i] * X[i].reshape(t,1)
b = b + alpha * y[i]
print('第{0}次迭代后w, b的值:\nw = {1}, b = {2}'.format(num, w.ravel(),b))
F = np.ravel(y.reshape(len(y), 1) * (np.dot(X, w) + b))
m = len(np.where(F<0)[0])
if m != 0:
i = np.random.choice(np.where(F<0)[0])
print('选择误分类点: X' + str(i+1))
num += 1
print('全部分类正确')
return w, b
if __name__ == '__main__':
X = np.array([[3,3], [4, 3], [1, 1]])
y = np.array([1, 1, -1])
w, b = model(X, y, alpha=1)
输出结果如下:
w, b初始值:
w = [0. 0.], b = 0
选择误分类点: X2
第1次迭代后w, b的值:
w = [4. 3.], b = 1
选择误分类点: X3
第2次迭代后w, b的值:
w = [3. 2.], b = 0
选择误分类点: X3
第3次迭代后w, b的值:
w = [2. 1.], b = -1
选择误分类点: X3
第4次迭代后w, b的值:
w = [1. 0.], b = -2
全部分类正确