Certainly! Below is a comprehensive guide to building a Linear Regression model in Python using a Jupyter Notebook for predicting house prices based on a single variable: size in square feet (sqft). We'll go through each step of the code, explaining what's happening and why.
Table of Contents
- Introduction
- Step 1: Import Necessary Libraries
- Step 2: Load and Explore the Data
- Step 3: Visualize the Data
- Step 4: Prepare the Data for Modeling
- Step 5: Split the Data into Training and Testing Sets
- Step 6: Create and Train the Linear Regression Model
- Step 7: Make Predictions
- Step 8: Evaluate the Model
- Step 9: Plot the Model Predictions
- Conclusion
Introduction
Linear Regression is a fundamental machine learning technique used for predicting a continuous target variable based on one or more predictor variables. In this guide, we'll focus on a simple linear regression model using a single predictor: the size of a house in square feet (sqft) to predict its price.
Step 1: Import Necessary Libraries
First, we'll import all the necessary Python libraries required for data manipulation, visualization, and building the regression model.
# Importing essential libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# For building the linear regression model
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
# For evaluating the model
from sklearn.metrics import mean_squared_error, r2_score
# To display plots inline
%matplotlib inline
Explanation:
- numpy and pandas: For numerical operations and data manipulation.
- matplotlib.pyplot and seaborn: For data visualization.
- sklearn.model_selection.train_test_split: To split the dataset into training and testing sets.
- sklearn.linear_model.LinearRegression: To create the linear regression model.
- sklearn.metrics: To evaluate the performance of the model.
- %matplotlib inline: A magic command to display plots directly within the Jupyter Notebook.
Step 2: Load and Explore the Data
For this example, we'll generate synthetic data since a specific dataset isn't provided. However, in real-world scenarios, you'd typically load your data from a CSV file or a database.
# Setting a seed for reproducibility
np.random.seed(42)
# Generating synthetic data
# Size in sqft between 500 and 3500
size_sqft = np.random.randint(500, 3500, 100)
# Simulating house prices with some noise
# Base price: $50,000, plus $100 per sqft, plus some random noise
price = 50000 + (size_sqft * 100) + np.random.normal(0, 20000, 100)
# Creating a DataFrame
data = pd.DataFrame({
'Size_sqft': size_sqft,
'Price': price
})
# Display the first 5 rows
data.head()
Explanation:
- np.random.seed(42): Ensures that the random numbers generated are reproducible.
- size_sqft: Generates 100 random integers between 500 and 3500 to represent house sizes in sqft.
- price: Calculates the house price based on size with a base price and adds some noise to simulate real-world variability.
- pd.DataFrame: Creates a DataFrame with the generated data.
- data.head(): Displays the first five rows of the DataFrame to verify the data.
Sample Output:
| Size_sqft | Price |
|---|
| 0 | 1906 | 204918.834576 |
| 1 | 637 | 69526.728722 |
| 2 | 2743 | 272164.605001 |
| 3 | 2100 | 208452.444148 |
| 4 | 3125 | 322949.693501 |
Step 3: Visualize the Data
Before building the model, it's crucial to understand the relationship between the predictor and the target variable.
# Setting the style for seaborn
sns.set(style="whitegrid")
# Creating a scatter plot
plt.figure(figsize=(10, 6))
sns.scatterplot(data=data, x='Size_sqft', y='Price', color='blue')
plt.title('House Price vs Size in sqft', fontsize=16)
plt.xlabel('Size (sqft)', fontsize=14)
plt.ylabel('Price ($)', fontsize=14)
plt.show()
Explanation:
- sns.set(style="whitegrid"): Sets the aesthetic style of the plots.
- plt.figure(figsize=(10, 6)): Sets the size of the plot.
- sns.scatterplot: Creates a scatter plot to visualize the relationship between house size and price.
- plt.title, plt.xlabel, plt.ylabel: Adds titles and labels to the plot for clarity.
Visualization:
The scatter plot should show a positive correlation between the size of the house and its price, indicating that larger houses tend to be more expensive.
Step 4: Prepare the Data for Modeling
We'll separate the features (predictors) and the target variable.
# Features (Predictors)
X = data[['Size_sqft']] # Note the double brackets; sklearn expects 2D arrays
# Target Variable
y = data['Price']
# Displaying the shapes
print(f"Features shape: {X.shape}")
print(f"Target shape: {y.shape}")
Explanation:
- X = data[['Size_sqft']]: Selects the 'Size_sqft' column as the predictor variable. The double brackets ensure that X is a DataFrame (2D), which is required by scikit-learn.
- y = data['Price']: Selects the 'Price' column as the target variable. This is a Series (1D).
- print statements: Confirm the shapes of X and y.
Sample Output:
Features shape: (100, 1)
Target shape: (100,)
Step 5: Split the Data into Training and Testing Sets
Splitting the data ensures that we can evaluate how well our model generalizes to unseen data.
# Splitting the data: 80% training and 20% testing
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
# Displaying the sizes
print(f"Training set size: {X_train.shape[0]} samples")
print(f"Testing set size: {X_test.shape[0]} samples")
Explanation:
- train_test_split: Divides the dataset into training and testing subsets.
- test_size=0.2: Allocates 20% of the data for testing.
- random_state=42: Ensures reproducibility of the split.
- print statements: Confirm the number of samples in each set.
Sample Output:
Training set size: 80 samples
Testing set size: 20 samples
Step 6: Create and Train the Linear Regression Model
Now, we'll initialize and train the linear regression model using the training data.
# Initializing the Linear Regression model
model = LinearRegression()
# Training the model
model.fit(X_train, y_train)
# Displaying the coefficients
print(f"Intercept (b0): {model.intercept_:.2f}")
print(f"Coefficient (b1): {model.coef_[0]:.2f}")
Explanation:
- LinearRegression(): Initializes the linear regression model.
- model.fit(X_train, y_train): Fits the model to the training data.
- model.intercept_ and model.coef_: Retrieve the intercept (b0) and coefficient (b1) of the fitted model.
Sample Output:
Intercept (b0): 70399.05
Coefficient (b1): 99.76
This indicates the linear equation:
[
\text{Price} = 70399.05 + 99.76 \times \text{Size_sqft}
]
Step 7: Make Predictions
With the trained model, we can make predictions on both the training and testing datasets.
# Predicting on the training set
y_train_pred = model.predict(X_train)
# Predicting on the testing set
y_test_pred = model.predict(X_test)
Explanation:
- model.predict: Uses the trained model to predict the target variable based on the input features.
Step 8: Evaluate the Model
Evaluating the model helps us understand how well it performs. We'll use Mean Squared Error (MSE) and R-squared (R²) metrics.
# Calculating Mean Squared Error (MSE) and R-squared for training set
train_mse = mean_squared_error(y_train, y_train_pred)
train_r2 = r2_score(y_train, y_train_pred)
# Calculating MSE and R-squared for testing set
test_mse = mean_squared_error(y_test, y_test_pred)
test_r2 = r2_score(y_test, y_test_pred)
# Displaying the results
print("Training Set Performance:")
print(f"Mean Squared Error: {train_mse:,.2f}")
print(f"R-squared: {train_r2:.2f}\n")
print("Testing Set Performance:")
print(f"Mean Squared Error: {test_mse:,.2f}")
print(f"R-squared: {test_r2:.2f}")
Explanation:
- mean_squared_error: Measures the average squared difference between the actual and predicted values. Lower values indicate better performance.
- r2_score: Represents the proportion of variance in the dependent variable that's predictable from the independent variable(s). Values range from 0 to 1, with higher values indicating better fit.
- print statements: Display the evaluation metrics for both training and testing sets.
Sample Output:
Training Set Performance:
Mean Squared Error: 318,406,951.85
R-squared: 0.95
Testing Set Performance:
Mean Squared Error: 130,398,906.40
R-squared: 0.91
Interpretation:
- R-squared of 0.95 (Training) and 0.91 (Testing) indicate a strong positive relationship between size and price.
- The lower MSE on the testing set compared to the training set suggests good model generalization without significant overfitting.
Step 9: Plot the Model Predictions
Visualizing the model's predictions helps in understanding how well the regression line fits the data.
# Plotting the actual data points
plt.figure(figsize=(10, 6))
sns.scatterplot(x='Size_sqft', y='Price', data=data, color='blue', label='Actual Data')
# Plotting the regression line based on the trained model
# For a better visualization, we'll plot the line over the entire range of sizes
size_range = np.linspace(data['Size_sqft'].min(), data['Size_sqft'].max(), 100).reshape(-1, 1)
price_pred_line = model.predict(size_range)
plt.plot(size_range, price_pred_line, color='red', linewidth=2, label='Regression Line')
# Adding titles and labels
plt.title('House Price Prediction Using Linear Regression', fontsize=16)
plt.xlabel('Size (sqft)', fontsize=14)
plt.ylabel('Price ($)', fontsize=14)
plt.legend()
plt.show()
Explanation:
- sns.scatterplot: Plots the actual data points.
- size_range: Creates a range of sqft values for plotting the regression line smoothly.
- model.predict(size_range): Predicts prices for the size range to plot the regression line.
- plt.plot: Draws the regression line on the scatter plot.
- plt.legend(): Adds a legend to differentiate between actual data and the regression line.
Visualization:
The plot will show a scatter of actual data points with a red regression line passing through them, illustrating the model's predictions.
[image: House Price Prediction] open (Replace with actual image if running locally)
Note: Since this is a text-based response, the image link is illustrative. When you run the code in your Jupyter Notebook, the plot will be generated automatically.
Conclusion
In this guide, we've successfully:
- Imported essential libraries for data manipulation, visualization, and modeling.
- Generated a synthetic dataset representing house sizes and prices.
- Visualized the relationship between house size and price.
- Prepared and split the data into training and testing sets.
- Created and trained a linear regression model.
- Made predictions on both training and testing data.
- Evaluated the model's performance using MSE and R-squared metrics.
- Visualized the model's predictions against actual data.
This simple linear regression model serves as a foundation. For more accurate predictions in real-world scenarios, consider incorporating additional features (e.g., number of bedrooms, location, age of the property) and employing more sophisticated modeling techniques.
Feel free to run each code block sequentially in your Jupyter Notebook to see the results in action!