Lessons › Projects
House price predictor
A linear regression model that prices a house from its size, rooms and age, with error measured in rupees.
No setup needed. Run every step in your browser on Gradient Lab, or download it.
Open the notebookLevel: Beginner · Time: 30 min · You’ll practise: pandas, linear regression, MAE and RMSE, reading coefficients
Steps
1. Create a table of 300 houses
Create 300 synthetic houses and save them as houses.csv, so you can open the data in Excel or Sheets too.
rng = np.random.default_rng(7)
n = 300
size = rng.uniform(40, 220, n) # square metres
rooms = np.clip((size / 35 + rng.normal(0, 0.8, n)).round(), 1, 7)
age = rng.uniform(0, 60, n) # years
price = 1200 * size + 8000 * rooms - 900 * age + 30000 + rng.normal(0, 15000, n)
houses = pd.DataFrame({"size": size.round(), "rooms": rooms, "age": age.round(), "price": price.round(-3)})
houses.to_csv("houses.csv", index=False)
print(houses.head())
print(f"Saved houses.csv with {len(houses)} rows")2. Features (clues) and label
Pick the feature columns and the label column, then split into training and test sets.
X = houses[["size", "rooms", "age"]] y = houses["price"] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1)
3. Fit the best straight line (plane) through the data
Fit a linear regression. Each coefficient tells you how much one extra unit of that feature adds to the price.
model = LinearRegression().fit(X_train, y_train)
for name, w in zip(X.columns, model.coef_):
print(f"Each extra unit of {name:<5} changes the price by {w:>9,.0f}")
print(f"Starting price (intercept): {model.intercept_:,.0f}")4. How wrong is it on houses it has never seen?
Measure the error on unseen houses: the average miss (MAE) and the root mean squared error (RMSE), which punishes big misses more.
pred = model.predict(X_test)
print(f"Mean absolute error: {mean_absolute_error(y_test, pred):,.0f}")
print(f"Root mean squared error: {mean_squared_error(y_test, pred) ** 0.5:,.0f}")5. Price a new house
Price a brand-new house that isn’t in the data.
new = pd.DataFrame({"size": [120], "rooms": [3], "age": [10]})
print(f"Estimated price for a 120 m2, 3-room, 10-year-old house: {model.predict(new)[0]:,.0f}")6. Plot predicted vs real prices
Plot predicted against real prices. Points close to the red line are good predictions.
plt.figure(figsize=(5, 5))
plt.scatter(y_test, pred, alpha=.6)
lims = [y.min(), y.max()]
plt.plot(lims, lims, "r--", label="perfect predictions")
plt.xlabel("real price"); plt.ylabel("predicted price"); plt.legend(); plt.tight_layout()
plt.savefig("predicted_vs_real.png")
print("Saved predicted_vs_real.png")Expected output
$ python house_prices.py
size rooms age price
0 153.0 5.0 56.0 186000.0
1 201.0 6.0 17.0 304000.0
2 180.0 5.0 54.0 250000.0
3 81.0 2.0 41.0 91000.0
4 94.0 4.0 51.0 125000.0
Saved houses.csv with 300 rows
Each extra unit of size changes the price by 1,166
Each extra unit of rooms changes the price by 8,665
Each extra unit of age changes the price by -840
Starting price (intercept): 30,251
Mean absolute error: 11,596
Root mean squared error: 13,881
Estimated price for a 120 m2, 3-room, 10-year-old house: 187,738
Saved predicted_vs_real.pngStretch goals
- Add a new feature such as “has parking” to the generator and to the model.
- Try
RandomForestRegressorand compare the error. - Replace the synthetic data with a real housing CSV from Kaggle.