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

使用迁移学习的TensorFlow模型保存后重构失败求助

问题解决:迁移学习模型保存后加载失败

错误根源

  • 代码混用了tf_keras(TensorFlow内置Keras)和独立keras包,导致层体系不兼容:hub.KerasLayer属于TensorFlow内置Keras的层类型,但加载时调用了独立keras的load_model方法,被识别为非keras.Layer实例。
  • 加载模型时的模块导入与模型构建时的模块不统一,加剧了类型匹配问题。

修正方案

方案1:统一使用TensorFlow内置Keras(推荐)

全程使用tf.keras模块,避免跨模块混用,同时优先使用SavedModel格式保存模型(官方推荐,对自定义层兼容性更好):

import numpy as np
import tensorflow as tf
import tensorflow_hub as hub
from sklearn.model_selection import train_test_split
import os

# 数据加载逻辑不变
directory = "brain_tumor_dataset"
images = []
labels = []
for category in os.listdir(directory):
    rute_category = os.path.join(directory, category)
    for image_name in os.listdir(rute_category):
        image_rute = os.path.join(rute_category, image_name)
        image = tf.keras.preprocessing.image.load_img(image_rute, target_size=(224,224))
        image_array = tf.keras.preprocessing.image.img_to_array(image) / 255.0  
        images.append(image_array)
        labels.append(1 if category == "yes" else 0)
images = np.array(images)
labels = np.array(labels)
X_training, X_testing, y_training, y_testing = train_test_split(images, labels, test_size=0.3, random_state=42)

# 模型构建与训练逻辑不变,统一用tf.keras
url = "https://tfhub.dev/google/imagenet/mobilenet_v2_140_224/feature_vector/5"
movilenetv2 = hub.KerasLayer(url, input_shape=(224,224,3), trainable=False)
model = tf.keras.Sequential([
    movilenetv2,
    tf.keras.layers.Dense(2,activation="softmax")
])
model.compile(
    optimizer="adam",
    loss="sparse_categorical_crossentropy",
    metrics = ["accuracy"]
)
training = model.fit(
    X_training,
    y_training,
    epochs=20,
    validation_data = (X_testing, y_testing)
)

# 保存为SavedModel格式(无需后缀)
model.save("my_saved_model")

# 加载模型,指定自定义层
reconstructured_model = tf.keras.models.load_model(
    "my_saved_model",
    custom_objects={"KerasLayer": hub.KerasLayer}
)

方案2:坚持使用.h5格式(需严格统一模块)

如果必须用.h5格式,需全程使用同一Keras模块(比如tf_keras):

import numpy as np
import tensorflow as tf
import tensorflow_hub as hub
import tf_keras as tfk
from sklearn.model_selection import train_test_split
import os

# 数据加载、模型构建与训练逻辑不变,全程用tfk
# ...(省略重复代码)

# 保存为.h5格式
model.save("my_model.h5")

# 加载时用tfk的load_model方法,指定自定义层
reconstructured_model = tfk.models.load_model(
    "my_model.h5",
    custom_objects={"KerasLayer": hub.KerasLayer}
)

关键注意点

  • 禁止混用Keras模块:要么全程用tf.keras,要么全程用独立keras包,跨模块混用必然导致层类型匹配错误。
  • 优先选择SavedModel格式:该格式是TensorFlow官方推荐的模型保存方式,对包含自定义层、迁移学习层的模型支持更完善,比.h5格式稳定性更高。
  • 加载必须指定custom_objects:hub.KerasLayer属于第三方自定义层,加载时必须明确告诉Keras如何识别该层类。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 03:47:19