【问题标题】:How can I one hot encode a list of strings with Keras?如何使用 Keras 对字符串列表进行热编码?
【发布时间】:2019-10-07 05:18:50
【问题描述】:

我有一个清单:

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: '&lt;s&gt;'

我做错了什么?

【问题讨论】:

  • 根据docsto_categorical 的参数必须是整数向量,而不是字符串
  • 如何将这些字符串转换为整数?

标签: python keras one-hot-encoding


【解决方案1】:

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

from numpy import array

然后:

to_categorical(array(code))

【讨论】:

    【解决方案2】:

    keras 只支持对已经整数编码的数据进行 one-hot-encoding。您可以像这样手动对字符串进行整数编码:

    手动编码

    # 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 个编码,对吧?
    • 如果vec 相同,那么是的,to_categorical 将返回相同的值
    【解决方案3】:

    改为使用

    pandas.get_dummies(y_train)
    

    【讨论】:

      【解决方案4】:

      tf.keras.layers.CategoryEncoding

      在 TF 2.6.0 中,可以使用 tf.keras.layers.CategoryEncodingtf.keras.layers.StringLookuptf.keras.layers.IntegerLookup 实现单热编码 (OHE) 或多热编码 (MHE)。

      我认为这种方式在 TF 2.4.x 中是不合理的,所以它一定是在之后实现的。

      具体实现见Classify structured data using Keras preprocessing layers

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

      【讨论】:

        猜你喜欢
        • 2018-05-26
        • 1970-01-01
        • 2020-08-12
        • 2023-04-10
        • 1970-01-01
        • 1970-01-01
        • 2020-12-27
        • 2018-06-29
        相关资源
        最近更新 更多