AttributeError on check whether RandomForestClassifier has been initialised

Viewed 66

I have a class that holds a scikitlearn-RandomForestClassifier as a member variable. In the __init__-method, it is first initialised to None,

def __init__(self):
   self.classifier = None

and later, once all necessary parameters are available, a RandomForestClassifier is created and assigned to this member variable:

def init_classifier(self):
    self.classifier = RandomForestClassifier(**params)

(In the debugger I can see that self.classifier has been initialised to something meaningful.) In the class method that is supposed to fit the classifier to the data, it is first checked whether the classifier has been initialised already:

if not self.classifier:
    self.init_classifier()

This results in an AttributeError: 'RandomForestClassifier' object has no attribute 'estimators_'. If the check is done by comparing to None explicitly,

if self.classifier is None:
    self.init_classifier()

it runs through. Can someone explain to me where this AttributeError comes from?

1 Answers

To understand why this behavior, you need to look at how the boolean comparison of an object works in Python. (i.e when you call if A).

  1. First, the interpreter will try to see if the object implements the special method __bool__. This a special method that will either return True or False.

  2. If the __bool__ special method is not defined, then the interpreter will try to use the __len__ function. If the result is 0, then the expression is evaluated at False. This is where the exception comes from.

  3. If the __len__ function is not defined either, then the statement is evaluated to True.

If we look at the BaseEnsemble class from which inherits RandomForestClassifier, we can see that it does not implement a __bool__ special method, but does implement a __len__ special method :

def __len__(self):
    """Return the number of estimators in the ensemble."""
    return len(self.estimators_)

So when you are calling if not self.classifier:, you are calling that __len__ function. At the moment in your code, the RandomForestClassifier is not yet properly instantiated (this is my guess) and does not have the estimators_ attribute, hence the exception.

If you want to check that an object is not instantiated, always explicitly call the comparison to None. In that case, the interpreter will check the object against None.

Related