gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 11:18:11 27 4
gpt4 key购买 nike

我有一个 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']

我想转换为一种热编码。我试过:
to_categorical(code)

我收到一个错误: ValueError: invalid literal for int() with base 10: '<s>'
我究竟做错了什么?

最佳答案

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]

使用 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)

关于python - 如何使用 Keras 对字符串列表进行热编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56227671/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com