The Wayback Machine - https://web.archive.org/web/20240901210328/https://www.geeksforgeeks.org/ordinary-least-squares-ols-using-statsmodels/
Open In App

Ordinary Least Squares (OLS) using statsmodels

Last Updated : 30 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we will use Python’s statsmodels module to implement Ordinary Least Squares ( OLS ) method of linear regression.

Introduction :

A linear regression model establishes the relation between a dependent variable( y ) and at least one independent variable( x ) as :
[Tex] \hat{y}=b_1x+b_0 [/Tex]

In OLS method, we have to choose the values of [Tex] b_1 [/Tex] and [Tex] b_0 [/Tex] such that, the total sum of squares of the difference between the calculated and observed values of y, is minimised.

Formula for OLS:

Where,
[Tex] \hat{y_i} [/Tex] = predicted value for the ith observation
[Tex] y_i [/Tex] = actual value for the ith observation
[Tex] \epsilon_i [/Tex] = error/residual for the ith observation
n = total number of observations

To get the values of [Tex] b_0 [/Tex] and [Tex] b_1 [/Tex] which minimise S, we can take a partial derivative for each coefficient and equate it to zero.

Modules used :

  • statsmodels : provides classes and functions for the estimation of many different statistical models.

pip install statsmodels

  • pandas : library used for data manipulation and analysis.
  • NumPy : core library for array computing.
  • Matplotlib : a comprehensive library used for creating static and interactive graphs and visualisations.

To master OLS regression and other essential techniques in data science, consider enrolling in the Data Science Live course . This course provides hands-on learning experiences with Python’s powerful libraries, including ‘statsmodels’, to help you build robust statistical models. Gain practical skills and expert knowledge to advance your data science career.

Approach :

  • First we define the variables x and y . In the example below, the variables are read from a csv file using pandas . The file used in the example can be downloaded here .
  • Next, We need to add the constant [Tex] b_0 [/Tex] to the equation using the add_constant() method.
  • The OLS() function of the statsmodels.api module is used to perform OLS regression. It returns an OLS object. Then fit() method is called on this object for fitting the regression line to the data.
  • The summary() method is used to obtain a table which gives an extensive description about the regression results

Syntax : statsmodels.api.OLS(y, x)
Parameters :

  • y : the variable which is dependent on x
  • x : the independent variable

Code:

Python

import statsmodels.api as sm import pandas as pd # reading data from the csv data = pd.read_csv('train.csv') # defining the variables x = data['x'].tolist() y = data['y'].tolist() # adding the constant term x = sm.add_constant(x) # performing the regression # and fitting the model result = sm.OLS(y, x).fit() # printing the summary table print(result.summary())

Output :

OLS Regression Results
==============================================================================
Dep. Variable: y R-squared: 0.989
Model: OLS Adj. R-squared: 0.989
Method: Least Squares F-statistic: 2.709e+04
Date: Fri, 26 Jun 2020 Prob (F-statistic): 1.33e-294
Time: 15:55:38 Log-Likelihood: -757.98
No. Observations: 300 AIC: 1520.
Df Residuals: 298 BIC: 1527.
Df Model: 1
Covariance Type: nonrobust
==============================================================================
coef std err t P>|t| [0.025 0.975]
------------------------------------------------------------------------------
const -0.4618 0.360 -1.284 0.200 -1.169 0.246
x1 1.0143 0.006 164.598 0.000 1.002 1.026
==============================================================================
Omnibus: 1.034 Durbin-Watson: 2.006
Prob(Omnibus): 0.596 Jarque-Bera (JB): 0.825
Skew: 0.117 Prob(JB): 0.662
Kurtosis: 3.104 Cond. No. 120.
==============================================================================

Warnings:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.


Description of some of the terms in the table :

  • R-squared : the coefficient of determination. It is the proportion of the variance in the dependent variable that is predictable/explained
  • Adj. R-squared : Adjusted R-squared is the modified form of R-squared adjusted for the number of independent variables in the model. Value of adj. R-squared increases, when we include extra variables which actually improve the model.
  • F-statistic : the ratio of mean squared error of the model to the mean squared error of residuals. It determines the overall significance of the model.
  • coef : the coefficients of the independent variables and the constant term in the equation.
  • t : the value of t-statistic. It is the ratio of the difference between the estimated and hypothesized value of a parameter, to the standard error


Predicting values:
From the results table, we note the coefficient of x and the constant term. These values are substituted in the original equation and the regression line is plotted using matplotlib .
Code:

Python

import pandas as pd import matplotlib.pyplot as plt import numpy as np # reading data from the csv data = pd.read_csv('train.csv') # plotting the original values x = data['x'].tolist() y = data['y'].tolist() plt.scatter(x, y) # finding the maximum and minimum # values of x, to get the # range of data max_x = data['x'].max() min_x = data['x'].min() # range of values for plotting # the regression line x = np.arange(min_x, max_x, 1) # the substituted equation y = 1.0143 * x - 0.4618 # plotting the regression line plt.plot(y, 'r') plt.show()

Output:




Previous Article
Next Article

Similar Reads

Ordinary Least Squares (OLS) Regression in R
Ordinary Least Squares (OLS) Regression allows researchers to understand the impact of independent variables on the dependent variable and make predictions based on the model. Ordinary Least Squares (OLS) Regression in ROrdinary Least Squares (OLS) regression is a powerful statistical method used to analyze the relationship between one or more inde
6 min read
Ordinary Least Squares and Ridge Regression Variance in Scikit Learn
In statistical modeling, Ordinary Least Squares (OLS) and Ridge Regression are two widely used techniques for linear regression analysis. OLS is a traditional method that finds the line of best fit through the data by minimizing the sum of the squared errors between the predicted and actual values. However, OLS can suffer from high variance and ove
7 min read
Interpreting the results of Linear Regression using OLS Summary
This article is to tell you the whole interpretation of the regression summary table. There are many statistical softwares that are used for regression analysis like Matlab, Minitab, spss, R etc. but this article uses python. The Interpretation is the same for other tools as well. This article needs the basics of statistics including basic knowledg
6 min read
Logistic Regression using Statsmodels
Prerequisite: Understanding Logistic RegressionLogistic regression is the type of regression analysis used to find the probability of a certain event occurring. It is the best suited type of regression for cases where we have a categorical dependent variable which can take only discrete values. The dataset : In this article, we will predict whether
4 min read
statsmodels.omni_normtest() in Python
With the help of statsmodels.omni_normtest() method, we can get the omnibus test for normality and we use chi^2 score for this statsmodels.omni_normtest() method. Syntax : statsmodels.omni_normtest(array) Return : Return the omnibus test for normality. Example #1 : In this example we can see that by using statsmodels.omni_normtest() method, we are
1 min read
How to Obtain ANOVA Table with Statsmodels
Analysis of Variance (ANOVA) is a statistical method used to analyze the differences among group means in a sample. It is particularly useful for comparing three or more groups for statistical significance. In Python, the statsmodels library provides robust tools for performing ANOVA. This article will guide you through obtaining an ANOVA table usi
4 min read
Confidence and Prediction Intervals with Statsmodels
In statistical analysis, particularly in linear regression, understanding the uncertainty associated with predictions is crucial. Confidence intervals and prediction intervals are two essential tools for quantifying this uncertainty. Confidence intervals provide a range within which the mean of the population is likely to lie, while prediction inte
5 min read
Extracting Regression Coefficients from statsmodels.api
data analysis and machine learning, regression analysis is a fundamental tool used to understand relationships between variables. Python's statsmodels library provides a powerful framework for performing regression analysis. This article delves into how to extract regression coefficients using statsmodels.api, focusing on practical implementation w
3 min read
Partial Least Squares Regression (PLSRegression) using Sklearn
Partial least square regression is a Machine learning Algorithm used for modelling the relationship between independent and dependent variables. This is mainly used when there are many interrelated independent variables. It is more commonly used in regression and latent variable modelling. It finds the directions (latent variables) in the independe
8 min read
Partial Least Squares Singular Value Decomposition (PLSSVD)
Partial Least Squares Singular Value Decomposition (PLSSVD) is a sophisticated statistical technique employed in the realms of multivariate analysis and machine learning. This method merges the strengths of Partial Least Squares (PLS) and Singular Value Decomposition (SVD), offering a powerful tool to extract crucial information from high-dimension
9 min read
Partial Least Squares (PLS) Canonical
In the realm of machine learning, it’s essential to have a diverse toolkit to solve various complex problems. Partial Least Squares (PLS) Canonical, a technique rooted in both regression and dimensionality reduction, has gained significant traction in recent years. This method, which finds patterns in data by projecting it onto a lower-dimensional
7 min read
Weighted Least Squares Regression in Python
Weighted Least Squares (WLS) regression is a powerful extension of ordinary least squares regression, particularly useful when dealing with data that violates the assumption of constant variance. In this guide, we will learn brief overview of Weighted Least Squares regression and demonstrate how to implement it in Python using the statsmodels libra
6 min read
Least Mean Squares Filter in Signal Processing
Filtering is a fundamental process in signal processing used to enhance or extract useful information from a signal by reducing noise, isolating certain frequency components, or performing other transformations. Filters are employed in various applications such as audio processing, image enhancement, communications, and biomedical signal analysis.
6 min read
Least Mean-Squares Algorithm in Neural Networks
The Least Mean-Squares (LMS) algorithm is a widely used adaptive filter technique in neural networks, signal processing, and control systems. Developed by Bernard Widrow and Ted Hoff in 1960, the LMS algorithm is a stochastic gradient descent method that iteratively updates filter coefficients to minimize the mean square error between the desired a
11 min read
Implementing Generalized Least Squares (GLS) in Python
Generalized Least Squares (GLS) is a statistical technique used to estimate the unknown parameters in a linear regression model. It extends the Ordinary Least Squares (OLS) method by addressing situations where the assumptions of OLS are violated, specifically when there is heteroscedasticity or autocorrelation in the error terms. GLS is crucial in
6 min read
Python Bokeh - Plotting Squares with Xs on a Graph
Bokeh is a Python interactive data visualization. It renders its plots using HTML and JavaScript. It targets modern web browsers for presentation providing elegant, concise construction of novel graphics with high-performance interactivity. Bokeh can be used to plot squares with Xs on a graph. Plotting squares with Xs on a graph can be done using t
2 min read
Python Bokeh - Plotting Squares with Dots on a Graph
Bokeh is a Python interactive data visualization. It renders its plots using HTML and JavaScript. It targets modern web browsers for presentation providing elegant, concise construction of novel graphics with high-performance interactivity. Bokeh can be used to plot squares with dots on a graph. Plotting squares with dots on a graph can be done usi
2 min read
Python Bokeh - Plotting Squares with Crosses on a Graph
Bokeh is a Python interactive data visualization. It renders its plots using HTML and JavaScript. It targets modern web browsers for presentation providing elegant, concise construction of novel graphics with high-performance interactivity. Bokeh can be used to plot squares with crosses on a graph. Plotting squares with crosses on a graph can be do
2 min read
Python Bokeh - Plotting Squares on a Graph
Bokeh is a Python interactive data visualization. It renders its plots using HTML and JavaScript. It targets modern web browsers for presentation providing elegant, concise construction of novel graphics with high-performance interactivity. Bokeh can be used to plot squares on a graph. Plotting squares on a graph can be done using the square() meth
2 min read
How to Calculate Residual Sum of Squares in Python
The residual sum of squares (RSS) calculates the degree of variance in a regression model. It estimates the level of error in the model's prediction. The smaller the residual sum of squares, the better your model fits your data; the larger the residual sum of squares, the worse. It is the sum of squares of the observed data minus the predicted data
2 min read
Least Angle Regression (LARS)
Regression is a supervised machine learning task that can predict continuous values (real numbers), as compared to classification, that can predict categorical or discrete values. Before we begin, if you are a beginner, I highly recommend this article. Least Angle Regression (LARS) is an algorithm used in regression for high dimensional data (i.e.,
3 min read
Facial Expression Recognizer using FER - Using Deep Neural Net
In our daily life, we knowingly or unknowingly carry out different types of Facial Expressions. These movements convey the emotional state of humans. We can judge the mood and mental state of the next person by his Facial Expression. In the early Twentieth century, Ekman and Friesen defined `six` basic emotions. This expression does not change with
7 min read
Create a Scatter Plot using Sepal length and Petal_width to Separate the Species Classes Using scikit-learn
In this article, we are going to see how to create Scatter Plot using Sepal length and Petal_width to Separate the Species classes using scikit-learn in Python. The Iris Dataset contains 50 samples of three Iris species with four characteristics (length and width of sepals and petals). Iris setosa, Iris virginica, and Iris versicolor are the three
2 min read
Real-Time Edge Detection using OpenCV in Python | Canny edge detection method
Edge detection is one of the fundamental image-processing tasks used in various Computer Vision tasks to identify the boundary or sharp changes in the pixel intensity. It plays a crucial role in object detection, image segmentation and feature extraction from the image. In Real-time edge detection, the image frame coming from a live webcam or video
5 min read
Building a Generative Adversarial Network using Keras
Prerequisites: Generative Adversarial Network This article will demonstrate how to build a Generative Adversarial Network using the Keras library. The dataset which is used is the CIFAR10 Image dataset which is preloaded into Keras. You can read about the dataset here. Step 1: Importing the required libraries import numpy as np import matplotlib.py
4 min read
Create Model using Custom Module in Pytorch
Custom module in Pytorch A custom module in PyTorch is a user-defined module that is built using the PyTorch library's built-in neural network module, torch.nn.Module. It's a way of creating new modules by combining and extending the functionality provided by existing PyTorch modules. The torch.nn.Module class provides a convenient way to create cu
8 min read
Next Sentence Prediction using BERT
Pre-requisite: BERT-GFG BERT stands for Bidirectional Representation for Transformers. It was proposed by researchers at Google Research in 2018. Although, the main aim of that was to improve the understanding of the meaning of queries related to Google Search. A study shows that Google encountered 15% of new queries every day. Therefore, it requir
7 min read
Plotting graph using Seaborn | Python
This article will introduce you to graphing in Python with Seaborn, which is the most popular statistical visualization library in Python. Installation: The easiest way to install seaborn is to use pip. Type following command in terminal: pip install seaborn OR, you can download it from here and install it manually. Plotting categorical scatter plo
8 min read
Analysis of test data using K-Means Clustering in Python
This article demonstrates an illustration of K-means clustering on a sample random data using open-cv library. Pre-requisites: Numpy, OpenCV, matplot-lib Let's first visualize test data with Multiple Features using matplot-lib tool. # importing required tools import numpy as np from matplotlib import pyplot as plt # creating two test data X = np.ra
2 min read
Linear Regression using PyTorch
Linear Regression is a very commonly used statistical method that allows us to determine and study the relationship between two continuous variables. The various properties of linear regression and its Python implementation have been covered in this article previously. Now, we shall find out how to implement this in PyTorch, a very popular deep lea
4 min read
Practice Tags :