MyMisPal
← Practical AI lessons
Lesson 3 of 11

Your first model: forecasting sales with a straight line

Nakhla's question: “If we spend more on ads, how much will we sell?”. We have 8 months: ad spend (in thousands) and cartons sold (in hundreds). The simplest model is linear regression: draw the best straight line through the points.

sales = intercept + slope × ads

The slope is how much sales rise per thousand riyals of ads. The intercept is the expected sales with zero ad spend. Move the two sliders and try to lower the average error, then let the machine compute the best line:

305070901100246810Ads (thousand SAR)
sales = 30.0 + 4.00 × ads
Mean error (MAE)20.9

Try to lower the average error: the dashed lines are each month's errors.

The machine doesn't guess: a formula called least squares finds the line with the smallest sum of squared errors. Here is the same calculation in Python, with no libraries:

PYTHON
ads   = [2, 3, 4, 5, 6, 7, 8, 9]          # ad spend, thousand SAR
sales = [52, 58, 63, 71, 74, 83, 87, 95]  # cartons sold, hundreds

n = len(ads)
mx = sum(ads) / n
my = sum(sales) / n
top = 0
bottom = 0
for x, y in zip(ads, sales):
    top += (x - mx) * (y - my)
    bottom += (x - mx) ** 2

slope = top / bottom
intercept = my - slope * mx
print(f"sales = {intercept:.1f} + {slope:.2f} x ads")
print(f"Forecast for 10k SAR: {intercept + slope * 10:.0f}")
Watch outBeware of predicting outside your data: our model saw ad spend from 2k to 9k. Ask it about 100k and it will give you a number, but nothing guarantees the relationship stays straight. Markets saturate.
Watch outCorrelation isn't causation: if sales and ads rise together, the real cause might be the Ramadan season, not the ads themselves.

Exercises

Exercise 1 · Calculation

Nakhla's model: sales = 40 + 6 × ads. What are the forecast sales (in hundreds) for 10 thousand of ad spend?

hundred cartons
Exercise 2 · Multiple choice

In the same model, what does the 6 mean?

Exercise 3 · Python · graded by running

Write a function predict(ads) that returns the forecast from the model 40 + 6 × ads. (The checker calls it with different values and prints the result.)

Spotted a mistake on this page, or have an idea to improve the site?