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

19

我有一个列表:

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']

我想将其转换为独热编码(One-hot encoding)。我尝试了:

to_categorical(code)

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

我做错了什么?


1
根据文档to_categorical的参数需要是整数向量,而不是字符串。 - C.Nivs
我该如何将这些字符串转换为整数? - Shamoon
4个回答

21

Keras 仅支持已经过整数编码的数据进行 one-hot 编码。您可以手动将字符串进行整数编码:

手动编码

# 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]

使用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])
你现在可以将其输入到 keras.utils.to_categorical 中:
from keras.utils import to_categorical

to_categorical(vec)

这会为重复项创建2个编码,对吗? - Shamoon
2
如果vec相同,则to_categorical将返回相同的值。 - C.Nivs

8

建议使用

pandas.get_dummies(y_train)

1

tf.keras.layers.CategoryEncoding

在TF 2.6.0中,可以使用tf.keras.layers.CategoryEncodingtf.keras.layers.StringLookuptf.keras.layers.IntegerLookup实现One Hot Encoding(OHE)或Multi Hot Encoding(MHE)。
我认为这种方式在TF 2.4.x中不可行,因此必须是后来才实现的。

enter image description here

请参见使用Keras预处理层对结构化数据进行分类以获取实际实现。
def get_category_encoding_layer(name, dataset, dtype, max_tokens=None):
  # Create a layer that turns strings into integer indices.
  if dtype == 'string':
    index = layers.StringLookup(max_tokens=max_tokens)
  # Otherwise, create a layer that turns integer values into integer indices.
  else:
    index = layers.IntegerLookup(max_tokens=max_tokens)

  # Prepare a `tf.data.Dataset` that only yields the feature.
  feature_ds = dataset.map(lambda x, y: x[name])

  # Learn the set of possible values and assign them a fixed integer index.
  index.adapt(feature_ds)

  # Encode the integer indices.
  encoder = layers.CategoryEncoding(num_tokens=index.vocabulary_size())

  # Apply multi-hot encoding to the indices. The lambda function captures the
  # layer, so you can use them, or include them in the Keras Functional model later.
  return lambda feature: encoder(index(feature))

-2

尝试先将其转换为 numpy 数组:

from numpy import array

然后执行:

to_categorical(array(code))


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接