如何使用 Keras 对字符串列表进行热编码?

Sha*_*oon 14 python keras one-hot-encoding

我有一个清单:

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']
Run Code Online (Sandbox Code Playgroud)

我想转换为一种热编码。我试过:

to_categorical(code)
Run Code Online (Sandbox Code Playgroud)

我收到一个错误: ValueError: invalid literal for int() with base 10: '<s>'

我究竟做错了什么?

C.N*_*ivs 16

keras仅支持对已经整数编码的数据进行单热编码。您可以像这样手动对字符串进行整数编码:

手动编码

# 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]
Run Code Online (Sandbox Code Playgroud)

使用 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])
Run Code Online (Sandbox Code Playgroud)

您现在可以将其输入到keras.utils.to_categorical

from keras.utils import to_categorical

to_categorical(vec)
Run Code Online (Sandbox Code Playgroud)

  • 如果 `vec` 相同,那么是的,`to_categorical` 将返回相同的值 (2认同)

小智 6

而是使用

pandas.get_dummies(y_train)
Run Code Online (Sandbox Code Playgroud)