LabelEncoder instance is not fitted yet

Issue

I have a code for prediction of unseen data in a sentence classification task.

The code is

from sklearn.preprocessing import LabelEncoder

maxlen = 1152

### PREDICT NEW UNSEEN DATA ###
tokenizer = Tokenizer()
label_enc = LabelEncoder()
X_test = ['this is boring', 'wow i like this you did a great job']

X_test = tokenizer.texts_to_sequences(X_test)
X_test = sequence.pad_sequences(X_test, maxlen=maxlen)

a = (model.predict(X_test)>0.5).astype(int).ravel()
print(a)

reverse_pred = label_enc.inverse_transform(a.ravel())
print(reverse_pred)

But I am getting this error

[1 1]
---------------------------------------------------------------------------
NotFittedError                            Traceback (most recent call last)
<ipython-input-33-7e12dbe8aec1> in <module>()
     39 print(a)
     40 
---> 41 reverse_pred = label_enc.inverse_transform(a.ravel())
     42 print(reverse_pred)

1 frames
/usr/local/lib/python3.6/dist-packages/sklearn/utils/validation.py in check_is_fitted(estimator, attributes, msg, all_or_any)
    965 
    966     if not attrs:
--> 967         raise NotFittedError(msg % {'name': type(estimator).__name__})
    968 
    969 

NotFittedError: This LabelEncoder instance is not fitted yet. Call 'fit' with appropriate arguments before using this estimator.

I have used Sequential model and the model.fit is written as history=model.fit() in the training part. Why am I getting this error?

Solution

following the sklearn documentation and what reported here, you have simply to fit your encoder before making an inverse transform

y = ['positive','negative','positive','negative','positive','negative']
label_enc = LabelEncoder()
label_enc.fit(y)

model_predictions = np.random.uniform(0,1, 3)
model_predictions = (model_predictions>0.5).astype(int).ravel()
model_predictions = label_enc.inverse_transform(model_predictions)

Answered By – Marco Cerliani

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published