🧠 AI with Python – 🏠 Predict House Prices with Linear Regression


Description:

A Real-World Application

One of the most common beginner ML problems is house price prediction. It teaches you:

  • Feature engineering (e.g., number of rooms, location).
  • Model training (Linear Regression or similar).
  • Performance evaluation.
Price = β0 + β1Size + β2Location + ... + ε

Why Is It Important?

It bridges theory and practice: you apply preprocessing, model training, and evaluation to solve an actual problem.


Practical Takeaway

Building a house price prediction model is a perfect ML practice project — it involves real-world datasets, preprocessing, and performance testing in one workflow.


Code Snippet:

# Import required libraries
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression

# Sample dataset
data = {
    'SquareFootage': [1500, 1800, 2400, 3000, 3500],
    'Bedrooms': [3, 4, 3, 5, 4],
    'Age': [10, 5, 20, 8, 2],
    'Price': [400000, 500000, 600000, 650000, 700000]
}

df = pd.DataFrame(data)
df

#%%
# Features (SquareFootage, Bedrooms, Age)
X = df[['SquareFootage', 'Bedrooms', 'Age']]

# Target (Price)
y = df['Price']

#%%
model = LinearRegression()
model.fit(X, y)

print("Coefficients:", model.coef_)
print("Intercept:", model.intercept_)

# New house: 2500 sq.ft, 4 bedrooms, 5 years old
new_house = [[2500, 4, 5]]
predicted_price = model.predict(new_house)

print(f"Predicted House Price: ${predicted_price[0]:,.2f}")

# Predict for training data
y_pred = model.predict(X)

# Scatter plot for actual vs predicted
plt.scatter(y, y_pred, color='blue')
plt.plot([y.min(), y.max()], [y.min(), y.max()], color='red', linestyle='--')
plt.xlabel("Actual Price")
plt.ylabel("Predicted Price")
plt.title("Actual vs Predicted House Prices")
plt.show()

Link copied!

Comments

Add Your Comment

Comment Added!