import numpy as np
def data_set(n, p, seed=20220227): # 构造数据集,特征矩阵shape=(n, p)
np.random.seed(seed)
w = np.random.uniform(-3, 3, p)
b = np.random.uniform(-3, 3, 1)
x = np.random.uniform(-10, 10, (n, p))
y = np.apply_along_axis(lambda s: 1 if (s*w).sum()+b >= 0 else -1, axis=1, arr=x)
return x, y, np.concatenate((w, b))
def perception(x, y, lr=0.6): # x为特征矩阵,y为label(一维数组)
n, p = x.shape
w = np.zeros(p)
b = np.zeros(1)
i = 0
while not (np.where(((x*w).sum(axis=1)+b) >= 0, 1, -1) == y).all():
row = np.random.randint(0, n, 1)[0]
if ((x[row]*w).sum()+b)*y[row] <= 0:
w = w+lr*y[row]*x[row]
b = b+lr*y[row]
i += 1
return np.concatenate((w, b)), i
def perception_dual(x, y, lr=3): # x为特征矩阵,y为label(一维数组
感知机python代码
于 2022-03-01 16:44:46 首次发布