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

如何修复Python中Sequential对象无_get_save_spec属性的AttributeError?

解决AttributeError: 'Sequential' object has no attribute '_get_save_spec'问题

问题复现

运行以下代码时触发错误:

import tensorflow as tf

model = tf.keras.models.load_model("../mymodel.keras")
model.compile(optimizer='adam', 
              loss='sparse_categorical_crossentropy', 
              metrics=['accuracy'])
model.save('saved_model.keras')

model = tf.keras.models.load_model('saved_model.keras')
model.compile(optimizer='adam', 
             loss='sparse_categorical_crossentropy', metrics= 
             ['accuracy'])

converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()

错误信息:

AttributeError: 'Sequential' object has no attribute '_get_save_spec'

解决方案

以下是几种可行的修复思路:

  • 统一TensorFlow版本
    该错误常因模型保存与加载时使用的TensorFlow版本不兼容导致。确保保存原始mymodel.keras的TF版本与当前运行代码的TF版本一致,优先选用官方稳定版(如2.15.x、2.16.x系列)。

  • 触发模型完整构建
    Keras Sequential模型采用延迟构建机制,若未经过前向传播,部分内部属性未初始化。可在转换前添加一次dummy输入的预测操作:

    import numpy as np
    # 根据你的模型输入形状调整,示例适配输入为(28,28)的模型
    dummy_input = np.random.rand(1, *model.input_shape[1:])
    model.predict(dummy_input)
    
    # 执行转换
    converter = tf.lite.TFLiteConverter.from_keras_model(model)
    tflite_model = converter.convert()
    
  • 改用SavedModel格式转换
    避免使用.keras格式中转,直接将模型保存为SavedModel目录后再执行转换:

    # 替换原代码中的保存与转换逻辑
    model = tf.keras.models.load_model("../mymodel.keras")
    # 转换TFLite无需训练配置,可省略compile步骤
    model.save('saved_model_dir')  # 保存为目录格式
    
    converter = tf.lite.TFLiteConverter.from_saved_model('saved_model_dir')
    tflite_model = converter.convert()
    
  • 移除不必要的compile操作
    转换TFLite仅需要模型的推理结构,不需要优化器、损失函数等训练相关配置,可直接去掉两次model.compile()调用,简化流程。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 04:56:00