SKLearner Home | About | Contact | Examples

Scikit-Learn PoissonRegressor Model

Poisson Regression is a fundamental algorithm for regression tasks where the target variable represents counts, such as the number of events. It models the relationship between the target counts and the input features using the Poisson distribution.

The key hyperparameters of PoissonRegressor include alpha (regularization strength) and fit_intercept (whether to calculate the intercept for the model).

The algorithm is appropriate for regression tasks with count data.

from sklearn.datasets import make_regression
from sklearn.model_selection import train_test_split
from sklearn.linear_model import PoissonRegressor
from sklearn.metrics import mean_squared_error

# generate synthetic count data regression dataset
X, y = make_regression(n_samples=100, n_features=5, noise=0.1, random_state=1)
y = abs(y.round().astype(int))  # ensure target is count data

# split into train and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1)

# create model
model = PoissonRegressor(alpha=1.0)

# fit model
model.fit(X_train, y_train)

# evaluate model
yhat = model.predict(X_test)
mse = mean_squared_error(y_test, yhat)
print('Mean Squared Error: %.3f' % mse)

# make a prediction
row = [[1.5, -0.7, 2.3, 0.4, -1.2]]
yhat = model.predict(row)
print('Predicted: %.3f' % yhat[0])

Running the example gives an output like:

Mean Squared Error: 2819.138
Predicted: 48.472

The steps are as follows:

  1. First, a synthetic count data regression dataset is generated using the make_regression() function. This creates a dataset with a specified number of samples (n_samples) and a fixed random seed (random_state) for reproducibility. The target variable is converted to absolute integer values to represent counts. The dataset is split into training and test sets using train_test_split().

  2. Next, a PoissonRegressor model is instantiated with the alpha hyperparameter set to 1.0 for regularization. The model is then fit on the training data using the fit() method.

  3. The performance of the model is evaluated by comparing the predictions (yhat) to the actual values (y_test) using the mean squared error metric.

  4. A single prediction can be made by passing a new data sample to the predict() method.

This example demonstrates how to use a PoissonRegressor for regression tasks involving count data, showcasing the effectiveness of this algorithm in scikit-learn. The model can be fit directly on the training data, and once fit, it can be used to make predictions on new data.



See Also