Module 10 · Machine learning: linear regression · Lesson 45 of 66

Linear regression: house prices

Predict house prices from neighborhood facts, read the coefficients, and measure the error.

In this lesson · about 25 minutes

  • Split data and fit a LinearRegression model
  • Interpret the intercept and coefficients
  • Judge predictions with a scatter plot, residuals, MAE, MSE and RMSE

Linear regression predicts a number as a weighted sum of the features: price = intercept + c₁ × income + c₂ × house age + …. Fitting finds the weights (coefficients) that make the predictions as close as possible to the real prices on the training data, by minimizing the squared errors.

Our data has 5,000 made-up neighborhoods: average income, house age, rooms, bedrooms, population, and the average house price.

Look before you model

Exercise

Features and label

Make X from the five number columns 'Avg. Area Income', 'Avg. Area House Age', 'Avg. Area Number of Rooms', 'Avg. Area Number of Bedrooms' and 'Area Population', and y from 'Price'. (Address is text, so it stays out.)

Code that runs before yours
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
USAhousing = pd.read_csv('USA_Housing.csv')

Exercise

Split and fit

Split X and y with test_size=0.4 and random_state=101. Then create a LinearRegression called lm and fit it to the training data.

Code that runs before yours
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
USAhousing = pd.read_csv('USA_Housing.csv')
X = USAhousing[['Avg. Area Income', 'Avg. Area House Age', 'Avg. Area Number of Rooms',
                'Avg. Area Number of Bedrooms', 'Area Population']]
y = USAhousing['Price']

Reading the coefficients

Each coefficient says how much the prediction changes when that feature goes up by one unit and the others stay the same. Put them in a table to read them easily.

For example, a coefficient of about 21.5 for Avg. Area Income means each extra dollar of average income adds about $21.50 to the predicted price, holding the rest fixed. One more room adds about $120,000. (Bedrooms look small because they rise with rooms; the two overlap.)

Predictions and errors

Plot the predictions against the real prices: a good model gives a tight diagonal line. The residuals (real minus predicted) should look like a bell curve centered on zero.

Three error measures

  • MAE, mean absolute error: the average size of the errors. Easiest to understand.
  • MSE, mean squared error: squares each error first, so big misses count much more. Its units are squared dollars, which is hard to read.
  • RMSE, root mean squared error: the square root of MSE, back in dollars. The most popular choice.

All three are errors, so lower is better. They live in sklearn.metrics.

Exercise

Measure the error

Predict on X_test, then compute the RMSE and make it the last line. Use metrics.mean_squared_error and np.sqrt.

Code that runs before yours
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
USAhousing = pd.read_csv('USA_Housing.csv')
X = USAhousing[['Avg. Area Income', 'Avg. Area House Age', 'Avg. Area Number of Rooms',
                'Avg. Area Number of Bedrooms', 'Area Population']]
y = USAhousing['Price']
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=101)
lm = LinearRegression()
lm.fit(X_train, y_train)

Exercises solved: 0 of 3

Tip: solve each exercise first. Press Check to test your code.

Noviq Academy's Data Science course is free and for learning. Python runs in your browser with Pyodide, which downloads about 20 MB the first time, plus a few more for scikit-learn. Your code and progress stay on this device. The salaries data is a sample of San Francisco's public pay records; the purchases, customers, housing, advertising and classified data are made up. The Titanic, tips, flights and iris data sets come from Seaborn's examples; the maps use public 2011 to 2014 US and world figures. The 911 data is a 20,000-call sample of Montgomery County, Pennsylvania's public 911 records; the movie ratings are the MovieLens 100K data from GroupLens Research; the reviews are a 3,000-review sample from the Yelp Dataset Challenge; the loans are public LendingClub data; the colleges are the College data from An Introduction to Statistical Learning; the bank notes, kyphosis and breast cancer data come from the UCI Machine Learning Repository. Spark and TensorFlow can't run in a browser, so those lessons use stand-ins that run here, and show the code for the real tools.