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

加载TF Hub的BERT模块时遇TypeError:'AutoTrackable'对象不可调用

解决TensorFlow 2.x中从TF Hub BERT模块创建Tokenizer的TypeError问题

错误原因

你用的是TensorFlow 1.X时代的代码,在TF2.12.0中完全不兼容:

  • TF2里hub.load()返回的是AutoTrackable对象,不能像TF1那样直接调用获取tokenization_info
  • TF2已经废弃了tf.compat.v1.Session()的必要操作,不需要手动启动会话获取值

解决方案1:适配TF Hub的TF2写法

先安装依赖库:

!pip install tensorflow-hub bert-tensorflow

修改后的代码:

import tensorflow as tf
import tensorflow_hub as hub
from bert.tokenization import FullTokenizer

bert_path = "https://tfhub.dev/google/bert_uncased_L-12_H-768_A-12/1"

def create_tokenizer_from_hub_module():
    # 加载TF Hub模块
    bert_module = hub.load(bert_path)
    # 获取tokenization_info对应的签名函数
    tokenization_fn = bert_module.signatures["tokenization_info"]
    # 调用函数获取结果(TF2中返回Tensor对象)
    tokenization_info = tokenization_fn()
    
    # 将Tensor转换为Python可用的格式
    vocab_file = tokenization_info["vocab_file"].numpy().decode("utf-8")
    do_lower_case = tokenization_info["do_lower_case"].numpy()
    
    return FullTokenizer(vocab_file=vocab_file, do_lower_case=do_lower_case)

# 实例化Tokenizer
tokenizer = create_tokenizer_from_hub_module()

解决方案2:使用Hugging Face Transformers(更推荐,适合新手)

如果不想处理TF Hub的兼容性问题,直接用Hugging Face的Tokenizer,一步到位:

!pip install transformers
from transformers import BertTokenizer

# 对应你使用的TF Hub模型,Hugging Face侧的模型名称是bert-base-uncased
tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")

这个方式不需要手动处理词汇文件,封装了所有细节,和TF2完全兼容,后续使用也更灵活。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 15:32:17