【问题标题】:Initialise Keras StringLookup with DataFrame list column使用 DataFrame 列表列初始化 Keras StringLookup
【发布时间】:2021-12-19 19:42:11
【问题描述】:

我在 pd.DataFrame 列中有数据,格式如下:

   col
0  ['str1', 'str2', 'str3']
1  []
2  ['str1']
3  ['str20']

我使用下面的代码来构造一个查找层:

lookup_layer = tf.keras.layers.StringLookup(max_tokens=335)
lookup_layer.adapt(df.col)

失败的原因是:

ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type list).

我还尝试将该列连接到一个列表中,因为错误表明嵌套列表是问题所在:

lookup_layer.adapt(itertools.chain(*df.col))

导致:

AttributeError: 'str' object has no attribute 'shape'

我还尝试了各种tf.cast/tf.convert_to_tensor 调用,但无济于事。

如何将我的 DataFrame 字符串列表列转换为 Tensorflow 接受的内容?

【问题讨论】:

    标签: python pandas tensorflow keras keras-layer


    【解决方案1】:

    您必须将您的字符串列表转换为单个列表,然后您的StringLookup 层应该可以工作:

    import pandas as pd
    import tensorflow as tf
    import numpy as np
    
    d = {'col': [['str1', 'str2', 'str3'], [], ['str1', 'str2', 'str3'], ['str1', 'str2', 'str3']]}
    df = pd.DataFrame(data=d)
    
    lookup_layer = tf.keras.layers.StringLookup(max_tokens=335)
    flattened_data = sum(list(df.col), [])
    lookup_layer.adapt(flattened_data)
    print(lookup_layer.get_vocabulary())
    
    ['[UNK]', 'str3', 'str2', 'str1']
    

    还可以查看post,了解不同列表展平方法的性能。

    【讨论】:

      【解决方案2】:

      作为替代方案,您可以在col pd.Series 上使用tf.ragged.constant

      lookup_layer = tf.keras.layers.StringLookup(max_tokens=335)
      lookup_layer.adapt(tf.ragged.constant(df.col))
      

      【讨论】:

        猜你喜欢
        • 2011-06-05
        • 1970-01-01
        • 1970-01-01
        • 2018-07-15
        • 2018-10-29
        • 2021-08-08
        • 2020-05-14
        • 1970-01-01
        • 2016-09-13
        相关资源
        最近更新 更多