[英]Initialise Keras StringLookup with DataFrame list column
我在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 接受的内容?
您必须将字符串列表列表转换为单个列表,然后您的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']
另请查看有关不同展平方法性能的帖子。
作为替代方案,你可以使用tf.ragged.constant在你的col
pd.Series。
lookup_layer = tf.keras.layers.StringLookup(max_tokens=335)
lookup_layer.adapt(tf.ragged.constant(df.col))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.