当样本大小设置为10时,直到收敛的平均迭代次数应该在15左右.然而,当在我的代码中实现该算法时,大约需要225次(或更多)迭代才能达到收敛.这使我怀疑代码中的While循环可能有问题,但我无法识别它.
def gen_data(N=10):
size = (N, 2)
data = np.random.uniform(-1, 1, size)
point1, point2 = data[np.random.choice(data.shape[0], 2, replace=False), :]
m = (point2[1] - point1[1]) / (point2[0] - point1[0])
c = point1[1] - m * point1[0]
labels = np.array([+1 if y >= m * x + c else -1 for x, y in data])
data = np.column_stack((data, labels))
return data, point1, point2
class PLA:
def __init__(self, data):
m, n = data.shape
self.X = np.hstack((np.ones((m, 1)), data[:, :2]))
self.w = np.zeros(n)
self.y = data[:, -1]
self.count = 0
def fit(self):
while True:
self.count += 1
y_pred = self.predict(self.X)
misclassified = np.where(y_pred != self.y)[0]
if len(misclassified) == 0:
break
idx = np.random.choice(misclassified)
self.update_weight(idx)
def update_weight(self, idx):
self.w += self.y[idx] * self.X[idx]
def sign(self, z):
return np.where(z > 0, 1, np.where(z < 0, -1, 0))
def predict(self, x):
z = np.dot(x, self.w)
return self.sign(z)