Code / AI & ML Basics / Unit 3: Learning a line

The perceptron: a tiny neuron Perceptron: एक नन्हा न्यूरॉन

Lesson 9 of 13 · about 20 minutes · Weights, bias, a step function and the update rule.

⚡ 0 XP

Step 1 of 2

Weights, bias and a yes/no

if ?true ✓else ✗

A perceptron is the great-grandparent of neural networks. It takes some inputs, multiplies each by a weight, adds a bias, and says yes or no:

z = w[0] × x0 + w[1] × x1 + b

output = 1 if z > 0, else 0 (the step function)

Example (made-up): inputs are hours studied and hours slept; output 1 means “will pass”. A big weight means that input matters a lot; the bias sets how easy it is to say yes.

🎯 Challenge: Fire or not? +15 XP

Write two functions:

  • stepFn(z) returns 1 if z > 0, otherwise 0
  • perceptronPredict(w, b, p) returns stepFn(w[0] * p[0] + w[1] * p[1] + b) for a 2-D point p

Try twice to unlock the solution (0/2)

script.jsCtrl ⏎
Console

Output from console.log appears here.

Checklist

Press Run to check your code.

  • stepFn: positive → 1, zero or negative → 0
  • [3, 3] with w = [1, 1], b = −5 → 1
  • [2, 2] → 0, and weights matter
Lesson notes (text version)

1. Weights, bias and a yes/no

A perceptron is the great-grandparent of neural networks. It takes some inputs, multiplies each by a weight, adds a bias, and says yes or no:

z = w[0] × x0 + w[1] × x1 + b

output = 1 if z > 0, else 0 (the step function)

Example (made-up): inputs are hours studied and hours slept; output 1 means “will pass”. A big weight means that input matters a lot; the bias sets how easy it is to say yes.

Challenge: Fire or not?

Write two functions:

  • stepFn(z) returns 1 if z > 0, otherwise 0
  • perceptronPredict(w, b, p) returns stepFn(w[0] * p[0] + w[1] * p[1] + b) for a 2-D point p

2. Learning from mistakes

How does the perceptron find good weights? It learns from its mistakes:

  1. start with w = [0, 0], b = 0
  2. for each example: predict, then err = label − prediction (0 if right, +1 or −1 if wrong)
  3. nudge: w[0] += lr × err × x0, w[1] += lr × err × x1, b += lr × err
  4. go through all examples again (each pass is an epoch)

If the prediction was right, err is 0 and nothing changes. If the yes/no groups can be split by a straight line, this rule is guaranteed to find one.

Challenge: Train the perceptron

stepFn and perceptronPredict are ready. Write trainPerceptron(data, epochs, lr) where each row is { point: [x0, x1], label: 0 or 1 }. Start with w = [0, 0] and b = 0; for each epoch, go through the rows in order and apply the update rule. Return { w, b }.

Search by task, format or tool name.