【发布时间】:2020-09-08 03:05:41
【问题描述】:
我正在研究逻辑回归模型,以借助 TensorFlow 中的 Keras 来预测客户是商业客户还是非商业客户。目前我可以在tf.feature_columns 的帮助下使用像纬度这样的列。现在我正在处理 NAME1 字段。该名称通常具有重复的部分,例如“GmbH”(例如“Mustermann GmbH”),在这种情况下,它与 Corp. 具有相似的含义,表示客户是商业客户。为了分离名称的所有不同部分并分别使用它们,我在函数text_to_word_sequence() 的帮助下使用标记化。
我将数据导入到 Pandas Dataframe 中,然后使用 from_tensor_slices() 函数将此 Dataframe 转换为 TensorFlow 数据集,这样我就可以使用 tf.feature_columns 函数。
我尝试了两种不同的标记化策略:
-
将 pandas Dataframe 转换为 TensorFlow Dataset 之前的标记化
导入 Dataframe 后,我使用 Pandas Dataframe 方法
apply()在 Dataframe 中创建一个新的标记化列:data['NAME1TOKENIZED'] = data['NAME1'].apply(lambda x: text_to_word_sequence(x))新列的结构如下:
0 [palle]
1 [pertl]
2 [graf, robert]
3 [löberbauer, stefanie, asg]
4 [stauber, martin, asg]
...
99995 [truber]
99996 [mesgec]
99997 [mesgec]
99998 [miedl]
99999 [millegger]
Name: NAME1TOKENIZED, Length: 100000, dtype: object
如您所见,列表具有不同数量的条目,因此我无法将 Dataframe 转换为 Dataset:
ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type list).
我还尝试了tf.ragged.constant() 函数来创建一个允许这种类型列表的参差不齐的张量。
这是我将 DataFrame 转换为 Dataset 的函数:
def df_to_dataset(dataframe, shuffle=True, batch_size=32):
dataframe = dataframe.copy()
tok_names = dataframe.loc[:,'NAME1TOKENIZED']
del dataframe['NAME1TOKENIZED']
rt_tok_names = tf.ragged.constant(tok_names)
labels = dataframe.pop('RECEIVERTYPE')
labels = labels - 1
ds = tf.data.Dataset.from_tensor_slices((dict(dataframe), rt_tok_names, labels))
if shuffle:
ds = ds.shuffle(buffer_size=len(dataframe))
ds = ds.batch(batch_size)
return ds
这很好用,但正如你想象的那样,现在我在另一边遇到了问题。当我现在尝试使用以下功能时:
name_embedding = tf.feature_column.categorical_column_with_hash_bucket('NAME1TOKENIZED', hash_bucket_size=2500)
我收到以下错误:
ValueError: Feature NAME1TOKENIZED is not in features dictionary.
我还尝试在tf.ragged.constant() 中输入 Dataframe 而不是 Serie,因此我可以使用 dict(rt_tok_names) 传递标签,但随后我再次收到以下错误:
ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type list).
- 将 pandas Dataframe 转换为 TensorFlow Dataset 后的标记化 我试过了,例如以下内容:
train_ds.map(lambda x, _: text_to_word_sequence(x['NAME1']))
但我收到以下错误:
AttributeError: 'Tensor' object has no attribute 'lower'
如您所见,我尝试了多种方法,但均未成功。对于如何解决我的问题的任何建议,我都会很高兴。
谢谢!
【问题讨论】:
标签: python pandas dataframe tensorflow feature-engineering