BeginnerCoder

Lesson 18 — Gradient over a whole dataset

The gradient over a whole dataset

In Lesson 11 the model learned from a single example. Real training uses many. The loss is MSE over all examples, and its gradient for w is the average of 2 × error × x. One update that uses every example is a batch gradient step.

g = sum(2 * (k * h - p) * h for h, p in zip(hours, pay)) / len(hours)
k = k - rate * g

Watch the loss: if training works, it should drop every step.

Why it matters: "loss going down" is the main thing ML engineers watch while a model trains. If it goes up, the learning rate is usually too big.

Want it another way?
Task

Compute grad with the formula from the theory. The loss should shrink each step and w should approach 2.

Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.

Keep going with AI / ML Foundations

Ready for more? Optional paid resources that pick up where this lesson leaves off.

Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.