Last active
September 26, 2018 22:35
-
-
Save ahwillia/40cdbe3b2f2df1806358dd1e6de0743a to your computer and use it in GitHub Desktop.
Poisson Regression via scipy.optimize
This file contains 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
""" | |
A simple implementation of Poisson regression. | |
""" | |
import numpy as np | |
from scipy.optimize import minimize | |
n = 1000 # number of datapoints | |
p = 5 # number of features | |
# create data | |
X = .3*np.random.randn(n, p) | |
true_b = np.random.randn(p) | |
y = np.random.poisson(np.exp(np.dot(X, true_b))) | |
# loss function and gradient | |
def f(b): | |
Xb = np.dot(X, b) | |
exp_Xb = np.exp(Xb) | |
loss = exp_Xb.sum() - np.dot(y, Xb) | |
grad = np.dot(X.T, exp_Xb - y) | |
return loss, grad | |
# hessian | |
def hess(b): | |
return np.dot(X.T, np.exp(np.dot(X, b))[:, None]*X) | |
# optimize | |
result = minimize(f, np.zeros(p), jac=True, hess=hess, method='newton-cg') | |
print('True regression coeffs: {}'.format(true_b)) | |
print('Estimated regression coeffs: {}'.format(result.x)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output: