-
Notifications
You must be signed in to change notification settings - Fork 84
[WIP] Add GLM example with the Negative Binomial distribution. #392
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
geektoni
wants to merge
7
commits into
glm-tools:master
Choose a base branch
from
geektoni:feature/neg-binomial-example
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 4 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
7725bf1
Add example of using GLM with the Negative Binomial distribution.
geektoni d52bfc8
Update Negative Binomial regression example description.
geektoni 214f900
Apply suggestions from code review.
geektoni b9b9ddd
Apply suggestions from code review 2.
geektoni 972b2c3
FIX: bring it close to R example
jasmainak dbed52e
Update plot_negative_binomial.
geektoni 6274c06
Add new example with Poisson and Negative Binomial distribution.
geektoni File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,92 @@ | ||
| # -*- coding: utf-8 -*- | ||
| """ | ||
| ======================================= | ||
| GLM with Negative Binomial Distribution | ||
| ======================================= | ||
|
|
||
| This is an example of GLM with negative binomial distribution. | ||
| We wrote this example taking inspiration from the R community | ||
| below | ||
| https://stats.idre.ucla.edu/r/dae/negative-binomial-regression/ | ||
|
|
||
| Here, we would like to predict the number of days absence of high school | ||
| juniors at two schools from there type of program they are enrolled, | ||
| and their math score. | ||
|
|
||
| The nature of the empirical data suggests that we need to model | ||
| count data (the number of days absent). In such scenarios, a common model | ||
| we could use is the Poisson regression. | ||
|
|
||
| However, if we inspect the dataset more closely, we will notice that | ||
| the dataset is over-dispersed since the conditional mean exceeds the | ||
| conditional variance. We would need to apply another model which is the | ||
| Negative Binomial regression. | ||
|
|
||
| The Negative Binomial regression can be seen as a mixture of Poisson | ||
| regression in which the mean of the Poisson distribution can be seen | ||
| as a random variable drawn from a Gamma distribution. | ||
|
|
||
| This gives us an extra parameter which can be used to account for the over | ||
| dispersion. | ||
| """ | ||
|
|
||
|
|
||
| # Author: Titipat Achakulvisut <my.titipat@gmail.com> | ||
| # Giovanni De Toni <giovanni.det@gmail.com> | ||
| # License: MIT | ||
|
|
||
|
|
||
|
|
||
| ######################################################## | ||
| # Import relevance libraries | ||
|
|
||
| import pandas as pd | ||
| from pyglmnet import GLM | ||
|
|
||
| from sklearn.model_selection import train_test_split | ||
|
|
||
| import matplotlib.pyplot as plt | ||
|
|
||
| ######################################################## | ||
| # Read and preprocess data | ||
| df = pd.read_stata("https://stats.idre.ucla.edu/stat/stata/dae/nb_data.dta") | ||
|
|
||
| # Histogram of type of program they are enrolled | ||
| df.hist(column='daysabs', by=['prog']) | ||
| plt.show() | ||
|
|
||
| # Print mean and standard deviation for each program enrolled. | ||
| # We can see from here that the variance is higher that then mean for all | ||
| # the levels, therefore hinting for over-dispersion. | ||
| prog_mean = df.groupby('prog').agg({'daysabs': ['mean', 'std']}) | ||
| print(prog_mean) | ||
|
|
||
| ######################################################## | ||
| # Feature | ||
| X = df.drop('daysabs', axis=1) | ||
| y = df['daysabs'].values | ||
|
|
||
| # design matrix | ||
| program_df = pd.get_dummies(df.prog) | ||
| Xdsgn = pd.concat((df['math'], program_df.drop(3.0, axis=1)), axis=1).values | ||
|
|
||
| # Split the dataset into training and test | ||
| Xtrain, Xtest, ytrain, ytest = train_test_split(Xdsgn, y, test_size=0.2) | ||
|
geektoni marked this conversation as resolved.
Outdated
|
||
|
|
||
| ######################################################## | ||
| # Fit the model using the GLM | ||
| glm_neg_bino = GLM(distr='neg-binomial', | ||
|
geektoni marked this conversation as resolved.
Outdated
|
||
| alpha=0.0, | ||
| reg_lambda=0.0, | ||
| score_metric='pseudo_R2', | ||
| verbose=True) | ||
| glm_neg_bino.fit(Xtrain, ytrain) | ||
|
|
||
| ######################################################## | ||
| # Predict | ||
| y_hat = glm_neg_bino.predict(Xtest) | ||
|
|
||
| ######################################################## | ||
| # Return the learned betas and the score | ||
| print(glm_neg_bino.beta0_, glm_neg_bino.beta_) | ||
| print(glm_neg_bino.score(Xtest, y_hat)) | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.