Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Data Science
  • Data Science Projects
  • Data Analysis
  • Data Visualization
  • Machine Learning
  • ML Projects
  • Deep Learning
  • NLP
  • Computer Vision
  • Artificial Intelligence
Open In App
Next Article:
Logistic Regression using Statsmodels
Next article icon

Logistic Regression using Statsmodels

Last Updated : 10 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Prerequisite: Understanding Logistic Regression
Logistic 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 a student will be admitted to a particular college, based on their gmat, gpa scores and work experience. The dependent variable here is a Binary Logistic variable, which is expected to take strictly one of two forms i.e., admitted or not admitted. 

Building the Logistic Regression model :

Statsmodels is a Python module that provides various functions for estimating different statistical models and performing statistical tests  

  • First, we define the set of dependent(y) and independent(X) variables. If the dependent variable is in non-numeric form, it is first converted to numeric using dummies. The file used in the example for training the model, can be downloaded here.
  • Statsmodels provides a Logit() function for performing logistic regression. The Logit() function accepts y and X as parameters and returns the Logit object. The model is then fitted to the data.
Python3
# importing libraries import statsmodels.api as sm import pandas as pd   # loading the training dataset  df = pd.read_csv('logit_train1.csv', index_col = 0)  # defining the dependent and independent variables Xtrain = df[['gmat', 'gpa', 'work_experience']] ytrain = df[['admitted']]   # building the model and fitting the data log_reg = sm.Logit(ytrain, Xtrain).fit() 

Output : 

Optimization terminated successfully.           Current function value: 0.352707           Iterations 8


In the output, 'Iterations' refer to the number of times the model iterates over the data, trying to optimize the model. By default, the maximum number of iterations performed is 35, after which the optimization fails.

The summary table :

The summary table below gives us a descriptive summary about the regression results.  

Python3
# printing the summary table print(log_reg.summary()) 

Output : 

                           Logit Regression Results                             ==============================================================================  Dep. Variable:               admitted   No. Observations:                   30  Model:                          Logit   Df Residuals:                       27  Method:                           MLE   Df Model:                            2  Date:                Wed, 15 Jul 2020   Pseudo R-squ.:                  0.4912  Time:                        16:09:17   Log-Likelihood:                -10.581  converged:                       True   LL-Null:                       -20.794  Covariance Type:            nonrobust   LLR p-value:                 3.668e-05  ===================================================================================                        coef    std err          z      P>|z|      [0.025      0.975]  -----------------------------------------------------------------------------------  gmat               -0.0262      0.011     -2.383      0.017      -0.048      -0.005  gpa                 3.9422      1.964      2.007      0.045       0.092       7.792  work_experience     1.1983      0.482      2.487      0.013       0.254       2.143  ===================================================================================


Explanation of some of the terms in the summary table:

  • coef : the coefficients of the independent variables in the regression equation.
  • Log-Likelihood : the natural logarithm of the Maximum Likelihood Estimation(MLE) function. MLE is the optimization process of finding the set of parameters that result in the best fit.
  • LL-Null : the value of log-likelihood of the model when no independent variable is included(only an intercept is included).
  • Pseudo R-squ. : a substitute for the R-squared value in Least Squares linear regression. It is the ratio of the log-likelihood of the null model to that of the full model.

Predicting on New Data :

Now we shall test our model on new test data. The test data is loaded from this csv file.
The predict() function is useful for performing predictions. The predictions obtained are fractional values(between 0 and 1) which denote the probability of getting admitted. These values are hence rounded, to obtain the discrete values of 1 or 0. 

Python3
# loading the testing dataset   df = pd.read_csv('logit_test1.csv', index_col = 0)  # defining the dependent and independent variables Xtest = df[['gmat', 'gpa', 'work_experience']] ytest = df['admitted']  # performing predictions on the test dataset yhat = log_reg.predict(Xtest) prediction = list(map(round, yhat))  # comparing original and predicted values of y print('Actual values', list(ytest.values)) print('Predictions :', prediction)   

Output : 

Optimization terminated successfully.           Current function value: 0.352707           Iterations 8  Actual values [0, 0, 0, 0, 0, 1, 1, 0, 1, 1]  Predictions : [0, 0, 0, 0, 0, 0, 0, 0, 1, 1]

Testing the accuracy of the model : 

Python3
from sklearn.metrics import (confusion_matrix,                             accuracy_score)  # confusion matrix cm = confusion_matrix(ytest, prediction)  print ("Confusion Matrix : \n", cm)   # accuracy score of the model print('Test accuracy = ', accuracy_score(ytest, prediction))  

Output : 

Confusion Matrix :    [[6 0]   [2 2]]  Test accuracy =  0.8


 


Next Article
Logistic Regression using Statsmodels

C

cosine1509
Improve
Article Tags :
  • Machine Learning
  • AI-ML-DS
  • python
  • AI-ML-DS With Python
Practice Tags :
  • Machine Learning
  • python

Similar Reads

    Logistic Regression using Python
    A basic machine learning approach that is frequently used for binary classification tasks is called logistic regression. Though its name suggests otherwise, it uses the sigmoid function to simulate the likelihood of an instance falling into a specific class, producing values between 0 and 1. Logisti
    8 min read
    Linear Regression using Turicreate
    Linear Regression is a method or approach for Supervised Learning.Supervised Learning takes the historical or past data and then train the model and predict the things according to the past results.Linear Regression comes from the word 'Linear' and 'Regression'.Regression concept deals with predicti
    2 min read
    Logistic Regression using PySpark Python
    In this tutorial series, we are going to cover Logistic Regression using Pyspark. Logistic Regression is one of the basic ways to perform classification (don’t be confused by the word “regression”). Logistic Regression is a classification method. Some examples of classification are: Spam detectionDi
    3 min read
    Ordinary Least Squares (OLS) using statsmodels
    Ordinary Least Squares (OLS) is a widely used statistical method for estimating the parameters of a linear regression model. It minimizes the sum of squared residuals between observed and predicted values. In this article we will learn how to implement Ordinary Least Squares (OLS) regression using P
    3 min read
    ML | Linear Regression vs Logistic Regression
    Linear Regression is a machine learning algorithm based on supervised regression algorithm. Regression models a target prediction value based on independent variables. It is mostly used for finding out the relationship between variables and forecasting. Different regression models differ based on –
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences