You need to enable JavaScript to run this app. 如何在TensorFlow Keras函数式API中实现跨类别编码
优惠活动
大模型
产品
解决方案
定价
更多

如何在TensorFlow Keras函数式API中实现跨类别编码

基于Keras函数式API实现跨类别特征查找的实现方案

原有实现的核心偏差

  • 逻辑混用:同时使用旧版tf.feature_column体系和原生Keras函数式API层,两套机制的输入输出维度不兼容,无法直接串联
  • API参数误用:CategoryCrossing是输入张量拼接类的层,不接收词表列表作为初始化参数,之前直接传年级、成绩的词表列表会导致层初始化失败
  • 维度不匹配:模型输出层维度和成绩类别数不一致,损失函数和目标编码方式不匹配
  • 数据拼写错误:年级集合中将Senior拼写为Senor,会导致查找表匹配失效

卡点对应解决方案

1. 分类特征到编码表的映射(适配函数式API)

  • 替代旧的categorical_column_with_vocabulary_list:直接使用tf.keras.layers.StringLookup,这是原生Keras层,可直接接在tf.keras.Input后面,完成字符串到整数索引的查找映射
  • 替代旧的crossed_column:使用tf.keras.layers.CategoryCrossing完成年级、成绩的跨类别哈希组合,层的输入是前序查找层的输出张量,哈希桶数设置为年级数*成绩数即可和原crossed_column逻辑对齐
  • 替代旧的embedding_column:使用tf.keras.layers.Embedding对跨类别组合后的索引做可训练的嵌入映射,全程不需要额外的类型转换,完全适配函数式API的组网逻辑

2. 训练阶段的目标数据编码

  • 单独初始化一个和成绩词表绑定的StringLookup层,在构建Dataset时直接将字符串格式的目标值转换为整数类别索引
  • 损失函数使用SparseCategoricalCrossentropy,不需要把目标值转成one-hot向量,减少内存占用
  • 目标编码用的查找层不需要加入模型的推理链路,只做训练阶段的标签转换即可

3. 模型输出反向映射为成绩文本

  • 将之前初始化的成绩词表传入StringLookup层,设置invert=True,即可把模型输出的整数预测值,通过查找表反向映射回对应的成绩文本
  • 不需要依赖旧的grade_buckets特征列对象,全流程统一使用原生Keras预处理层

修正后的可运行核心代码

import pandas as pd
import numpy as np
import tensorflow as tf
from tensorflow.keras import layers, Model

# 定义词表(修正原数据的拼写错误)
grades_vocab = ['A','B','C','D','E','F']
classes_vocab = ['Freshman', 'Sophomore', 'Junior', 'Senior']

# 保留原示例的sample_df结构(数据行完全沿用用户提供的示例数据)
sample_df = pd.DataFrame(
    # 此处省略原示例的15行样本数据,列名保持不变:Freshman_1/2/3、Sophomore_1/2/3、Junior_1/2/3、Senior_1/2/3、TARGET
)

def create_ds(dataframe):
    df = dataframe.copy()
    target = df.pop('TARGET')
    # 目标值编码:字符串转整数索引
    target_lookup = layers.StringLookup(vocabulary=grades_vocab, output_mode='int')
    target_encoded = target_lookup(target)
    ds = tf.data.Dataset.from_tensor_slices((dict(df), target_encoded))
    return ds, target_lookup

# 按年级分组列名的逻辑完全沿用用户原有实现
group = {}
group['Freshman'] = [col for col in sample_df if col.startswith("Freshman")]
group['Sophomore'] = [col for col in sample_df if col.startswith("Sophomore")]
group['Junior'] = [col for col in sample_df if col.startswith("Junior")]
group['Senior'] = [col for col in sample_df if col.startswith("Senior")]

# 初始化所有公共预处理层
grade_lookup = layers.StringLookup(vocabulary=grades_vocab, output_mode='int')
crossing_layer = layers.CategoryCrossing(num_buckets=len(classes_vocab)*len(grades_vocab))
embed_layer = layers.Embedding(input_dim=len(classes_vocab)*len(grades_vocab), output_dim=8)

inputs = []
encoded_features = []

for class_name, student_cols in group.items():
    for col_name in student_cols:
        input_tensor = tf.keras.Input(shape=(), name=col_name, dtype='string')
        inputs.append(input_tensor)
        # 第一步:学生成绩字符串转整数索引
        grade_idx = grade_lookup(input_tensor)
        # 第二步:拼接固定年级标识,做跨类别组合
        class_idx = classes_vocab.index(class_name)
        crossed = crossing_layer([tf.constant(class_idx, dtype=tf.int64), grade_idx])
        # 第三步:跨类别特征嵌入映射
        embedded = embed_layer(crossed)
        encoded_features.append(embedded)

# 组网
x = layers.concatenate(encoded_features)
x = layers.Dense(32, activation="relu")(x)
output = layers.Dense(len(grades_vocab), activation="softmax")(x)

model = Model(inputs=inputs, outputs=output)
model.compile(
    optimizer='adam',
    loss=tf.keras.losses.SparseCategoricalCrossentropy(),
    metrics=["accuracy"]
)

# 训练
sample_ds, target_lookup = create_ds(sample_df)
model.fit(sample_ds.batch(3), epochs=10)

# 反向映射为成绩文本
inverse_grade_lookup = layers.StringLookup(vocabulary=grades_vocab, invert=True)
# 示例:取预测结果的最高概率索引,转成文本
sample_pred = model.predict(sample_ds.batch(1))
pred_idx = tf.argmax(sample_pred, axis=-1)
pred_grade_text = inverse_grade_lookup(pred_idx)

常见问题提示

  • StringLookup层的输入形状不要设置多余的维度:原来的Input(shape=(1,), dtype='string')会导致和后续层的形状不匹配,改成shape=()即可匹配Dataset返回的一维字符串样本
  • CategoryCrossing层的输入必须是整数类型的张量,不能直接传字符串,需要提前经过StringLookup转换
  • 跨类别组合的哈希桶数不要设置过小,避免不同类别对被哈希到同一个桶里丢失信息

内容的提问来源于stack exchange,提问作者P-Rod

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.15 16:36:04