Menu
CoddyTech

Predicting Numbers

Part of the Supervised Learning section of Coddy's Machine Learning journey. Lesson 11 of 58.

This chapter's models predict numbers. By its end, a chart of a model's misses will expose what it overlooked:

A chart of a model's misses against the temperature: the dots arch from -280 up to +140 and back down, around a dashed line at 0, labelled: the model overlooked a curve

Start with a line you know. LinearRegression learns it from a table X, one row per sample and one column per feature:

from sklearn.linear_model import LinearRegression

area = np.array([60, 75, 90, 110, 130, 150])  # houses, in m²
price = np.array([215, 248, 290, 335, 385, 428])  # thousand dollars
X = area.reshape(-1, 1)  # 6 rows, 1 column
model = LinearRegression()
model.fit(X, price)
print(np.round(model.coef_, 2), np.round(model.intercept_, 2))
print(np.round(np.polyfit(area, price, 1), 2))

This prints the same line twice:

[2.39] 71.59
[ 2.39 71.59]

Six houses as dots, price against area, with the thick orange LinearRegression line and the dashed black np.polyfit line lying exactly on top of each other: price = 2.39 * area + 71.59

coef_ holds one slope per feature: each extra m² adds 2.39 thousand dollars. intercept_ is the line's start, at 0 m². Then model.predict([[100]]) prices 100 m² at about 310.85 thousand.

challenge icon

Challenge

Medium

A print shop never published its prices, but you have 10 past jobs: pages and price in dollars. The program reads the pages of a new job.

  1. Fit a LinearRegression on the pages, as a one-column table.
  2. Print the price per page (3 decimals) and the setup fee, the intercept (2 decimals).
  3. Print the new job's predicted price (2 decimals).

For another shop and 120:

Per page: 0.095 dollars
Setup fee: 4.1 dollars
120 pages: 15.5 dollars

Try it yourself

import numpy as np
from sklearn.linear_model import LinearRegression

# 10 past print jobs: pages printed and the price paid, in dollars
pages = np.array([40, 75, 120, 160, 210, 260, 300, 380, 450, 520])
price = np.array([7.38, 12.6, 17.65, 20.69, 26.63, 32.18, 37.76, 46.4, 55.17, 60.89])
new_pages = int(input())

# Write your code below
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Supervised Learning

Practice on your own: Online Python compiler