Linear Regression Model for House Price Prediction Based on Size
In this tutorial, we will build a simple linear regression model to predict house prices based on the size in square feet. We'll go through each step of the process, explaining what is happening in the code.
Step 1: Import Necessary Libraries
First, we need to import the essential libraries for data manipulation, visualization, and building the regression model.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
numpy and pandas: Used for data manipulation and analysis.
matplotlib.pyplot: Used for data visualization.
sklearn.linear_model.LinearRegression: Provides the linear regression modeling tool.
sklearn.model_selection.train_test_split: Used to split the dataset into training and testing sets.
Step 2: Generate Synthetic Dataset
Since we don't have an actual dataset, we'll generate a synthetic one for demonstration purposes.
# Generate synthetic data for house sizes (in square feet) and prices
np.random.seed(0) # For reproducibility
# House sizes between 500 and 3500 sqft
sizes = np.random.randint(500, 3500, 100)
# Prices as a function of size with some added noise
prices = sizes * 200 + np.random.normal(0, 50000, 100)
np.random.seed(0): Ensures that the random numbers are the same every time you run the code.
sizes: An array of 100 random integers representing house sizes between 500 and 3500 square feet.
prices: Calculated by multiplying each size by $200 (assuming a price per sqft) and adding some random noise to simulate real-world data variability.
Step 3: Create a DataFrame
We will organize the synthetic data into a pandas DataFrame for easier handling.
# Create a DataFrame
data = pd.DataFrame({'Size': sizes, 'Price': prices})
data: A DataFrame containing two columns:
Size: The size of the house in square feet.
Price: The price of the house in dollars.
Step 4: Explore the Data
Let's take a quick look at the first few rows of our dataset to ensure it has been created correctly.
# Display the first five rows of the dataset
data.head()
Output:
Size Price
0 2794 602903.962271
1 3093 637689.009481
2 1881 400046.240997
3 2739 563486.278293
4 2097 396556.633615
Step 5: Visualize the Data
Visualizing the data helps us understand the relationship between the variables.
# Plot the data
plt.figure(figsize=(8,6))
plt.scatter(data['Size'], data['Price'], color='blue')
plt.xlabel('Size (sqft)')
plt.ylabel('Price ($)')
plt.title('House Price vs. Size')
plt.show()
- Scatter Plot: Shows the relationship between house size and price.
- Observation: We expect to see a positive correlation – as size increases, price generally increases.
[image: Scatter Plot]
(Note: In an actual Jupyter notebook, the plot would display here.)
Step 6: Separate Features and Target Variable
We need to define our feature(s) and the target variable for modeling.
# Define features and target variable
X = data[['Size']] # Features (independent variable)
y = data['Price'] # Target variable (dependent variable)
X: A DataFrame containing the features (in this case, just 'Size'). Note that we use double brackets to keep X as a 2D array, which is required by scikit-learn.
y: A Series containing the target variable ('Price').
Step 7: Split the Data into Training and Testing Sets
We split the data to evaluate our model's performance on unseen data.
# Split data into training and testing sets (80% train, 20% test)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
train_test_split: Splits arrays or matrices into random train and test subsets.
test_size=0.2: 20% of the data is used for testing.
random_state=0: Controls the shuffling applied to the data before splitting for reproducibility.
Step 8: Create and Train the Linear Regression Model
Now, we'll create an instance of the linear regression model and train (fit) it using the training data.
# Create an instance of LinearRegression
model = LinearRegression()
# Train the model using the training data
model.fit(X_train, y_train)
model.fit(X_train, y_train): Fits the linear model to the training data.
Step 9: Examine Model Coefficients
Let's look at the learned parameters of our model.
# Get the model parameters
intercept = model.intercept_
coefficient = model.coef_[0]
print(f'Intercept: {intercept}')
print(f'Coefficient: {coefficient}')
Output:
Intercept: 4895.026223282718
Coefficient: 198.9900486248098
intercept: The estimated price when the size is 0 (the y-intercept of the regression line).
coefficient: The estimated increase in price for each additional square foot.
Step 10: Make Predictions on the Test Set
We use the trained model to predict house prices from the test set.
# Make predictions using the testing data
y_pred = model.predict(X_test)
y_pred: An array of predicted prices corresponding to the sizes in X_test.
Step 11: Compare Actual and Predicted Prices
Create a DataFrame to compare the actual prices with the predicted prices.
# Create a DataFrame to compare actual and predicted prices
comparison = pd.DataFrame({'Actual Price': y_test, 'Predicted Price': y_pred})
comparison.head()
Output:
Actual Price Predicted Price
26 223718.609336 223223.498053
86 316403.007693 329165.549480
2 400046.240997 380057.613436
55 509335.919663 485575.719393
75 640347.607826 602614.625838
Step 12: Visualize the Training Data with Regression Line
Plotting the regression line over the training data helps visualize how well the model fits.
# Plot the regression line with the training data
plt.figure(figsize=(8,6))
plt.scatter(X_train, y_train, color='blue', label='Training Data')
plt.plot(X_train, model.predict(X_train), color='red', linewidth=2, label='Regression Line')
plt.xlabel('Size (sqft)')
plt.ylabel('Price ($)')
plt.title('Regression Line on Training Data')
plt.legend()
plt.show()
[image: Training Data with Regression Line]
Step 13: Plot Actual vs. Predicted Prices on Test Data
Visualizing actual vs. predicted prices helps assess the model's performance.
# Plot actual vs. predicted prices
plt.figure(figsize=(8,6))
plt.scatter(X_test, y_test, color='gray', label='Actual Price')
plt.scatter(X_test, y_pred, color='red', label='Predicted Price')
plt.xlabel('Size (sqft)')
plt.ylabel('Price ($)')
plt.title('Actual vs. Predicted Prices on Test Data')
plt.legend()
plt.show()
[image: Actual vs Predicted Prices]
Step 14: Evaluate the Model
Finally, we evaluate the model's performance using standard regression metrics.
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
# Calculate evaluation metrics
mae = mean_absolute_error(y_test, y_pred) # Mean Absolute Error
mse = mean_squared_error(y_test, y_pred) # Mean Squared Error
rmse = np.sqrt(mse) # Root Mean Squared Error
r2 = r2_score(y_test, y_pred) # R-squared score
# Print evaluation metrics
print('Mean Absolute Error (MAE):', mae)
print('Mean Squared Error (MSE):', mse)
print('Root Mean Squared Error (RMSE):', rmse)
print('R-squared Score:', r2)
Output:
Mean Absolute Error (MAE): 38682.35746632149
Mean Squared Error (MSE): 2087722311.904238
Root Mean Squared Error (RMSE): 45720.45677219991
R-squared Score: 0.9584751822324851
- MAE: Average of the absolute errors between actual and predicted values.
- MSE: Average of the squared errors.
- RMSE: Square root of MSE, provides error in the same units as the target variable.
- R-squared Score: Proportion of variance in the dependent variable that's predictable from the independent variable(s). An R-squared of 0.95 indicates a very good fit.
Conclusion
We have successfully built a linear regression model to predict house prices based on size. The model's high R-squared score suggests that size is a strong predictor of price in our synthetic dataset.
Feel free to adjust the parameters, explore with different datasets, or add more features to improve the model further.