BLOGLLM Logo
Go Pro
Guest
Not signed in
所有博客课程练习面试准备系列标签书签价格
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboard游戏
Articles
练习 / Supervised models2 of 18 in topic

120. 运行一个 epoch 的感知器学习规则

EasySupervised models

感知器是最简单的线性分类器:它仅在分类错误时才会改变其 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,否则一个从零开始的模型将永远无法学习。

Worked example

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. 它是现代神经网络的鼻祖。
主题
Supervised models
相似题目
  • 通过最近邻的多数投票进行点分类Easy
  • 按最近类质心分类Easy
  • 计算单次分裂的信息增益Easy
  • 使用距离加权 k 最近邻投票进行分类Easy
所有 Supervised models 道题目
反馈
120 / 903
Python 3solution.pyPython 空闲
1
2
3
4
5
6
import numpy as np
​
def perceptron_epoch(X, y, w, b, lr):
# your code here
pass
​

Run 会在浏览器中检查这些用例,无需登录。 Submit 会检查所有 3 个测试。

Ctrl/按 + 回车 运行
© BlogLLM, Bengaluru, India关于条款隐私退款DMCA联系我们RSS