The objective of working with the California Housing Prices dataset is to predict median housing prices of California districts based on a set of features. This is a regression problem where the goal is to model the relationship between housing prices (the target variables) and various features(predictors).
| Column Name | Description | Type | Example Value |
|---|---|---|---|
MedInc | Median income of households (scaled) | Continuous | 3.87 |
HouseAge | Median age of houses in the block group | Continuous | 15 |
AveRooms | Average number of rooms per household | Continuous | 6.98 |
AveBedrms | Average number of bedrooms per household | Continuous | 1.02 |
Population | Total population in the block group | Continuous | 322 |
AveOccup | Average number of people per household | Continuous | 2.56 |
Latitude | Geographical latitude of the block group | Continuous | 37.88 |
Longitude | Geographical longitude of the block group | Continuous | -122.23 |
MedHouseVal | Median house value (in $100,000s) (Target) | Continuous | 4.52 |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
california = fetch_california_housing()
X = pd.DataFrame(california.data, columns=california.feature_names)
y = california.target
print(X.head())

print(y[:5])
# Prints the first 5 values of the target variable y.
# [4.526 3.585 3.521 3.413 3.422]
X_simple = X[['MedInc']]
X_train, X_test, y_train, y_test = train_test_split(X_simple, y, test_size=0.2, random_state=42)
random_state = 42 means that the same split will occur each time the code is run, making experiments consistent. The number doesn't matter. You can put any numbers.
output
model = LinearRegression()
model.fit(X_train, y_train)

y_pred = model.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
print(f"\nMean Squared Error: {mse:.2f}")
print(f"R-squared: {r2:.2f}")
# Mean Squared Error: 0.71
# R-squared: 0.46
plt.scatter(X_test, y_test, color='blue', label='Actual Data')
plt.plot(X_test, y_pred, color='red', label='Regression Line')
plt.title("Linear Regression: MedInc vs House Value")
plt.xlabel("Median Income")
plt.ylabel("Median House Value")
plt.legend()
plt.show()

- The scatter and saturation at higher house values indicate that a simple linear regression may not fully capture the complexity of the relationship.
- There may be other factors (e.g., location, population) influencing house prices that are not included in this model.
- Let's condider trying a nonlinear regression model or polynomial regresion
- Include additional features (e.g., location, house age) to improve predictions.
california = fetch_california_housing()
X = pd.DataFrame(california.data, columns=california.feature_names)
y = california.target
# select variables
X_selected = X[['MedInc', 'HouseAge', 'AveRooms', 'AveOccup']]
X_train, X_test, y_train, y_test = train_test_split(X_selected, y, test_size=0.2, random_state=42)
model = LinearRegression()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
print(f"Mean Squared Error: {mse:.2f}")
print(f"R-squared: {r2:.2f}")
# Mean Squared Error: 0.66
# R-squared: 0.50
plt.scatter(y_test, y_pred, color='blue', alpha=0.6)
plt.plot([0, 5], [0, 5], color='red', linestyle='--') # 1:1 선
plt.title("Actual vs Predicted Values")
plt.xlabel("Actual Median House Value")
plt.ylabel("Predicted Median House Value")
plt.show()

- By incorporating additional features, the model accounts for more variability in house prices, as shown by the closer clustering of points around the diagonal line.
- While it performs better, multiple regression models are harder to interpret due to the involvement of several features.
- Some points are far from the red dashed line, indicating that the model still has errors or might struggle with certain data points
The goal is to predict the median housing value(MedHouseVal) of California district based on demographic and geographic attributes. This is a supervised regression problem, as the target variable is continuous.
- If the goal is interpretability and simplicity, Simple Linear Regression is better. It shows a straightforward relationship between MedInc and house prices.
- If the goal is better prediction and accuracy, Multiple Linear Regression is better. It leverages more features, providing a closer match between predicted and actual values.
https://www.kaggle.com/datasets/camnugent/california-housing-prices