Previously, we saw how to run a linear regression in Python using statsmodels and sklearn. In this type of regression, we dealt with interval variables, ones where there is order and there is a meaningful difference between the two values. In this post, you will learn how to run logistic regressions in Python.
There are three major types of variables we can encounter:
- Nominal: One where there is no order to the elements. This type of variable is known as categorical, and hence is commonly used for categorising. e.g. male = 0, female = 1, etc.
- Ordinal: A categorical variable for which the elements are ordered. For instance, a ranking scale from 1-5 (with 1 being the lowest and 5 being the highest) is an ordinal variable.
- Interval: A variable where the elements are ordered and the differences between those variables are significant. For instance, speed is a variable that operates on an interval scale – the difference between 70-80 km/h and 100-110 km/h is 10 km/h in both instances.
A binary logistic regression is one where the dependent variable is nominal. Let’s see how we run and interpret regressions such as these.
Here is the structure of our variables within the binomial_stock dataset (available at my repository):
Dependent Variable (Y)
- Dividends (dummy variable) – if the company pays dividends currently it is given a ranking of 1. If the company does not pay dividends, it is given a ranking of 0.
Independent Variables (X)
- Years: The number of years of consecutive dividend increases.
- Earnings Estimates: If the stock beat earnings for the past four consecutive quarters, it is given a ranking of 1. Otherwise, it is given a ranking of 0.
Essentially, we wish to use the input variables years and earnings estimates to determine whether a stock will pay a dividend or not.
Firstly, we will import our relevant libraries, including the LogisticRegression and train_test_split from sklearn.
import numpy as np import statsmodels.api as sm import statsmodels.formula.api as smf import pandas as pd from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split import os; path="C:/Users/michaeljgrogan/Documents/YourDirectory" os.chdir(path) os.getcwd()
The code and datasets we will use for this example are logisticregression.ipynb and binomial_stock.csv, available from the MGCodesandStats Github Repository. Then, we generate our regression model, using the dividend variable as our dependent variable, and years and earnings estimates as our independent variables:
variables = pd.read_csv('binomial_stock.csv')
years = variables['years']
dividend = variables['dividend']
earnings_estimates = variables['earnings_estimates']
y = dividend
x = np.column_stack((years,earnings_estimates))
x = sm.add_constant(x, prepend=True)
logit_model=sm.Logit(y,x)
result=logit_model.fit()
print(result.summary())
Upon running the above, we generate the following output:
Optimization terminated successfully.
Current function value: 0.162588
Iterations 10
Logit Regression Results
==============================================================================
Dep. Variable: dividend No. Observations: 70
Model: Logit Df Residuals: 67
Method: MLE Df Model: 2
Date: Sat, 03 Feb 2018 Pseudo R-squ.: 0.7654
Time: 21:24:55 Log-Likelihood: -11.381
converged: True LL-Null: -48.520
LLR p-value: 7.425e-17
==============================================================================
coef std err z P>|z| [95.0% Conf. Int.]
------------------------------------------------------------------------------
const -10.6858 3.441 -3.105 0.002 -17.431 -3.941
x1 0.8919 0.297 2.999 0.003 0.309 1.475
x2 0.3953 1.100 0.359 0.719 -1.761 2.552
==============================================================================
Possibly complete quasi-separation: A fraction 0.29 of observations can be
perfectly predicted. This might indicate that there is complete
quasi-separation. In this case some parameters will not be identified.
Of our predictors, we see that years is indicated as statistically significant at the 1% significance level.
Note that the Pseudo R-Squared statistic provided in the output is not necessarily reliable as a measure of fit in logistic regressions. This is because the degree of variation in a nominal dependent variable is a lot smaller than that of an interval one, and therefore a very large number of observations are needed for this statistic to have credence.
Now, we need to obtain the odds ratio for the years variable. An odds ratio is a ratio comparing the likelihood of an event happening compared to the likelihood of the event not happening.
For instance, the odds ratio for our years variable is exp(0.8919) = 2.439. This means that if a company’s lifespan increases by a year, then the odds of that company paying a dividend is 2.439:1.
Now, let’s interpret the odds ratio in a way that makes more sense. We can convert the odds ratio to a probability as follows:
probability=(oddsratio/(1+oddsratio)) probability
Therefore, we can then calculate that if the lifespan of a company increases by a year, then the likelihood of that company paying a dividend goes up by 70.93%:
(2.439/(1+2.439)) = 0.7093
Note that while we ran a logistic regression on all our observations, we can also split the data into training and test data using train_test_split.
print("Training set score: {:.3f}".format(logreg.score(x_train,y_train)))
Training set score: 0.885
print("Test set score: {:.3f}".format(logreg.score(x_test,y_test)))
Test set score: 0.944
We see that we obtained high training and test scores across our data, indicating that the logistic regression showed a high degree of accuracy in determining whether a stock would pay a dividend or not.
Read on to see how we can take classification one step further with the MLPClassifier!
2 comments