
What is Simple Linear Regression?
Simple linear regression is a basic statistical method to understand the relationship between two variables. One variable is dependent, and the other is independent. Python’s statsmodels library makes linear regression easy to apply and understand. This article will show you how to perform simple linear regression using statsmodels.
Simple Linear Regression is a statistical method that models the relationship between two variables. The general equation for a simple linear regression is:
\[
Y = mX + b + \epsilon
\]
where:
- Y is the dependent variable
- X is the independent variable
- m is the slope of the line
- b is the y-intercept
- ϵ is the error term
This equation represents a straight-line relationship. Changes in X lead to proportional changes in Y. Simple linear regression helps to understand and measure this relationship. It is a fundamental technique in statistical modeling and machine learning.
Installing and Importing Dependencies
First, install statsmodels if you haven’t already:
pip install statsmodels
Now, import the necessary libraries:
import numpy as np import pandas as pd import statsmodels.api as sm import matplotlib.pyplot as plt
Creating or Loading the Dataset
We will use a simple dataset where we analyze the relationship between advertising spending (X) and sales revenue (Y).
# Creating a sample dataset
np.random.seed(42)
# Generate 50 random advertising budget values (independent variable X)
X = np.random.randint(10, 100, 50)
# Generate sales revenue with some noise (dependent variable Y)
Y = 5 + 1.5 * X + np.random.normal(0, 10, 50)
# Convert to a Pandas DataFrame
df = pd.DataFrame({'Advertising Budget': X, 'Sales Revenue': Y})
# Display the first five rows
print(df.head())

Preparing the Data for statsmodels
Unlike scikit-learn, statsmodels does not automatically include an intercept in the regression model. We need to manually add a column of ones to represent the intercept term.
# Add a constant (intercept) to the independent variable X = sm.add_constant(df['Advertising Budget']) # Adds a column of ones # Define the dependent variable Y = df['Sales Revenue']
Fitting the Simple Linear Regression Model
Now, we can use the ordinary least squares (OLS) method to fit the model. OLS estimates the slope and intercept by minimizing the sum of squared residuals. The .fit() method in statsmodels trains the model and computes statistical measures such as R-squared, p-values, and confidence intervals to evaluate its accuracy.
In Python, we use the statsmodels library to perform OLS regression. Here’s how we do it:
# Create the OLS model model = sm.OLS(Y, X) # Fit the model results = model.fit()
Evaluating the Model
Once the model is fitted, we need to evaluate its performance. This helps us see how well X explains the changes in Y. Analyzing the regression output provides key insights into the model’s accuracy.
In statsmodels, we can obtain a detailed summary of the regression results using the .summary() method:
print(results.summary())

Visualizing the Results
After fitting the regression model, it is useful to see the results in a graph. This helps us understand how well the regression line matches the data and if there are any unusual patterns.
We can plot the actual data points and overlay the fitted regression line to visually assess the model’s accuracy.
# Scatter plot of actual data
plt.scatter(df['Advertising Budget'], df['Sales Revenue'], color='blue', label="Actual Data")
# Plot the regression line
plt.plot(df['Advertising Budget'], results.predict(X), color='red', linewidth=2, label="Regression Line")
# Labels and title
plt.xlabel("Advertising Budget (in $1000s)")
plt.ylabel("Sales Revenue (in $1000s)")
plt.title("Advertising Budget vs. Sales Revenue (with Regression Line)")
plt.legend()
plt.grid()
plt.show()

In this plot:
- The blue dots represent the actual data points
- The red line represents the predicted values based on the regression model
A good fit is indicated if most data points are close to the red regression line.
Conclusion
Simple linear regression with statsmodels is easy to perform, and providing a detailed statistical analysis of the model is straightforward. This method is useful in many fields, like finance and engineering. It helps us to understand relationships between variables.
By following the above steps, you can apply linear regression using statsmodels to your data and interpret the results.
