我有一个列表:
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>'
我在做什么错了?
答案 0 :(得分:4)
代替使用
pandas.get_dummies(y_train)
答案 1 :(得分:1)
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]
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 :(得分:-1)
首先尝试将其转换为numpy
数组:
from numpy import array
然后:
to_categorical(array(code))