How to Build a Linear Regression Model in Python: A Step-by-Step Guide
Linear regression is one of the simplest yet most powerful tools for predicting continuous values. In Python, scikit-learn makes building a model straightforward. This tutorial walks you through the essential steps: preparing data, fitting the model, evaluating performance, and making predictions.
Before writing code, ensure you have the required libraries installed: numpy, pandas, and scikit-learn. Use pip install numpy pandas scikit-learn to set up your environment. We’ll use a sample dataset like house prices to illustrate the workflow.
1. Load and Prepare Your Data
Start by importing pandas and reading your dataset. Split the data into features (X) and target (y). Then, divide into training and testing sets using train_test_split. Scaling features isn’t strictly necessary for simple linear regression, but it can help with interpretation.
import pandas as pd
from sklearn.model_selection import train_test_split
df = pd.read_csv('data.csv')
X = df[['feature1', 'feature2']]
y = df['target']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
2. Fit the Linear Regression Model
Create an instance of LinearRegression and fit it to your training data. The model learns the coefficients that minimize the residual sum of squares.
from sklearn.linear_model import LinearRegression
model = LinearRegression()
model.fit(X_train, y_train)
3. Evaluate Model Performance
Predict on the test set and calculate metrics like R² score and mean squared error (MSE). These tell you how well the model generalizes to unseen data.
from sklearn.metrics import r2_score, mean_squared_error
y_pred = model.predict(X_test)
print('R2:', r2_score(y_test, y_pred))
print('MSE:', mean_squared_error(y_test, y_pred))
4. Interpret and Make Predictions
Check the learned coefficients to understand the impact of each feature. Use model.predict(new_data) to forecast on new inputs. For a more robust model, consider feature engineering or regularization (Ridge, Lasso).
Building a linear regression model in Python is quick and effective. Start simple, validate your assumptions, and iterate to improve accuracy.