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

Keras模型训练报错:sequential层预期1个输入却收到5个输入张量

Fix: ValueError: Layer sequential expects 1 inputs, but received 5 input tensors

Let's break down what's causing this error and how to fix it step by step:

First, the core issue: Incorrect use of ImageDataGenerator

You mentioned augmented_images and val_data_gen are objects from keras.preprocessing.image.ImageDataGenerator — but here's the catch: you can't pass the ImageDataGenerator instance directly to model.fit(). Instead, you need to use its flow() or flow_from_directory() methods to create an iterator that yields batches of (input data, labels) pairs. If you skip this step, the model doesn't receive the expected input structure, hence the "got 5 input tensors" error.

Fix 1: Create valid data generators

Depending on how you're loading your data, use one of these approaches:

If using numpy arrays (e.g., x_train, y_train):

# Assume you have your training data and labels defined
datagen = ImageDataGenerator(...)  # Your augmentation settings here
augmented_images = datagen.flow(x_train, y_train, batch_size=32)

# Do the same for validation data
val_datagen = ImageDataGenerator(...)  # Usually no augmentation for validation
val_data_gen = val_datagen.flow(x_val, y_val, batch_size=32)

If loading from a directory structure:

augmented_images = datagen.flow_from_directory(
    'path/to/train/dir',
    target_size=(32, 32),  # Matches your model's input_shape
    batch_size=32,
    class_mode='binary'  # Use 'binary' since you're using sigmoid for 2 classes
)

val_data_gen = val_datagen.flow_from_directory(
    'path/to/val/dir',
    target_size=(32, 32),
    batch_size=32,
    class_mode='binary'
)

Fix 2: Match your loss function to the output layer

I noticed a small mismatch here: you're using BinaryCrossentropy(from_logits=True) but your output layer has a sigmoid activation. The from_logits=True flag is meant for when your output layer doesn't have an activation function. Since you're using sigmoid, set from_logits=False (or just omit it, since False is the default):

model.compile(
    optimizer=tf.keras.optimizers.SGD(learning_rate=0.05),
    loss=tf.keras.losses.BinaryCrossentropy(from_logits=False),
    metrics=['accuracy']
)

Fix 3: Verify your generator's output format

To double-check everything's working, print a batch from your generator:

x_batch, y_batch = next(augmented_images)
print(f"Input batch shape: {x_batch.shape}")  # Should be (32, 32, 32, 3)
print(f"Label batch shape: {y_batch.shape}")  # Should be (32,) or (32, 2) depending on your setup

If this returns more than two tensors, you have an issue with your generator configuration — double-check the parameters you passed to flow()/flow_from_directory().

内容的提问来源于stack exchange,提问作者Saransh B.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 17:22:58