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

TensorFlow将.pb转.tflite报错:模型非支持的SavedModel格式

解决冻结图转TFLite时的「Model is not saved in the supported SavedModel format」报错

这个报错我帮人排查过好多次,核心原因其实很直白:你手里的是单个冻结.pb文件,但转换命令默认在找SavedModel格式的目录结构,两者不是一回事,所以触发了MaybeSavedModelDirectory的检查错误。下面给你分步骤解决:

一、先搞懂两种格式的区别

  • 冻结图(.pb):把模型的计算图结构和权重参数打包成单个文件,没有固定目录规范。
  • SavedModel:TensorFlow官方推荐的标准格式,是一个目录,里面必须包含saved_model.pb文件和variables文件夹(存权重),tflite_convert默认优先识别这种格式。

二、针对冻结图的正确转换方法

如果你只有冻结.pb文件,别用--saved_model_dir参数,改用--graph_def_file指定.pb文件,同时必须明确输入输出节点的名字。

1. 先找到输入输出节点名

你需要知道模型输入层和输出层的节点名称,用这段代码就能查出来:

import tensorflow as tf

# 加载冻结图
with tf.io.gfile.GFile('你的冻结图文件名.pb', 'rb') as f:
    graph_def = tf.compat.v1.GraphDef()
    graph_def.ParseFromString(f.read())

# 打印所有节点名称
with tf.compat.v1.Session() as sess:
    sess.graph.as_default()
    tf.import_graph_def(graph_def, name='')
    for op in sess.graph.get_operations():
        print(op.name)

运行后,找类似input_1(输入层)、dense_2/Softmax(分类任务的输出层,通常是Softmax节点)这样的名字记下来。

2. 用命令行转换

用tflite_convert(TF2.x里已经替代了旧的toco)执行以下命令,替换成你的参数:

tflite_convert \
  --graph_def_file=你的冻结图文件名.pb \
  --output_file=输出的tflite文件名.tflite \
  --input_arrays=刚才找到的输入节点名 \
  --output_arrays=刚才找到的输出节点名

如果你的输入有固定形状(比如224x224的RGB图),可以加上--input_shapes=输入节点名:[1,224,224,3](1是batch大小,按需调整)。

3. 更可靠的Python API转换

怕命令行出错的话,用TensorFlow的Python API更直观:

import tensorflow as tf

# 初始化转换器,指定冻结图路径和输入输出节点
converter = tf.lite.TFLiteConverter.from_frozen_graph(
    graph_def_file='你的冻结图文件名.pb',
    input_arrays=['输入节点名'],
    output_arrays=['输出节点名'],
    input_shapes={'输入节点名': [1, 224, 224, 3]}  # 可选,根据你的模型输入调整
)

# 执行转换并保存
tflite_model = converter.convert()
with open('输出的tflite文件名.tflite', 'wb') as f:
    f.write(tflite_model)

三、如果想改用SavedModel格式转换

如果你有训练好的模型(比如Keras模型),直接保存成SavedModel再转换更省心:

  1. 重新保存模型为SavedModel格式:
# 假设model是你训练好的Keras模型
model.save('saved_model_dir')  # TF2.x会自动生成标准的SavedModel目录
  1. 用命令行转换:
tflite_convert --saved_model_dir=saved_model_dir --output_file=model.tflite

四、注意版本问题

  • 如果你用的是TF1.x,确保toco命令是对应版本的,或者改用tf.contrib.lite.TocoConverter。
  • TF2.x里建议用tflite_convert或者上面的Python API,旧的toco命令已经被弃用,容易出兼容问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:31:01