Lesson 12 of 18 · 2 min
Multiple Linear Regression
Formula: Price = b0 + b1×Area + b2×Bedrooms + b3×Bathrooms + ...
Each coefficient (b1, b2...) tells you: "if this feature increases by 1 unit, how much does price change, holding everything else constant?"
import pandas as pd
import numpy as np
from sklearn.datasets import fetch_california_housing
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_absolute_error, mean_squared_error
import matplotlib.pyplot as plt
# Load California Housing Dataset (built into sklearn)
housing = fetch_california_housing()
df = pd.DataFrame(housing.data, columns=housing.feature_names)
df["Price"] = housing.target # price in $100,000s
print(df.head())
print(df.shape) # (20640, 9)
print(df.describe())
# Features and target
X = df.drop("Price", axis=1) # all columns except price
y = df["Price"] # what we want to predict
# Split: 80% train, 20% test
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
print(f"Training rows: {len(X_train)}")
print(f"Testing rows: {len(X_test)}")
# Build model
model = LinearRegression()
model.fit(X_train, y_train) # learn from training data
# See coefficients
coef_df = pd.DataFrame({"Feature": X.columns, "Coefficient": model.coef_})
print(coef_df)
print(f"Intercept: {model.intercept_:.4f}")
# Output: Coefficient: [1.2534] Intercept: -12.8431
# Predict on test set
y_pred = model.predict(X_test)
# Compare actual vs predicted
results = pd.DataFrame({"Actual": y_test.values[:10], "Predicted": y_pred[:10]})
print(results)
# Output: Predicted prices (first 3): [312450. 287230. 398760.]