You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

tf.keras.layers.TextVectorization从保存配置重建后输出序列长度异常问题

异常原因说明
  • 该问题是TensorFlow 2.4~2.7版本的已知实现缺陷,核心诱因是TextVectorization.get_config()返回的output_mode字段并非原生Python字符串,而是Keras内部定义的枚举类型实例。
  • 代码中from_disk['config']['output_mode'] == 'int'返回True,是因为该枚举类重写了相等判断方法,但TextVectorization的初始化逻辑有严格的类型校验:只有当output_mode传入**原生字符串'int'**时,才会触发output_sequence_length对应的填充/截断逻辑;传入枚举类型的'int'时,内部判断分支未匹配到对应模式,自动忽略了output_sequence_length参数,只会输出原始分词长度的序列。
  • 硬编码传入output_mode='int'时,参数是原生字符串,能被逻辑正确识别,因此padding规则正常生效。

修复方案

你可以选择以下任意一种方式解决该问题:

  1. 加载配置时强制转换output_mode为字符串类型:
new_v1 = tf.keras.layers.TextVectorization(
        max_tokens=None,
        standardize="lower_and_strip_punctuation",
        split="whitespace",
        output_mode=str(from_disk['config']['output_mode']),
        output_sequence_length=from_disk['config']['output_sequence_length'],
        )
  1. 直接调用官方提供的from_config方法加载配置,内部会自动处理类型匹配问题,无需手动传参:
new_v1 = tf.keras.layers.TextVectorization.from_config(from_disk['config'])
new_v1.set_weights(from_disk['weights'])
# TensorFlow 2.6及以上版本使用该方法加载,无需额外调用dummy adapt

内容的提问来源于stack exchange,提问作者lankuohsing

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 23:30:03