How can I one hot encode a list of strings with Keras?

余生颓废 提交于 2020-04-07 04:00:07

问题


I have a list:

code = ['<s>', 'are', 'defined', 'in', 'the', '"editable', 'parameters"', '\n', 'section.', '\n', 'A', 'larger', '`tsteps`', 'value', 'means', 'that', 'the', 'LSTM', 'will', 'need', 'more', 'memory', '\n', 'to', 'figure', 'out']

And I want to convert to one hot encoding. I tried:

to_categorical(code)

And I get an error: ValueError: invalid literal for int() with base 10: '<s>'

What am I doing wrong?


回答1:


keras only supports one-hot-encoding for data that has already been integer-encoded. You can manually integer-encode your strings like so:

Manual encoding

# this integer encoding is purely based on position, you can do this in other ways
integer_mapping = {x: i for i,x in enumerate(code)}

vec = [integer_mapping[word] for word in code]
# vec is
# [0, 1, 2, 3, 16, 5, 6, 22, 8, 22, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]

Using scikit-learn

from sklearn.preprocessing import LabelEncoder
import numpy as np

code = np.array(code)

label_encoder = LabelEncoder()
vec = label_encoder.fit_transform(code)

# array([ 2,  6,  7,  9, 19,  1, 16,  0, 17,  0,  3, 10,  5, 21, 11, 18, 19,
#         4, 22, 14, 13, 12,  0, 20,  8, 15])

You can now feed this into keras.utils.to_categorical:

from keras.utils import to_categorical

to_categorical(vec)



回答2:


Try converting it to a numpy array first:

from numpy import array

and then:

to_categorical(array(code))



来源:https://stackoverflow.com/questions/56227671/how-can-i-one-hot-encode-a-list-of-strings-with-keras

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!