120. 运行一个 epoch 的感知器学习规则
感知器是最简单的线性分类器:它仅在分类错误时才会改变其 weights。它仍然是理解错误驱动更新(mistake-driven updates)机制的一个很好的思维模型。
编写 perceptron_epoch(X, y, w, b, lr)。X 的 shape 为 (n, d),标签 y 为 -1 或 +1,w 的 shape 为 (d,),b 是一个 float。按顺序访问点 i = 0, 1, ..., n - 1。当 y_i * (w @ x_i + b) <= 0 时,该点被视为一次 mistake(得分为 0 恰好也计为一次 mistake)。发生 mistake 时,设置 w = w + lr * y_i * x_i 和 b = b + lr * y_i,然后使用更新后的 weights 继续处理后续点。
返回 (w, b, mistakes),其中 w 是一个新数组(不要修改输入),b 是一个 float,mistakes 是更新次数的 int 计数。
def perceptron_epoch(X, y, w, b, lr)示例 1
X = [[1, 0], [0, 1]], y = [1, -1], w = [0, 0], b = 0, lr = 1. Point 0 has score 0, so update to w = [1, 0], b = 1. Point 1 has score 1 with label -1, so update to w = [1, -1], b = 0. Result ([1, -1], 0.0, 2).
约束条件
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 3 tests to be accepted.
提示 1
The perceptron only changes its weights on a mistake, and each update is used right away for the next point.
提示 2
Copy w, then loop over the rows in order, compute the signed margin y_i * (w @ x_i + b), and on a mistake update w and b and count it.
提示 3
Use <= 0 so a score of exactly 0 counts as a mistake, and start from np.array(w, dtype=float) so the caller's array is not modified.
常见错误
- 那是带有 bug 的版本。
理解思路
感知器是一种仅从错误中学习的线性分类器。对于每个按顺序出现的点,它会检查 w . x + b 的符号是否与标签 (+1 或 -1) 一致。如果不一致,它会通过向 w 添加 lr * y * x 以及向 b 添加 lr * y 来微调边界,从而使该点分类正确。得分为 0 恰好也计为一次 mistake,否则一个从零开始的模型将永远无法学习。
X = [[1, 1], [2, -1]], y = [-1, 1], w = [0, 0], b = 0, lr = 1. Point 0: score 0, so y * score = 0 <= 0, mistake. w = [0, 0] - [1, 1] = [-1, -1], b = -1. Point 1: score = (-1)(2) + (-1)(-1) - 1 = -2, label +1, mistake. w = [-1, -1] + [2, -1] = [1, -2], b = 0. Result ([1, -2], 0.0, 2 mistakes).
if y_i (w . x_i + b) <= 0, then w += lr y_i x_i and b += lr y_i; use the updated w for later points; do not modify the input array. 它是现代神经网络的鼻祖。