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)
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)
归档时间: |
|
查看次数: |
8144 次 |
最近记录: |