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

加载Keras模型报错:dense层预期1个输入却收到2个,求解决方法

问题解决:加载模型时出现"dense层期望1个输入但收到2个"的错误

错误原因分析

你加载的new_mobilenet_model.h5模型结构中,dense分类层仅接受1个输入张量,但实际传入了2个,这通常是因为模型训练时采用了多分支输入结构(比如自定义的特征融合MobileNet变体),但推理阶段你只传入了单张图片的输入,导致输入不匹配。

修改后的完整代码

import cv2
import numpy as np
import tensorflow as tf
from tensorflow.keras.preprocessing import image

CLASS_MAP = {
    0: 'rock',
    1: 'paper',
    2: 'scissor'
}

# 加载模型并调整输入适配
try:
    base_model = tf.keras.models.load_model(r'D:\practice_CV22\new_mobilenet_model.h5')
    # 打印模型结构,方便调试输入输出(可后续删除)
    base_model.summary()
    
    # 方案1:创建单输入适配模型(推荐)
    # 假设模型的双输入是冗余设计,取第一个输入映射到原始模型输出
    model = tf.keras.Model(inputs=base_model.input[0], outputs=base_model.output)

except Exception as e:
    print(f"Error loading model: {str(e)}")
    exit()

def detection_fn(image_batch):
    predictions = model.predict_on_batch(image_batch).flatten()
    class_id = np.argmax(predictions)
    label = CLASS_MAP[class_id]
    confidence = predictions[class_id]
    return label, confidence

def preprocess_frame(frame, img_size=224):
    frame = cv2.resize(frame, (img_size, img_size))
    frame = image.img_to_array(frame)
    frame = np.expand_dims(frame, axis=0)
    frame = frame / 255.0
    return frame

# 初始化摄像头
cap = cv2.VideoCapture(0)

if not cap.isOpened():
    print("Error: Could not open webcam.")
    exit()

while cap.isOpened():
    ret, frame = cap.read()
    if not ret:
        break

    processed_frame = preprocess_frame(frame)
    label, confidence = detection_fn(processed_frame)
    
    cv2.putText(frame, f"{label}: {confidence:.2f}", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
    cv2.imshow('Webcam Object Detection', frame)
    
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

备选方案(若方案1无效)

如果模型确实需要双输入才能运行,可修改detection_fn函数,将预处理后的输入复制一份作为第二个输入传入:

def detection_fn(image_batch):
    # 复制输入张量以匹配模型的双输入要求
    predictions = model.predict_on_batch([image_batch, image_batch]).flatten()
    class_id = np.argmax(predictions)
    label = CLASS_MAP[class_id]
    confidence = predictions[class_id]
    return label, confidence

额外注意事项

  • Windows路径建议用原始字符串r'路径'或双反斜杠\\,避免转义字符解析错误;
  • 运行代码时先查看base_model.summary()的输出,确认模型的输入数量和结构,能更精准地调整适配逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 00:07:21