Ravikant Singh
Ravikant Singh

Reputation: 348

Class label not present sklearn.ensemble.RandomForestClassifier for class_weight

I am using RandomForestClassifier from sklearn.ensemble. It works when I use it without class_weight but when I add class_weight It gives this error.

lr = RandomForestClassifier(n_estimators = 22,criterion =
                           'entropy',max_depth=5,class_weight={'Sex':2.})

lr.fit(X_train.values[:,1:],Y_train)

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-248-411a1c135d08> in <module>
      1 print(X_train)
----> 2 lr.fit(X_train.values[:,1:],Y_train)

/opt/conda/lib/python3.6/site-packages/sklearn/ensemble/forest.py in fit(self, X, y, sample_weight)
    273         self.n_outputs_ = y.shape[1]
    274 
--> 275         y, expanded_class_weight = self._validate_y_class_weight(y)
    276 
    277         if getattr(y, "dtype", None) != DOUBLE or not y.flags.contiguous:

/opt/conda/lib/python3.6/site-packages/sklearn/ensemble/forest.py in _validate_y_class_weight(self, y)
    519                     class_weight = self.class_weight
    520                 expanded_class_weight = compute_sample_weight(class_weight,
--> 521                                                               y_original)
    522 
    523         return y, expanded_class_weight

/opt/conda/lib/python3.6/site-packages/sklearn/utils/class_weight.py in compute_sample_weight(class_weight, y, indices)
    161             weight_k = compute_class_weight(class_weight_k,
    162                                             classes_full,
--> 163                                             y_full)
    164 
    165         weight_k = weight_k[np.searchsorted(classes_full, y_full)]

/opt/conda/lib/python3.6/site-packages/sklearn/utils/class_weight.py in compute_class_weight(class_weight, classes, y)
     63             i = np.searchsorted(classes, c)
     64             if i >= len(classes) or classes[i] != c:
---> 65                 raise ValueError("Class label {} not present.".format(c))
     66             else:
     67                 weight[i] = class_weight[c]

ValueError: Class label Sex not present. 

This is my X_train :

PassengerId Pclass Sex ... Ticket Fare Embarked

Upvotes: 0

Views: 4694

Answers (1)

seralouk
seralouk

Reputation: 33197

How many classes do you have in Y_train?

The class_weight concerns the Y_train i.e. the labels.

Example:

class_weight={0:1,1:2}

means weight 1 to class 0 and weight 2 to class 1.

Using class_weight={'Sex':2.} is wrong and it refers to X_train.

Upvotes: 2

Related Questions