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

发布于 2021-01-29 15:58:55

我有一个清单:

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
被浏览
51
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    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)
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看