5

LabelEncoder won't "remember" parameters. When I fit and transform data with it then ask for the parameters, all I get is {}. This makes it impossible to re-use the encoder on new data.

Example:

from sklearn.preprocessing import LabelEncoder
encode = LabelEncoder()
encode.fit_transform(['one', 'two', 'three'])
print(encode.get_params())

Not sure about the intended format, but I expect something like {['one', 0], ['two', 1], ['three', 2]}

Actual Result: {}

I'm on:

Darwin-16.7.0-x86_64-i386-64bit
Python 3.6.1 |Anaconda 4.4.0 (x86_64)| (default, May 11 2017, 13:04:09) 
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)]
NumPy 1.12.1
SciPy 0.19.0
Scikit-Learn 0.18.1
Alexander
110k32 gold badges212 silver badges208 bronze badges
asked Aug 31, 2017 at 14:29

1 Answer 1

10

Label encoder stores the parameters in the classes_ attribute. You can obtain the encoded values transforming those classes and creating a dictionary. This encoder will work with new data that has the same labels otherwise it will raise a ValueError. Use the transform method on the labels you want to encode and that's it.

from sklearn import preprocessing
encode = preprocessing.LabelEncoder()
encode.fit_transform(['one', 'two', 'three'])
keys = encode.classes_
values = encode.transform(encode.classes_)
dictionary = dict(zip(keys, values))
print(dictionary)

Output: {'three': 1, 'two': 2, 'one': 0}

answered Aug 31, 2017 at 14:40
Sign up to request clarification or add additional context in comments.

2 Comments

This answer works for me, but does anyone know why OP's code did not work as intended? I arrived at this page by trying the same thing, as sklearn docs seem to indicate that the get_params function should return this dictionary..
The get_params method is inherited from BaseEstimator and basically does nothing in the LabelEncoder. There was an open issue about that on the project's github page (github.com/scikit-learn/scikit-learn/issues/9662)

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.