Skip to content
ImagineWorld

Discrete Models

node_idnode-book_building-statistical-models-in-python_chapter-08-discrete-models
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num8
chapter_titleDiscrete Models
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

In the previous two chapters, we discussed models for predicting a continuous response variable. In this chapter, we will begin discussing models for predicting discrete response variables. We will start by discussing the probit and logit models for predicting binary outcome variables (categorical variables with two levels). Then, we will extend this idea to predicting categorical variables with multiple levels. Finally, we will look at predicting count variables, which are like categorical variables but only take values of integers and have an infinite number of levels.

In this chapter, we’re going to cover the following main topics:

  • Probit and logit models
  • Multinomial logit model
  • Poisson model
  • The negative binomial regression model

Previously, we discussed different types of problems that can be solved with regression models. In particular, the dependent variable is continuous, such as house prices, salaries, and so on. A natural question is if dependent variables are not continuous – in other words, if they are categorical – how would we adapt our regression equation to predict a categorical response variable? For instance, a human resources department in a company wants to conduct an attrition study to predict whether an employee will stay with the company or a car dealership wants to know if one car can be sold or not based on prices, car models, colors, and so on.

First, we will study binary classification. Here, the outcome (dependent variable) is a binary response such as yes/no or to do/not to do. Let’s look back at the simple linear regression model:

Here, the predicted outcome is a line crossing data points. With this model, we could build a model to predict house prices (the dependent variable) based on different independent variables, such as districts, units, stories, or distances. The same idea cannot be applied to a binary classification problem. Let’s consider a simple example that we want to predict if a house is sold only based on its price. Let’s build a model based on linear regression:

(1)

Here, if the house is sold and if it was not sold. By performing visualization using linear regression, we can draw a line of best fit through the data points. It looks like when the price increases, the chance of selling a house decreases:

Figure 8.1 – Line of best fit using linear regression

So, instead of considering the equation model (1), we will be considering the following:

Here, is the probability of selling a house. The probability value will be between 0 and 1; the midpoint of its range is 0.5 when the probability of selling a house is equal to the probability of not selling a house. However, when the price of a house is very high, then the value of can be negative. To avoid this problem, we can model the problem with the following equation:

(2)

Here, is the probability of selling a house and is the probability of not selling a house. The value of is in the range of and when the probability of selling a car is the same as the probability of not selling a car, (, then or the midpoint of its range is 1. This is also called the odds ratio. To interpret the odds ratio, when for every house that is sold, there is a house that is not sold. When then the odds ratio is 3. In this case, the interpretation is that the odds of being able to sell the house are three times higher than the odds of not being able to sell the house. Going back to the equation (2), the range of the odds ratio is and its lower limit is 0, but as we discussed previously for equation (1), when the price of a house is really high, then the estimate of the odds ratio could be negative, which contradicts the probability properties. In addition, because the midpoint is 1 but the range of the odds ratio is from 0 to infinity, then the distribution is very skewed with a long right tail. However, we expected it to be normally distributed per one of the assumptions of linear regression. So, instead of using equation (2), we will consider the following:

The value of is in the range of and the midpoint is 0. Similar to linear regression, we can use the following formula:

(3)

We can use this to interpret how the explanatory variables are associated with the categorical outcome. We can rewrite the previous equation (3) as follows:

The preceding formula is bounded below by 0 and above by 1 (the predicted probability, P, of the outcome takes place) and is called the logit model. It is the cumulative distribution function of the logistic distribution.

Another approach to model the probability of a binary dependent variable is probit regression. Instead of using the cumulative distribution function of logistic regression, we use the cumulative distribution function of the standard normal distribution:

The preceding formula is bounded below by 0 and above by 1 (the predicted probability, P, of the outcome takes place), and is called the probit model. Remember the following:

Both the logit and probit models are estimated by using the maximum likelihood method. In statsmodels, we have classes for the probit and logit models. The documentation for these classes can be found at https://www.statsmodels.org/dev/generated/statsmodels.discrete.discrete_model.Probit.html and https://www.statsmodels.org/dev/generated/statsmodels.discrete.discrete_model.Logit.html.

Now, let’s create a training dataset to illustrate how to use the Logit class from statsmodels to conduct a logit study:

import pandas as pd
# create gpa train data
train = pd.DataFrame({'Admitted': [1, 1, 1,1, 1, 0, 1, 1, 0, 1,1,1, 1,1,0, 1, 0, 0, 0, 0, 0, 0, 0, 0 ,0 ,0, 1,1,1,1, 0],
'GPA': [2.8, 3.3, 3.7, 3.7, 3.7, 3.3, 3.7, 3, 1.7, 3.6, 3.3, 4, 3.2, 3.4, 2.8, 4, 1.5, 2.7, 2.3, 2.3, 2.7, 2.2, 3.3,3.3, 4, 2.3, 3.6, 3.4, 4, 3.7, 2.3],
'Exp': [8, 6, 5, 5, 6, 3, 4, 2, 1, 5, 5, 3, 6,5, 4, 4, 4, 1, 1, 2, 2, 2, 1, 4, 4, 4, 5, 2, 4, 6, 3]})
train.head()

Here, Admitted is the dependent variable and has two possibilities (1 – admitted and 0 – not admitted). GPA is the GPA grade and Exp is the number of years of experience. The output of the preceding code is as follows:

Figure 8.2 – Training dataset on GPA grades and years of experience

We must also create a testing dataset for this model:

test = pd.DataFrame({'Admitted': [1, 0, 1, 0, 1],
'GPA': [2.9, 2.4, 3.8, 3, 3.3],
'Exp': [9, 1, 6, 1,4 ]})
test.head()

The resulting output is as follows:

Figure 8.3 – Testing dataset on GPA grades and years of experience

We will use logit from statsmodels:

import statsmodels.formula.api as smf
#fit logistic regression
model = smf.logit('Admitted ~ GPA + Exp', data =train).fit()
#summary
model.summary()

This will print the following summary:

Figure 8.4 – Logit Regression Output

From this output, we can see that GPA and Exp are significant at the significance level.

The values under the [0.025 0.975] heading are the 95% confidence interval for Intercept, GPA, and Exp, respectively. The next step is to use confusion_matrix and accuracy_score to compute the accuracy of the model on the test set:

from sklearn.metrics import confusion_matrix, accuracy_score, ConfusionMatrixDisplay
# X_test and y_test
X_test = test[['GPA', 'Exp']]
y_test = test['Admitted']
#
y_hat = model.predict(X_test)
pred = list(map(round, y_hat))
# confusion matrix
cm = confusion_matrix(y_test, pred)
ConfusionMatrixDisplay(cm).plot()
# Accuracy
print('Test accuracy = ', accuracy_score(y_test, pred))

The output is as follows:

Figure 8.5 – Confusion matrix on testing dataset

By using these train and test datasets, the model can predict the outcome perfectly. In the next section, we will discuss multi-class regression using a similar idea as in binary logistic regression.

In practice, there are many situations where the outcomes (dependent variables) are not binary but have more than two possibilities. Multinomial logistic regression can be understood as a general case of the logit model, which we studied in the previous section. In this section, we will consider a hands-on study on Iris data by using the MNLogit class from statsmodels: https://www.statsmodels.org/dev/generated/statsmodels.discrete.discrete_model.MNLogit.html.

Iris data (https://archive.ics.uci.edu/ml/datasets/iris) is one of the best-known statistical and machine learning datasets for education. The independent variables are sepal length (in cm), sepal width (in cm), petal length (in cm), and petal width (in cm). The dependent variable is a categorical variable with three levels: Iris Setosa (0), Iris Versicolor (1), and Iris Virginia (2). The following Python codes illustrate how to conduct this using sklearn and statsmodels:

# import packages
import numpy as np
import pandas as pd
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix, accuracy_score, ConfusionMatrixDisplay
import statsmodels.discrete.discrete_model as sm
# import Iris data
iris = datasets.load_iris()
print(iris.feature_names)
print(iris.target_names)
#create dataframe
df = pd.DataFrame(iris.data, columns = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width'])
df['target'] = iris.target
df.head()
# check missing values
df.isna().sum()
# create train and test data
X = df.drop('target', axis=1)
y = df['target']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size =0.2, random_state =1)
# fit the model using sklearn
model_sk = LogisticRegression(solver = 'newton-cg', multi_class = 'multinomial')
model_sk.fit(X_train, y_train)
y_hat_sk = model_sk.predict(X_test)
pred_sk = list(map(round, y_hat_sk))
# confusion matrix
cm_sk = confusion_matrix(y_test, pred_sk)
ConfusionMatrixDisplay(cm_sk).plot()
# Accuracy
print('Test accuracy = ', accuracy_score(y_test, pred_sk))
#fit the model using statsmodels
model_stat = sm.MNLogit(y_train, X_train).fit(method='bfgs')
model_stat.summary()
y_hat_stat = model_stat.predict(X_test)
pred_stat = np.asarray(y_hat_stat).argmax(1)
# confusion matrix
cm_stat = confusion_matrix(y_test, pred_stat)
ConfusionMatrixDisplay(cm_stat).plot()
# Accuracy
print('Test accuracy = ', accuracy_score(y_test, pred_stat))

Both methods give us the same test accuracy value (96.67%), with the confusion matrix produced as follows:

Figure 8.6 – Confusion matrices using sklearn (left) and statsmodels (right)

In the previous section, we discussed models where the response variable was categorical. In this section, we will look at a model for count data. Count data is like categorical data (the categories are integers), but there are an infinite number of levels (0, 1, 2, 3, and so on). We model count data with the Poisson distribution. In this section, we will start by examining the Poisson distribution and its properties. Then, we will model a count variable with explanatory variables using the Poisson model.

The Poisson distribution is given by the following formula:

Here, is the average number of events and is the number of events for which we would like the probability. is the probability that the events occur. This distribution is used to calculate the probability of events occurring in a fixed time interval or a defined space.

The shape of the distribution changes with the value of. When is greater than 10, the distribution appears approximately normal. However, as approaches 0, the distribution becomes right-skewed. This is because count data cannot be negative. Three example Poisson distributions are shown in Figure 8*.7* with means of 12, 5, and 2. Notice that the distribution with the mean of 12 is approximately normally distributed, while the distributions of 5 and 2 are right-skewed:

Figure 8.7 – Example Poisson distributions with means of 12, 5, and 2

Another interesting aspect of the distribution is that the mean and variance are equal. This means that as the mean increases, the spread of the distribution also increases. We can see this in action in the examples in Figure 8*.7*. The distribution with a mean of 2 has a small spread with a large peak at the mean, while the distribution with a mean of 12 has a much wider spread with a lower peak at the mean.

Now that we have discussed the Poisson distribution, let’s look at how to set up a Poisson model.

Now, let’s look at how to model the response variable of counts with the Poisson model. As mentioned previously, count data often follows a Poisson distribution. The Poisson model is expressed mathematically as follows:

Here, y is the response variable, values are model coefficients, and variables represent explanatory variables. This should appear similar to the equation we used in the previous chapter but with the addition of the exponentiation of the explanatory variables. This type of model is called a log-linear model, which is a model where the logarithm of the response variable is modeled by a linear combination of variables. We can rewrite this equation by applying the natural logarithm to both sides of the equation to make it explicit:

Now, we have the logarithm of the response variable ( ) expressed as a linear combination of explanatory variables.

The natural logarithm

The Poisson model uses a special logarithm called the natural logarithm. The natural logarithm of a number is the logarithm of that number using the mathematical constant as the base. The natural logarithm is generally written as (x),, or (the first two options are explicit, but the third option can be ambiguous). The logarithm operation is the inverse of exponentiation. In this case, the natural logarithm is the inverse of the exponential function:. The natural logarithm and exponential function are commonly used in statistics, mathematics, and science.

Let’s look at an example. We will be using the Bike Sharing Dataset from UCI (https://archive.ics.uci.edu/ml/datasets/bike+sharing+dataset.). In this dataset, we have counts of bikes rented each day. There are two types of rentals: pre-registered (registered) and on-demand at a location (causal). In this example, we will model the weekly mean count of casually rented bikes over a given year. The dataset provides several explanatory variables, including environmental factors such as temperature and calendar information such as whether a holiday occurred.

We will start by setting up the equation for our model and then take a look at the results from fitting the model with statsmodels. The model equation follows the form we discussed previously:

We can fit this model with the given data using statsmodels, similar to how we did in the previous chapter. An excerpt of the code to fit the model is shown here (see the Jupyter Notebook for details on preprocessing):

# select variables
X = df.groupby('isoweek').mean()[['atemp', 'season', 'weathersit','hum','windspeed', 'holiday']]
# transform holiday variable as an indicator that a holiday occurs within that week
X['holiday'] = X['holiday'].apply(lambda x: 1 if x > 0.1 else 0)
# add a constant for the model
X = sm.add_constant(X)
# get the response variable
y = df.groupby('isoweek').mean()['casual']
fit_model = sm.Poisson(y, X).fit()
fit_model.summary()

After fitting the model, we can get details on the coefficients using the summary() method. For this model, we get the following output for the coefficients:

Figure 8.8 – Poisson model summary

Just like the modeling example for linear regression, these coefficient values are estimates of the parameters listed in our model. All the explanatory variables in the model appear to be significant in the model. Interestingly, based on the value of the coefficient estimates, temperature (atemp) appears to be the most influential factor, followed by humidity (hum) and wind speed. With the model fit and no need to remove insignificant variables, we can assess the model’s performance. This model has an MAE of 155, which corresponds to a MAPE of 36%.

The Poisson model depends strongly on the assumption that the response variable has a Poisson distribution. In the next section, we will look at a similar type of model for count data, but with weaker distributional assumptions.

Another useful approach to discrete regression is the log-linear negative binomial regression model, which uses the negative binomial probability distribution. At a high level, negative binomial regression is useful with over-dispersed count data where the conditional mean of the count is smaller than the conditional variance of the count. Model over-dispersion is where the variance of the target variable is greater than the mean assumed by the model. In a regression model, the mean is the regression line. We make the determination of using the negative binomial model based on target variable counts analysis (mean versus variance) and supply a measure of model over-dispersion to the negative binomial model to adjust for the over-dispersion, which we will discuss here.

It is important to note that the negative binomial model is not for modeling simply discrete data, but specifically count data associated with a fixed number of random trials, such as modeling the number of attempts before an event occurs – or failing to occur – in a random sampling scenario. The model operates only on count data, where each count response of the target variable is based on a finite set of outcomes. Additionally, because the count data is the result of repeated binomial trials, the order of count arrangement does not matter.

The following is an example of the negative binomial distribution of failure counts with a conditional mean of 17 and a conditional variance of 52:

Figure 8.9 – Negative binomial distribution example

The binomial distribution is a construct of counts of successes in a fixed count of random trials (X = ( X 1, X 2, … )) of a Bernoulli random variable, which is a variable that has one of two outcome values: 0 or 1. The negative binomial distribution is a construct of the count of failures in a fixed count of random draws of the Bernoulli random variable. This distinction is important because a model using binomial regression models a binary outcome across observations, whereas a negative binomial regression model models a count outcome across observations. The negative binomial distribution is the inverse of the binomial distribution. The probability mass function for the negative binomial distribution is as follows:

Here, there are failures and successes in a set of trials reaching success at trial.

Concerning the Poisson distribution, the negative binomial does not require strict adherence to the assumption that conditional variance is equal to the conditional mean as it includes an additional parameter, α, to explain the extra variance, whereas the Poisson model assumes the variance is equal to the mean, μ. The negative binomial model assumes the variance, here based on the Poisson-gamma mixture distribution, is equal to the following:

This reduces to the following:

Stated in terms of the probability of success, p, the negative binomial variance is calculated as follows:

It has the following mean:

Because the variance is not expected to equal the mean with the negative binomial model, the negative binomial is likely to outperform the Poisson approach when the counts are large enough that the variance in response exceeds the mean. Similarly, to Poisson, a negative binomial is a log-linear model with confidence intervals being based on the Wald and drop-in-deviance likelihood ratio. The form of the negative binomial model’s regression equation, shown here, is the same as that for Poisson regression:

It reduces to the following:

The maximum likelihood estimate of the probability of success for a given sample of the distribution is as follows:

Maximum likelihood estimation

Maximum likelihood estimation (MLE) is an underpinning of the log-odds (or logit) and log-likelihood approaches to statistical modeling. Likelihood is the probability of the known outcome of a regression model being observed given specific regression coefficient values. By default, a set of variables will have a higher likelihood than another set of variables if the set provides a higher probability of the observed outcome being obtained. The logarithm of the likelihood is taken as a measure of goodness-of-fit for a regression model. Out of a set of potential coefficient values for each variable, the set of coefficients with the maximum log-likelihood values for each variable are referred to as the maximum likelihood estimates. These values are obtained through an iterative approach that generates multiple possible values. If the sample size is sufficiently large and an appropriate set of variables has been obtained for the model, the maximum likelihood estimates can be considered unbiased.

Calculating the confidence intervals for negative binomial regression is similar to that for logistic regression. The Wald approach to the calculation leverages a z-ratio. Where there are j variables in the model, the z-ratio is calculated as follows:

Here, SE is the standard error. The confidence interval is the variable’s coefficient estimate plus and minus the half-width confidence interval percentile multiplied by the standard error of the coefficient estimate. The z-ratio can be used because it is assumed the estimates have standard normal sampling distributions. Therefore, we can derive the 95% confidence interval for the variable’s estimated coefficient as follows:

Lower 95% confidence limit:

Upper 95% confidence limit:

There are three required assumptions specific to negative binomial regression:

  1. Independence between samples.
  2. A linear relationship between the log of the target variable and input variables (log-linear model).
  3. Conditional variance is greater than or equal to the conditional mean.

Independence between samples means there is no serial correlation nor any cluster or other conditional dependence between samples. A linear relationship between the log of the target variable and input variables means that the relationship between the logarithm of the target variable and changes in each input variable scales linearly. Except for requirement 3, which we discussed at the start of this section, the requirements are essentially the same as for the Poisson model.

Let’s walk through an example in Python using statsmodels. For this, let’s load the statsmodels affairs dataset to model child count (the children variable) using the remaining variables. In line three, we must add the constant required to generate an intercept coefficient:

import statsmodels.api as sm
data = sm.datasets.fair.load().data
data = sm.add_constant(data, prepend=False)

First, let’s numerically confirm there is over-dispersion present in the target variable:

print('Mean count of children per marriage: ', data['children'].mean())
print('Variance of the count of children per marriage: ', data['children'].var())

We can see the variance is greater than the mean:

Mean count of children per marriage: ``1.3968740182218033

Variance of the count of children per marriage: ``2.054838616333698

Here, we can see that the conditional mean per marriage is smaller than the conditional variance. While not a massive difference, it is enough to consider using negative binomial regression. Let’s visually observe the distribution of the response:

Figure 8.10 – Distribution of children

The first five rows of the data can be seen here. Note that the first column of the design matrix should always contain the constant:

Figure 8.11 – First five records of example data set, including the added constant

In our visual inspection of the distribution of children in Figure 8*.10*, we identified that there is a value of 5.5 for children. This may be the result of averaging or an error. A subject matter expert may help determine this, but for our analysis, let’s assume it was a mistake and round to a whole number of children since people are not fractional. Let’s set up the target array, y, and design matrix, X:

y = round(data['children'])
X = data[['const','age','religious','yrs_married','educ','occupation','occupation_husb','affairs','rate_marriage']]

Now, let’s create a train and test split for regression modeling. Note that shuffle=True will provide different results. To obtain a representative sample, the data should be randomly shuffled:

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, shuffle=True)

Because the negative binomial model is based on a Poisson-gamma mixture model, we need to estimate the model’s measure of over-dispersion using a Poisson model. A method referred to as auxiliary OLS regression (without constant) is provided by A. Colin Cameron and Pravin K. Trivedi in Microeconometrics: Methods and Applications. The authors propose the creation of an over-dispersion test statistic where the null hypothesis is α=0 and the alternate hypothesis is, where α is the estimate of over-dispersion. The auxiliary OLS regression formula is as follows:

Here, is an error term and is. Thus, the right-hand operand reduces to. In terms of negative binomial regression, we consider the error to equal zero, so we can factor in as the over-dispersion estimate.

In the following code, we have fit our training data to a generalized linear model using the Poisson model for the linkage. Then, we used the regression mean of the model to build the estimated auxiliary target variable. Because the method is “without constant,” we subtract 1 to remove the constant from the process:

from statsmodels.formula.api import ols as OLS
import statsmodels.api as sm
poisson_model = sm.GLM(y_train, X_train, family=sm.families.Poisson()).fit()
df_aux = pd.DataFrame()
df_aux['y_mu_hat'] = poisson_model.mu
df_aux['children'] = y_train
df_aux['y_auxiliary'] = df_aux.apply(lambda x: ((x['children'] - x['y_mu_hat'])**2 - x['y_mu_hat']) / x['y_mu_hat'], axis=1)
ols_model = OLS('y_auxiliary ~ y_mu_hat - 1', df_aux).fit()
print(ols_model.params)

As we can see, the estimated dispersion for the negative binomial model is 0.622034. Now, we need to assess if the auxiliary estimate is statistically significant. We can do this using the p-value from the OLS model:

print(ols_model.summary())

This will print the following output:

Figure 8.12 – OLS regression results

Because the coefficient is significant and greater than 0, we can confirm the model has over-dispersion based on the target. The coefficient can be used as the measure for that over-dispersion in the negative binomial model, which we can use to adjust the variance in the alpha argument here:

from statsmodels.genmod.families.family import NegativeBinomial
negative_binomial_model = sm.GLM(y_train, X_train, family=NegativeBinomial(alpha=ols_model.params.values)).fit()
print(negative_binomial_model.summary())

The output is generated as follows:

Figure 8.13 – Generalized linear model regression results

Finally, let’s use the model we built on the training data to predict the training data, then again to predict on the test data so that we can compare generalizability on unseen data using residual error as a basis of comparison:

from sklearn.metrics import mean_squared_error as RMSE
print('Training Root Mean Squared Error: ', RMSE(y_train, negative_binomial_model.predict(X_train)) )
print('Testing Root Mean Squared Error: ', RMSE(y_test, negative_binomial_model.predict(X_test)))

We can observe from the root mean squared error that the model’s performance is approximately constant across training and test data, indicating a consistent model:

Training Root Mean Squared Error: 1.2553439918425695

Testing Root Mean Squared Error: 1.266620561303553

In this chapter, we explained the issue of encountering negative raw probabilities that are generated by building a binary classification probability model based strictly on linear regression, where probabilities in a range of [0, 1] are expected. We provided an overview of the log-odds ratio and probit and logit modeling using the cumulative distribution function of both the standard normal distribution and logistic distribution, respectively. We also demonstrated methods for applying logistic regression to solve binary and multinomial classification problems. Lastly, we covered count-based regression using the log-linear Poisson and negative binomial models, which can also be logically extended to rate data without modification. We provided examples of their implementations.

In the following chapter, we will introduce conditional probability using Bayes’ theorem in addition to dimension reduction and classification modeling using linear discriminant analysis and quadratic discriminant analysis.