GLMs in Python.
Project description
PyGLMs
An implementation of various Generalized Linear Models (GLMs), written in Python.
I created this package as a personal refresher on GLMs and the underlying optimization techniques. It's intended as a learning tool and a reference for building and understanding these models from the ground up.
Overview
The code is packaged as a Python library named turtles-glms (I like turtles).
The package is written using numpy for linear algebra operations, scipy for (some) optimization, pandas for displaying tabular results, and matplotlib for plots.
The following models have been implemented:
- Multiple Linear Regression (
turtles.stats.glms.MLRclass) - Logistic Regression (
turtles.stats.glms.LogRegclass, usesGLMparent class) - Poisson Regression (
turtles.stats.glms.PoissonRegclass, usesGLMparent class)
The GLM parent class supports three optimization methods for parameter estimation: Momentum-based Gradient Descent for first-order optimization, Newton's Method for second-order optimization, and Limited-memory Broyden–Fletcher–Goldfarb–Shanno (L-BFGS). The user can specify the desired optimization method during class instantiation.
Momentum-based Gradient Descent and Newton's Method are implemented in Python as part of the code base. L-BFGS is implemented using scipy.optimize; it's a quasi-Newton method that approximates the Hessian (instead of fully computing it, like Newton's Method), so it's quite fast.
Usage
You can pip install the package from PyPI:
pip install turtles-glms
See examples/ in the GitHub repo for example usage of the GLM classes and statistical functions.
Fitting GLMs
You can fit GLMs by instantiating a GLM child class and calling its fit() method.
model = PoissonReg(
method="newton",
learning_rate=1.0,
tolerance=0.00001
)
model.fit(
X=X,
y=y,
exposure=exposure
)
A few important notes about fitting turtles GLMs:
- The
fit()method parametersX,y, and (for Poisson)exposuremust benumpyarrays. Parametersyandexposuremust be of shape(M, 1), whereMis the number of rows in the data. The package does not supportpandasorpolarsdataframes at this time. See class / instance method docstrings for exact requirements. - Each GLM class has a
learning_rateparameter, applicable to Gradient Descent and Newton's optimization methods. The learning rate (or step size) is a hyperparameter that controls the magnitude of parameter updates during the optimization process. If it's too large, the Hessian matrix may become singular, in which case the learning rate should be decreased. This is typically part of the tuning process. (NOTE: learning rate is typically just 1.0 for Newton's method). - There are currently no regularization methods implemented in the package. Future versions may include L1, L2, and Elastic Net methods.
Contributing
Clone the repo and create your virtual environment from project root. This project requires Python 3.10+.
uv venv
source .venv/Scripts/activate || source .venv/bin/activate
uv sync --all-extras
pre-commit install
Adding GLMs
To add a new GLM class, inherit from the GLM parent class (see PoissonReg and LogReg for examples). The GLM parent class provides a framework for implementing new models and should be used whenever possible. Planned but currently unimplemented GLMs include Negative Binomial, Gamma, and Tweedie.
The GLM parent class defines several empty instance methods that are intended to be overridden by child classes:
self._objective_func: The objective function to be minimized.self._link_func: The GLM's link function (e.g., the logit link for Logistic Regression).self._grad_func: The first derivative of the loss function, used by some optimization algorithms.self._hess_func: The second derivative of the loss function, used by some optimization algorithms.
The implementations in the existing child classes are intentionally written for clarity to help readers and developers understand the underlying mathematics. This design also makes implementing new GLMs pretty straightforward.
Testing
All tests are contained within tests directories for each module. You can simply execute the pytest command from project root to run all unit tests.
pytest
Notes on Test Coverage:
- Plotting functions from
turtles.plottingare tested, but plotting methods in GLM classes (likeMLR) are ignored. Those class methods are essentially just wrappers aroundmatplotlibandturtles.plottingfunctions. GLMclass methods that are meant to be implemented by child classes are ignored.
Unreleased
Some future updates I'd like to make:
- Support flattened arrays (in addition to (m, 1))
- Tweedie GLM
- Regularization methods
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file turtles_glms-1.1.2.tar.gz.
File metadata
- Download URL: turtles_glms-1.1.2.tar.gz
- Upload date:
- Size: 29.3 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: uv/0.8.22
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
7b65f94104dbdb4383a51bf1571b7ccee65f458211710b72280a3db83165e7ab
|
|
| MD5 |
b3ab81a3d78bb028237585391cb450b6
|
|
| BLAKE2b-256 |
a62a907ed78d772338a1c0079cec53230ed987bd5e498394f22602b9d0521266
|
File details
Details for the file turtles_glms-1.1.2-py3-none-any.whl.
File metadata
- Download URL: turtles_glms-1.1.2-py3-none-any.whl
- Upload date:
- Size: 28.2 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: uv/0.8.22
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
a74b5b12a1b59572a24c61cba83630d4bbce15c74e1afa105a6d069baf0d9b15
|
|
| MD5 |
26ca6af0240df7cc93a856272d24005b
|
|
| BLAKE2b-256 |
2924fc46902319c38237faf2678d13c348c7c52e8d55da37942c590d00a0f866
|