1

I need to check whether an object is from the sklearn library. Basically, I need to check if a model belongs to a specific library so I can create a general pattern based on it's type.

I need to check that if I receive a model object that it belongs to the sklearn library.

For example,

if isinstance(model, sklearn):
    #do something

I would like to avoid try drilling down to checking types of specific models.

For example,

from sklearn.linear_model import LinearRegression
from sklearn.cluster import FeatureAgglomeration
if isinstance(model, sklearn.linear_model.LinearRegression):
   #to something 

if isinstance(model, sklearn.cluster.FeatureAgglomeration):
   #to something

The above are acceptable models. However, sklearn has too many models and is constantly changing. I would just like to check if its from the sklearn library.

Bryce Ramgovind
  • 3,127
  • 10
  • 41
  • 72
  • You can just check the output of `model.__module__` and see if starts with `sklearn`. Possible duplicate of [Get fully qualified class name of an object in Python](https://stackoverflow.com/questions/2020014/get-fully-qualified-class-name-of-an-object-in-python) – Vivek Kumar Nov 13 '18 at 07:22

2 Answers2

6

No ideal but u can use:

if "sklearn" in str(type(model)):
Tiago Martins Peres
  • 14,289
  • 18
  • 86
  • 145
wiktor_kubis
  • 61
  • 1
  • 2
2

if you use :

from sklearn.linear_model import LinearRegression
from sklearn.cluster import FeatureAgglomeration

the sklearn object is not imported, only LinearRegression and FeatureAgglomeration are, so you must use this :

if isinstance(model, LinearRegression):
   #to something 

if isinstance(model, FeatureAgglomeration):
   #to something

or import sklearn object

import sklearn
if isinstance(model, sklearn.linear_model.LinearRegression):
   #to something 

if isinstance(model, sklearn.cluster.FeatureAgglomeration):
   #to something
iElden
  • 1,272
  • 1
  • 13
  • 26