Imagine your have five different classes e.g. ['cat', 'dog', 'fish', 'bird', 'ant']. If you would use one-hot-encoding you would represent the presence of 'dog' in a five-dimensional binary vector like [0,1,0,0,0]. If you would use multi-hot-encoding you would first label-encode your classes, thus having only a single number which represents the presence of a class (e.g. 1 for 'dog') and then convert the numerical labels to binary vectors of size .
Examples:
'cat' = [0,0,0]
'dog' = [0,0,1]
'fish' = [0,1,0]
'bird' = [0,1,1]
'ant' = [1,0,0]
This representation is basically the middle way between label-encoding, where you introduce false class relationships (0 < 1 < 2 < ... < 4, thus 'cat' < 'dog' < ... < 'ant') but only need a single value to represent class presence and one-hot-encoding, where you need a vector of size (which can be huge!) to represent all classes but have no false relationships.
Note: multi-hot-encoding introduces false additive relationships, e.g. [0,0,1] + [0,1,0] = [0,1,1] that is 'dog' + 'fish' = 'bird'. That is the price you pay for the reduced representation.
Imagine your have five different classes e.g. ['cat', 'dog', 'fish', 'bird', 'ant']. If you would use one-hot-encoding you would represent the presence of 'dog' in a five-dimensional binary vector like [0,1,0,0,0]. If you would use multi-hot-encoding you would first label-encode your classes, thus having only a single number which represents the presence of a class (e.g. 1 for 'dog') and then convert the numerical labels to binary vectors of size .
Examples:
'cat' = [0,0,0]
'dog' = [0,0,1]
'fish' = [0,1,0]
'bird' = [0,1,1]
'ant' = [1,0,0]
This representation is basically the middle way between label-encoding, where you introduce false class relationships (0 < 1 < 2 < ... < 4, thus 'cat' < 'dog' < ... < 'ant') but only need a single value to represent class presence and one-hot-encoding, where you need a vector of size (which can be huge!) to represent all classes but have no false relationships.
Note: multi-hot-encoding introduces false additive relationships, e.g. [0,0,1] + [0,1,0] = [0,1,1] that is 'dog' + 'fish' = 'bird'. That is the price you pay for the reduced representation.
The accepted answer seems rather eccentric to me. I think that is rarely done, if ever, and will usually yield bad results.
There's a much more common, sensible use case for this. "Multi-hot encoding" doesn't seem to be a standard term, but I'm not sure there's any standard term. scikit-learn refers to a multi label binarizer.
This is simply used for multi label problems. That is, problems where more than one label can be associated with each example.
For example, say you are trying to detect whether certain types of animal are in a photo. Note that multiple types of animal can be in a single photo. Say the possible types of animal are ['cat', 'dog', 'fish', 'bird', 'ant']. A photo containing cats and dogs would be represented as [1, 1, 0, 0, 0].
keras - How to create multi-hot encoding from a list column in dataframe? - Data Science Stack Exchange
scikit learn - How to perform one hot encoding on multiple categorical columns - Data Science Stack Exchange
python - One-hot-encoding multiple columns in sklearn and naming columns - Stack Overflow
scikit learn - Multi-Feature One-Hot-Encoder with varying amount of feature instances - Data Science Stack Exchange
LabelEncoder is not made to transform the data but the target (also known as labels) as explained here. If you want to encode the data you should use OrdinalEncoder.
If you really need to do it this way:
categorical_cols = ['a', 'b', 'c', 'd']
from sklearn.preprocessing import LabelEncoder
# instantiate labelencoder object
le = LabelEncoder()
# apply le on categorical feature columns
data[categorical_cols] = data[categorical_cols].apply(lambda col: le.fit_transform(col))
from sklearn.preprocessing import OneHotEncoder
ohe = OneHotEncoder()
#One-hot-encode the categorical columns.
#Unfortunately outputs an array instead of dataframe.
array_hot_encoded = ohe.fit_transform(data[categorical_cols])
#Convert it to df
data_hot_encoded = pd.DataFrame(array_hot_encoded, index=data.index)
#Extract only the columns that didnt need to be encoded
data_other_cols = data.drop(columns=categorical_cols)
#Concatenate the two dataframes :
data_out = pd.concat([data_hot_encoded, data_other_cols], axis=1)
Otherwise:
I suggest you to use pandas.get_dummies if you want to achieve one-hot-encoding from raw data (without having to use OrdinalEncoder before) :
#categorical data
categorical_cols = ['a', 'b', 'c', 'd']
#import pandas as pd
df = pd.get_dummies(data, columns = categorical_cols)
You can also use drop_first argument to remove one of the one-hot-encoded columns, as some models require.
You can do dummy encoding using Pandas in order to get one-hot encoding as shown below:
import pandas as pd
# Multiple categorical columns
categorical_cols = ['a', 'b', 'c', 'd']
pd.get_dummies(data, columns=categorical_cols)
If you want to do one-hot encoding using sklearn library, you can get it done as shown below:
from sklearn.preprocessing import OneHotEncoder
onehotencoder = OneHotEncoder()
transformed_data = onehotencoder.fit_transform(data[categorical_cols])
# the above transformed_data is an array so convert it to dataframe
encoded_data = pd.DataFrame(transformed_data, index=data.index)
# now concatenate the original data and the encoded data using pandas
concatenated_data = pd.concat([data, encoded_data], axis=1)
If a single column has more than 500 categories, the aforementioned way of one-hot encoding is not a good approach. In this case, we can do one-hot encoding for the top 10 or 20 categories that are occurring most for a particular column. A sample code is shown below:
categorical_cols = ['a', 'b', 'c', 'd']
# Let's say we have a column 'b' which has more than 500 categories.
# Find the top 10 most frequent categories for column 'b'
data.b.value_counts().sort_values(ascending = False).head(20)
# make a list of the most frequent categories of the column
top_10_occurring_cat = [cat for cat in data.b.value_counts().sort_values(ascending = False).head(10).index]
# now make the 10 binary variables
for cat in top_10_occurring_cat:
data[cat] = np.where(data['b'] == cat, 1, 0) # whenever data['b'] == cat replace it with 1 else 0
# This is done for one categorical column, similarly you can repeat for all categorical columns
You you are almost there... Like you said you can add all the columns you want to encode in fit_transform directly.
ohe = OneHotEncoder(categories='auto')
feature_arr = ohe.fit_transform(df[['phone','city']]).toarray()
feature_labels = ohe.categories_
And then you just need to do the following:
feature_labels = np.array(feature_labels).ravel()
Which enables you to name your columns like you wanted:
features = pd.DataFrame(feature_arr, columns=feature_labels)
this solution gives column names same as in pd.get_dummies(), what is useful IMO
labels = ['Sex', 'Embarked', 'Pclass']
categorical_data = data[labels]
ohe = OneHotEncoder(categories='auto')
feature_arr = ohe
.fit_transform(categorical_data)
.toarray()
ohe_labels = ohe.get_feature_names(labels)
features = pd.DataFrame(
feature_arr,
columns=ohe_labels)
I believe @David Masip's answer can now be further improved upon by providing a custom analyzer to CountVectorizer.
Joining all the features into a single string has a few issues:
- Wouldn't work well with features containing whitespace
- Wouldn't work well with features containing accents, stop words, etc. due to CountVectorizer's tokenization
Luckily, CountVectorizer now offers a way to provide a custom tokenizer via the analyzer argument. So, we could just keep passing lists of values as input, and have a custom analyzer pass those lists through without tokenization:
from sklearn.feature_extraction.text import CountVectorizer
X = [["banana","apple","cucumber"], ["orange","banana", "cucumber"]]
enc = CountVectorizer(analyzer=lambda lst: lst)
print(enc.fit_transform(X).toarray())
This produces the same result
[[1 1 1 0]
[0 1 1 1]]
while avoiding the issues listed above, and also saving CPU cycles/memory by not joining and re-tokenizing features.
I think you can transform this into a text preprocessing problem and then use CountVectorizer. You basically build "documents" by putting together all the words in your raw data and then use CountVectorizer on those documents.
from sklearn.feature_extraction.text import CountVectorizer
X = [["banana","apple","cucumber"], ["orange","banana", "cucumber"]]
# Create documents
X_ = [' '.join(x) for x in X]
enc = CountVectorizer()
print(enc.fit_transform(X_).toarray())
Returns
[[1 1 1 0]
[0 1 1 1]]
which has 4 different values as you expected.
A simple example which encodes an array using LabelEncoder, OneHotEncoder, LabelBinarizer is shown below.
I see that OneHotEncoder needs data in integer encoded form first to convert into its respective encoding which is not required in the case of LabelBinarizer.
from numpy import array
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OneHotEncoder
from sklearn.preprocessing import LabelBinarizer
# define example
data = ['cold', 'cold', 'warm', 'cold', 'hot', 'hot', 'warm', 'cold',
'warm', 'hot']
values = array(data)
print "Data: ", values
# integer encode
label_encoder = LabelEncoder()
integer_encoded = label_encoder.fit_transform(values)
print "Label Encoder:" ,integer_encoded
# onehot encode
onehot_encoder = OneHotEncoder(sparse=False)
integer_encoded = integer_encoded.reshape(len(integer_encoded), 1)
onehot_encoded = onehot_encoder.fit_transform(integer_encoded)
print "OneHot Encoder:", onehot_encoded
#Binary encode
lb = LabelBinarizer()
print "Label Binarizer:", lb.fit_transform(values)

Another good link which explains the OneHotEncoder is: Explain onehotencoder using python
There may be other valid differences between the two which experts can probably explain.
A difference is that you can use OneHotEncoder for multi column data, while not for LabelBinarizer and LabelEncoder.
from sklearn.preprocessing import LabelBinarizer, LabelEncoder, OneHotEncoder
X = [["US", "M"], ["UK", "M"], ["FR", "F"]]
OneHotEncoder().fit_transform(X).toarray()
# array([[0., 0., 1., 0., 1.],
# [0., 1., 0., 0., 1.],
# [1., 0., 0., 1., 0.]])
LabelBinarizer().fit_transform(X)
# ValueError: Multioutput target data is not supported with label binarization
LabelEncoder().fit_transform(X)
# ValueError: bad input shape (3, 2)
I have a pandas data series of strings that each have a bunch of text symbols in them (I'll call them words for discussion's sake, but in my use case they aren't actually words). The series of strings is already parsed to give me a vocabulary of all the words found anywhere in the series.
I've taken that vocabulary (vocab1, a list of all the words in the vocabulary) and made a dict (vocab) to assign an index to each word:
vocab = {c:i for i,c in enumerate(vocab1)}I need to change these strings into a multi-hot encoded numpy array (for machine learning blah blah). The arrays are the size of the vocabulary. 1 at a given position in the array indicates the absence of the corresponding word in the string, while 0 indicates its absence. The strings typically only have a few words in them (which sometimes are redundantly repeated in the original data) but there are 30k different words in the vocabulary, and in the broader use case this goes up to 260k or so.
Anyway, vocablength is the number of words in the vocabulary. I'm using pandas.Series.transform to apply my function to the entire series, which is over 200k strings (and will be millions in the broader use case).
def multihot_codes(codes):
o = np.zeros((vocablength,),dtype=np.int32)
for k in codes.split():
o[vocab[k]] = 1
return o
df["codesmh"] = df["codess"].transform(multihot_codes)This takes close to forever and has significant disk usage. There's probably a faster way to do this. For example, Tensorflow generates binary one-hot vectors for each word and then does a row reduce on them, but if you dig into the code, they have a compiled C++ module that does the heavy lifting. Not exactly what I'm prepared to do here myself....
Any ideas on how to improve this, or if there's something already in numpy/scipy or another package that's suited for use here? Thanks in advance!
Your original approach, without one-hot encoding, was doing what you wanted.
One-hot encoding is meant for inputs to many models, but outputs for only a few (e.g. training a neural network with cross-entropy loss). So these are only needed for some algorithm implementations, while others can do fine without it.
For output labels, a classifier like RandomForest is just fine with strings and multiple classes.
You don't have to make one hot encoding when using random forest in sklearn.
What you need is "label encoder", and your Y should looks like
from sklearn.preprocessing import LabelEncoder
y = ["A","B","D","A","C"]
le = LabelEncoder()
le.fit_transform(y)
# array([0, 1, 3, 0, 2], dtype=int64)
I tried to modified the sample code sklearn provided :
from sklearn.ensemble import RandomForestClassifier
import numpy as np
from sklearn.datasets import make_classification
>>> X, y = make_classification(n_samples=1000, n_features=4,
... n_informative=2, n_redundant=0,
... random_state=0, shuffle=False)
y = np.random.choice(["A","B","C","D"],1000)
print(y.shape)
>>> clf = RandomForestClassifier(max_depth=2, random_state=0)
>>> clf.fit(X, y)
>>> clf.classes_
# array(['A', 'B', 'C', 'D'], dtype='<U1')
Either process the y with label encoding or without, it both worked with RandomForestClassifier.