ValueError: Input 0 of layer "sequential_30" is incompatible with the layer: expected shape=(None, 800, 1400, 1), found shape=(32, 1400, 1)

Hey Tensorflow community!
I am encountering an issue while training a convolutional neural network (CNN) using TensorFlow. The specific error is a value error related to downsampling in the Conv2D layer. The model architecture includes Conv2D layers with MaxPooling2D layers, and the input shape is (800, 1400, 1). Despite setting up the input shape, the error suggests an issue during downsampling, and I’m unable to identify the root cause.
here is my code :

import spectral
import matplotlib.pyplot as plt
import numpy as np
from sklearn.model_selection import train_test_split
from tensorflow.keras import layers, models

def lire_base_apprentissage(nom_fichier):
with open(nom_fichier, ‘r’) as fichier:
lignes = fichier.readlines()

base_apprentissage = []
for ligne in lignes:
    if not ligne.startswith(';'):
        point = list(map(int, ligne.strip().split()))

return base_apprentissage

def prepare_data(envi_img, base_apprentissage):
input_image = np.asarray(envi_img.load()).astype(‘float32’) / 255.0
target_mask = np.zeros_like(input_image[:, :, 0], dtype=int)

for point in base_apprentissage[:9682]:
    target_mask[point[2], point[1]] = 1  # Region #1

for point in base_apprentissage[9682+1:]:
    target_mask[point[2], point[1]] = 2  # Region #2

return input_image, target_mask

def create_cnn_model(input_shape):
model = models.Sequential([
layers.Conv2D(32, (3, 3), activation=‘relu’, input_shape=input_shape ,padding=‘same’),
layers.MaxPooling2D((2, 2)),
layers.Dense(64, activation=‘relu’),
layers.Dense(2, activation=‘softmax’) # Output layer for three classes (background, Region #1, Region #2)

model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
return model

Charger et prétraiter votre image ENVI

envi_header_path = ‘C:chemin/ima-nap1.hdr’
envi_img = spectral.open_image(envi_header_path)

Lire la base d’apprentissage depuis le fichier

nom_fichier_base_apprentissage = ‘C:chemin/Base apprentissage-ASCII.txt’
base_apprentissage = lire_base_apprentissage(nom_fichier_base_apprentissage)

Préparer les données pour l’entraînement

input_image, target_mask = prepare_data(envi_img, base_apprentissage)

Diviser les données en ensembles d’entraînement et de test

X_train, X_test, y_train, y_test = train_test_split(input_image, target_mask, test_size=0.2, random_state=42)

Avant d’ajuster la forme, assurez-vous que X_train a la forme correcte

X_train.shape devrait être (nombre_d’échantillons, 800, 1400, 1)

Créer le modèle CNN

input_shape = (800, 1400, 1) # Adjust this based on your actual image dimensions and number of bands
model = create_cnn_model(input_shape)

Entraîner le modèle, y_train, epochs=10, batch_size=32, validation_split=0.2)

Évaluer le modèle sur l’ensemble de test

test_loss, test_accuracy = model.evaluate(X_test, y_test)
print(f’Test Accuracy: {test_accuracy * 100:.2f}%')

Faire des prédictions sur l’image d’entrée

predictions = model.predict(input_image.reshape((1,) + input_image.shape))

Sélectionner la classe prédite pour chaque pixel

predicted_mask = np.argmax(predictions, axis=-1)

Visualiser les résultats

plt.figure(figsize=(12, 6))

plt.subplot(1, 3, 1)
plt.imshow(input_image[:, :, 0], cmap=‘gray’) # Display the first channel of the input image
plt.title(‘Original Image’)

plt.subplot(1, 3, 2)
plt.imshow(target_mask, cmap=‘viridis’) # Adjust colormap based on the number of classes
plt.title(‘Ground Truth Mask’)

plt.subplot(1, 3, 3)
plt.imshow(predicted_mask, cmap=‘viridis’) # Adjust colormap based on the number of classes
plt.title(‘Predicted Mask’)

Hi @ISSAAD_Yasser, I guess the error did not occur due to the down sampling of conv2D layer, the X_train shape may not match with the input defined shape. Could you please verify Whether the input shape matches with the training data shape. Thank You.