python sklearn get list of available hyper parameters for model

Question:

I am using python with sklearn, and would like to get a list of available hyper parameters for a model, how can this be done? Thanks

This needs to happen before I initialize the model, when I try to use

model.get_params() 

I get this

TypeError: get_params() missing 1 required positional argument: 'self'
Asked By: thebeancounter

||

Answers:

This should do it: estimator.get_params() where estimator is the name of your model.

To use it on a model you can do the following:

reg = RandomForestRegressor()
params = reg.get_params()
# do something...
reg.set_params(params)
reg.fit(X,  y)

EDIT:

To get the model hyperparameters before you instantiate the class:

import inspect
import sklearn

models = [sklearn.ensemble.RandomForestRegressor, sklearn.linear_model.LinearRegression]

for m in models:
    hyperparams = inspect.getargspec(m.__init__).args
    print(hyperparams) # Do something with them here

The model hyperparameters are passed in to the constructor in sklearn so we can use the inspect model to see what constructor parameters are available, and thus the hyperparameters. You may need to filter out some arguments that aren’t specific to the model such as self and n_jobs.

Answered By: sudo

As of May 2021:
(Building on sudo’s answer)

# To get the model hyperparameters before you instantiate the class
import inspect
import sklearn

models = [sklearn.linear_model.LinearRegression]
for m in models:
    hyperparams = inspect.signature(m.__init__)
    print(hyperparams)

#>>> (self, *, fit_intercept=True, normalize=False, copy_X=True, n_jobs=None)

Using inspect.getargspec(m.__init__).args, as suggested by sudo in the accepted answer, generated the following warning:

DeprecationWarning: inspect.getargspec() is deprecated since Python 3.0, 
use inspect.signature() or inspect.getfullargspec()
Answered By: rahul-ahuja

If you happen to be looking at CatBoost, try .get_all_params() instead of get_params().

Answered By: rumble_shark
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.