首页 > 解决方案 > Keras 预处理层

问题描述

我正在尝试为神经网络提供 50 个特征(所有是/否值)来预测一个是/否标签的概率。我正在尝试使用 keras 来做到这一点CategoryEncoding,但遇到了一些问题。

我的代码的开头如下:

model = Sequential([
    tf.keras.Input(shape = (50,)),
    tf.keras.layers.CategoryEncoding(num_tokens=100, output_mode='one_hot'),
    tf.keras.layers.LayerNormalization(),
    tf.keras.layers.Dense(1024, activation='relu'),
    tf.keras.layers.Dense(32, activation='relu'),
    tf.keras.layers.Dropout(0.2),
    tf.keras.layers.Dense(1, activation='softmax')
])

但是,我在下面收到此错误:

ValueError: Exception encountered when calling layer "category_encoding_12" (type CategoryEncoding).

When output_mode is not `'int'`, maximum supported output rank is 2. Received output_mode one_hot and input shape (None, 50), which would result in output rank 3.

Call arguments received:
  • inputs=tf.Tensor(shape=(None, 50), dtype=float32)
  • count_weights=None

我正在查看文档,但我认为我不完全理解令牌在其上下文中的含义。另外,我将如何在这里预处理我的标签?我可以使用pd.get_dummies,但我不知道 tensorflow 是否有任何东西可以自动执行此操作?

标签: pythontensorflowkerasdata-preprocessing

解决方案


正如错误消息所暗示的,当输出模式不是时int,请使用 multi_hot 而不是 one_hot。

num_tokens

该层应支持的令牌总数。该层的所有输入必须是 0 <= value < num_tokens 范围内的整数,否则将引发错误。

import tensorflow as tf
x = tf.keras.Input(shape = (50,))
y = tf.keras.layers.CategoryEncoding(
          num_tokens=100, output_mode="multi_hot")
y(x)

输出

<KerasTensor: shape=(None, 100) dtype=float32 (created by layer 'category_encoding_15')>

推荐阅读