【问题标题】:Keras preprocessing layerKeras 预处理层
【发布时间】:2026-02-13 12:50:01
【问题描述】:

我正在尝试为神经网络提供 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是否有什么可以自动做到这一点?

【问题讨论】:

    标签: python tensorflow keras data-preprocessing


    【解决方案1】:

    当输出模式不是int 时,错误消息提示,请使用 multi_hot 而不是 one_hot。

    num_tokens

    层应支持的令牌总数。所有输入到 layer 必须是 0

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

    【讨论】: