SKLearner Home | About | Contact | Examples

Scikit-Learn RandomizedSearchCV TweedieRegressor

Hyperparameter tuning is crucial for optimizing machine learning models. In this example, we’ll demonstrate how to use scikit-learn’s RandomizedSearchCV for hyperparameter tuning of a TweedieRegressor, which is used for generalized linear models.

Random search is a method for evaluating different combinations of model hyperparameters. Unlike grid search, it samples a fixed number of hyperparameter combinations from a specified distribution, making it more efficient when searching over a large hyperparameter space.

The TweedieRegressor can model data distributions that are part of the exponential family, including normal, Poisson, and gamma distributions. It is particularly useful for modeling data with varying dispersion and skewness.

Key hyperparameters for TweedieRegressor include the power parameter (power), which determines the variance function of the target distribution; the regularization strength (alpha), which controls model complexity and helps prevent overfitting; and the solver (solver), which is the method used to solve the optimization problem.

from sklearn.datasets import make_regression
from sklearn.model_selection import train_test_split, RandomizedSearchCV
from sklearn.linear_model import TweedieRegressor
from scipy.stats import uniform
import numpy as np

# Generate synthetic regression dataset
X, y = make_regression(n_samples=1000, n_features=10, noise=0.1, random_state=42)
y = np.abs(y)

# 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=42)

# Define the model
model = TweedieRegressor()

# Define hyperparameter distribution
param_dist = {
    'power': uniform(loc=0, scale=2),
    'alpha': uniform(loc=0, scale=1),
    'solver': ['lbfgs', 'newton-cholesky', 'autograd']
}

# Perform random search
random_search = RandomizedSearchCV(estimator=model,
                                   param_distributions=param_dist,
                                   n_iter=100,
                                   cv=5,
                                   scoring='neg_mean_squared_error',
                                   random_state=42)
random_search.fit(X_train, y_train)

# Report best score and parameters
print(f"Best score: {random_search.best_score_:.3f}")
print(f"Best parameters: {random_search.best_params_}")

# Evaluate on test set
best_model = random_search.best_estimator_
test_score = best_model.score(X_test, y_test)
print(f"Test set score: {test_score:.3f}")

Running the example gives an output like:

Best score: -6370.587
Best parameters: {'alpha': 0.450499251969543, 'power': 0.026529922319733057, 'solver': 'lbfgs'}
Test set score: -0.130

The steps are as follows:

  1. Generate a synthetic regression dataset using scikit-learn’s make_regression function with noise to simulate real-world data.
  2. Split the dataset into training and test sets using train_test_split.
  3. Define the TweedieRegressor model.
  4. Define the hyperparameter distributions:
    • power: Sampled from a uniform distribution covering values from 0 to 2.
    • alpha: Sampled from a uniform distribution with values between 0 and 1.
    • solver: Selected from available solvers for the TweedieRegressor.
  5. Perform random search using RandomizedSearchCV, specifying the TweedieRegressor model, hyperparameter distribution, 100 iterations, 5-fold cross-validation, and mean squared error as the scoring metric.
  6. Report the best cross-validation score and hyperparameters found by random search.
  7. Evaluate the best model on the hold-out test set and report the score.

By using RandomizedSearchCV, we can efficiently explore different hyperparameter settings and find the combination that maximizes the model’s performance. This automated approach saves time and effort compared to manual hyperparameter tuning and helps ensure we select the best configuration for our TweedieRegressor model.



See Also