Fit a line to house prices

Fit a straight line to six house prices, then compare your line with the best-fit line.

Artificial intelligence Intermediate Supervised learning · Linear regression ~8 min
The idea

Predict the price with a straight line

Linear regression fits a straight line when one number tends to rise with another. Here, a larger floor area tends to mean a higher sale price. The six houses do not sit on one straight line, so every line leaves some error.

The line is ŷ = mx + b. The slope m is how many thousand CHF the price rises for each extra square metre. The intercept b is the price the line gives at 0 m². ŷ is the predicted price. The residual is the observed price minus that prediction, y − ŷ.

Mean squared error (MSE) is the mean of the squared residuals. Squaring stops a house above the line from cancelling a house below it. The best-fit line is the ordinary least-squares line: the straight line with the smallest MSE. The starter line ŷ = 2x + 150 has MSE 2250. For these six houses the best-fit line is ŷ = 3.31x + 69.23, and its MSE is 545.51.

A line can look close and still lose to the best-fit line. Move one house far from the others, and the best-fit line swings toward that house. A prediction past the smallest or largest floor area is extrapolation: the line is used outside the houses it was fitted to.

TipPrices on the chart are in thousands of Swiss francs, so 300 means 300,000 CHF. Clustering does not predict a price. This page does, because each house already has one.
Go deeper

The best-fit slope and intercept are calculated from the houses, not from the line you drag. The best-fit line passes through the average floor area and the average sale price. If fewer than two houses remain, or they all share one floor area, there is no unique slope. The button turns off, and your line stays on the chart.

DataSix houses
HouseFloor area (m²)Sale price (CHF thousands)
Ash40210
Birch55250
Cedar70320
Dale85300
Elm100410
Fern120480

Dale is a little cheap for 85 m², so the points scatter around the trend.

Interactive

Fit the line

Drag the slope, the intercept, or a house. The line, the residuals, and the MSE change as you move them. Before you show the best-fit line, guess whether its MSE will be smaller.

Floor area and sale pricefit a line
House
Predict with

Enter a floor area to predict a sale price.

Remember

Error, then the smallest error

The line is a prediction. The residuals tell you where it misses.

Gap

Residual

The residual is y − ŷ. Positive means the house is above your line. Negative means it is below.

Score

Mean squared error

MSE squares each residual, then takes the mean. A house above the line cannot cancel a house below it.

Best

Best-fit line

The best-fit line has the smallest MSE. One house moved far from the others pulls that line toward it.