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

如何仅使用tensorflow-cpu包通过URL加载模型?

仅用tensorflow-cpu从URL加载Universal Sentence Encoder模型的可行方案

由于TensorFlow Hub上的模型本质是标准的SavedModel格式,你可以绕过tensorflow-hub包,直接通过下载模型文件并使用tensorflow-cpu的tf.saved_model.load()加载,以此减少项目依赖体积,适配Heroku的slug限制。具体实现如下:

方法:运行时下载并加载模型

利用TensorFlow内置的文件下载工具,在应用启动时将模型下载到Heroku的临时目录(/tmp),再加载模型。这种方式不会将模型打包进slug,完全依赖tensorflow-cpu即可。

示例代码

import tensorflow as tf
import os

# 对应Universal Sentence Encoder 4的直接下载链接
model_download_url = "https://storage.googleapis.com/tfhub-modules/google/universal-sentence-encoder/4.tar.gz"

# 指定临时存储目录,避免占用slug空间
cache_dir = "/tmp/tfhub_models"
os.makedirs(cache_dir, exist_ok=True)

# 下载并解压模型(自动跳过已下载的文件)
model_dir = tf.keras.utils.get_file(
    fname="universal_sentence_encoder_4",
    origin=model_download_url,
    extract=True,
    cache_dir=cache_dir,
    cache_subdir=""
)

# 加载SavedModel格式的模型
model = tf.saved_model.load(model_dir)
print("Universal Sentence Encoder模型加载完成")

部署优化

  1. 在requirements.txt中仅保留tensorflow-cpu(指定与模型兼容的版本,如tensorflow-cpu==2.15.0),移除tensorflow-hub依赖,大幅降低slug体积。
  2. 注意:Universal Sentence Encoder 4解压后体积约为1GB,若Heroku默认临时存储(/tmp)空间不足,可升级Heroku的临时存储扩展来解决容量问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 02:35:08