How to check if sklearn model is classifier or regressor

Viewed 2176

Is there a simple way to check if a model instance solves a classification or regression task in the scikit-learn library?

2 Answers

Use sklearn.base.is_classifier and/or is_regressor:

from sklearn.base import is_classifier, is_regressor
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import RandomForestRegressor
from sklearn.ensemble import RandomForestClassifier

models = [LinearRegression(), RandomForestClassifier(), RandomForestRegressor()]

for m in models:
    print(m.__class__.__name__, is_classifier(m), is_regressor(m))

Output:

# model_name is_classifier is_regressor
LinearRegression False True
RandomForestClassifier True False
RandomForestRegressor False True

I guess you ask this because you have a serialized model whose type you do not know. Open the file and do

mlType = type(variable_name)

where variable_name is the handle of your de-serialized model.

output e.g.

class 'sklearn.linear_model.base.LinearRegression'
Related