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

加载Keras模型报错:Layer dense_2预期1个输入却收到2个张量

问题分析与解决方案

错误原因

你在加载训练好的模型后,额外执行了子模型提取的代码,错误地指定了模型的输入层(使用预训练模型MobileNetV2的输入作为新模型的输入),导致模型在后续处理时接收到两个输入张量,与dense_2层预期的单个输入不匹配,从而抛出ValueError。

解决方案

方案1:直接加载模型用于测试(推荐)

如果你的需求只是加载模型进行预测测试,完全不需要子模型提取的步骤,直接加载模型即可使用:

# 加载模型
model_save_path = '/content/drive/MyDrive/Machine Learning/saved_models/model_plastik.h5'
loaded_model = tf.keras.models.load_model(model_save_path)

# 示例:用加载的模型预测单张图片
from tensorflow.keras.preprocessing import image
import numpy as np

# 定义预测函数
def predict_single_image(img_path):
    # 加载并预处理图片
    img = image.load_img(img_path, target_size=(224, 224))
    img_array = image.img_to_array(img)
    img_array = np.expand_dims(img_array, axis=0)  # 添加batch维度
    img_array /= 255.0  # 和训练时的预处理一致

    # 执行预测
    predictions = loaded_model.predict(img_array)
    # 映射类别索引到类别名称
    class_labels = {v: k for k, v in train_dataset.class_indices.items()}
    predicted_class = class_labels[np.argmax(predictions)]
    confidence = np.max(predictions)

    return predicted_class, confidence

# 使用示例(替换为你的测试图片路径)
# test_img_path = "/path/to/your/test/image.jpg"
# cls, conf = predict_single_image(test_img_path)
# print(f"预测类别:{cls},置信度:{conf:.4f}")

方案2:正确提取子模型(若需中间层输出)

如果你确实需要提取模型的中间层输出,要使用整个加载模型的input属性作为输入,而不是预训练模型的输入:

# 加载模型
model_save_path = '/content/drive/MyDrive/Machine Learning/saved_models/model_plastik.h5'
loaded_model = tf.keras.models.load_model(model_save_path)

# 先打印所有层的信息,确认目标层的名称或索引
for idx, layer in enumerate(loaded_model.layers):
    print(f"层索引 {idx}:{layer.name}")

# 假设要提取到第一个全连接层(比如名称为'dense')的输出
target_layer_name = "dense"
sub_model = tf.keras.models.Model(
    inputs=loaded_model.input,
    outputs=loaded_model.get_layer(target_layer_name).output
)

# 测试子模型(获取中间层输出)
# test_img_path = "/path/to/your/test/image.jpg"
# img = image.load_img(test_img_path, target_size=(224, 224))
# img_array = image.img_to_array(img)
# img_array = np.expand_dims(img_array, axis=0) / 255.0
# intermediate_output = sub_model.predict(img_array)
# print(f"中间层输出形状:{intermediate_output.shape}")

关键说明

原代码中loaded_model.layers[0]是MobileNetV2预训练模型,它本身是一个独立的Functional模型,直接使用它的input作为新模型的输入会触发Keras内部的张量解析错误,导致输入数量不匹配。而loaded_model.input指向的是整个训练模型的原始输入(形状为(224, 224, 3)的图像张量),能保证输入输出的一致性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 23:05:05