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:
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]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
MediumA 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.
- Fit a
LinearRegressionon the pages, as a one-column table. - Print the price per page (3 decimals) and the setup fee, the intercept (2 decimals).
- 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 dollarsTry 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
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Supervised Learning
1Your First Model
Learning from ExamplesTrain and Test SetsFit and PredictScoring a ModelRecap: Seed Sorter2Nearest Neighbors
How k-NN DecidesChoosing kDecision BoundariesScaling for NeighborsRecap: Wine Neighbors5Measuring Classifiers
The Confusion MatrixPrecision and RecallThe F1 ScoreImbalanced ClassesROC CurvesRecap: Screening Test11Project: Penguin Species
Meet the PenguinsPrepare the DataChoose a ModelTune the WinnerShip the Model3Linear Regression
Predicting NumbersSeveral FeaturesMeasuring ErrorsResidual PlotsRecap: Bike RentalsPractice on your own: Online Python compiler