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

无法加载TensorFlow Hub模型,代码无报错却卡住求助

解决TensorFlow Hub加载模型卡住无响应的问题

执行代码时,print('before')正常输出,但卡在hub.load("https://tfhub.dev/google/universal-sentence-encoder/4")步骤,无报错信息,程序无法继续运行。以下是针对性的解决方法:

  • 切换本地加载模型
    网络波动可能导致远程加载超时,建议手动下载模型文件到本地后加载:

    1. 从模型对应页面下载压缩包并解压;
    2. 修改代码加载本地路径:
    import tensorflow_hub as hub
    
    print('before')
    # 替换为本地模型解压后的实际路径
    embed = hub.load("./universal-sentence-encoder_4")
    print('after')
    
    embeddings = embed([
        "The quick brown fox jumps over the lazy dog.",
        "I am a sentence for which I would like to get its embedding"])
    
    print(embeddings)
    
  • 校验版本兼容性
    TensorFlow与TensorFlow Hub版本不匹配可能引发加载异常,执行以下命令升级到兼容版本:

    # 查看当前版本
    pip show tensorflow tensorflow-hub
    # 升级到适配TF2.x的版本
    pip install --upgrade tensorflow tensorflow-hub
    

    注意:Universal Sentence Encoder v4仅支持TensorFlow 2.0及以上版本。

  • 强制使用CPU运行
    部分GPU环境下可能存在加载阻塞问题,可临时禁用GPU加速:

    import tensorflow as tf
    import tensorflow_hub as hub
    
    # 限制仅使用CPU
    tf.config.set_visible_devices([], 'GPU')
    
    print('before')
    embed = hub.load("https://tfhub.dev/google/universal-sentence-encoder/4")
    print('after')
    
    embeddings = embed([
        "The quick brown fox jumps over the lazy dog.",
        "I am a sentence for which I would like to get its embedding"])
    
    print(embeddings)
    
  • 清理TensorFlow Hub缓存
    缓存文件损坏可能导致加载卡住,删除缓存目录后重新运行:

    • Linux/macOS:删除~/.cache/tensorflow/hub下的模型相关文件;
    • Windows:删除C:\Users\<你的用户名>\AppData\Local\Temp\tensorflow_hub下的模型相关文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 15:52:05