感知机python实现

看了《统计学习方法》自己实现下感知机算法:

import numpy as np

train = np.array([[3, 3], [4, 3], [1, 1]])
label = np.array([1, 1, -1])
omega = np.zeros(train.shape[1])

b = 0
alpha = 1
j = 0
i = 0

while(i < train.shape[0]):
    res = (np.dot(train[i], omega) + b) * label[i]
    if(res <= 0):
        omega += alpha * label[i] * train[i]
        b += alpha * label[i]
        print('迭代次数{0},误分类点x[{1}], w={2},b={3}, w*x + b={4}'.format(j + 1, i + 1, omega, b, res))
        j += 1
        i = 0
    else:
        i += 1
print('迭代次数{0},误分类点{1}, w={2},b={3}, w*x + b={4}'.format(j + 1, 0, omega, b, res))

你可能感兴趣的:(机器学习)