感知机代码

​
#Python 3.6
#author: ald
#
import numpy as np 

x = np.array([[3, 3],[4, 3],[1, 1],[5,2]])
y = np.array([1, 1, -1,-1])

Gamma = x.dot(x.T)

eta = 1
alpha = np.zeros(len(y), np.float)
b = 0
judge = False

def update(i):
    global b, alpha,eta,y
    alpha[i] += eta
    b += eta * y[i]

def check(i):
    global y,alpha,Gamma,b
    result = y[i] * (np.dot(alpha * y, Gamma[i]) + b) > 0
    return result

while not judge: #如果judge = False,表明上次循环发生过更新,要继续循环,直至上轮循环未发生更新
    judge = True
    for m in range(0,len(y)):
        while not check(m):
            judge = False
            update(m)
            
w = np.dot(alpha*y,x)
print('w:',str(w),'\nb:',b)

​
posted @ 2024-06-27 10:23  猫种鱼  阅读(14)  评论(0)    收藏  举报