[Python] Tensorflow gives error when predicting: expected axis -1 of input shape to have value...

Discussão em 'Python' iniciado por Stack, Abril 11, 2025.

  1. Stack

    Stack Membro Participativo

    I have been trying to create a neural network that can identify images, but When I go and try to fit my model, I get the following error:

    ValueError: Exception encountered when calling Sequential.call().
    Input 0 of layer "dense_82" is incompatible with the layer: expected axis -1
    of input shape to have value 2304, but received input with shape (None, 118336)


    I am building it on Collab and the code I am using is the following:

    import numpy as np
    import matplotlib.pyplot as plt
    import tensorflow as tf
    from tensorflow.keras.models import Sequential
    from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense
    from tensorflow.keras.utils import to_categorical

    from google.colab import drive
    from google.colab.patches import cv2_imshow
    drive.mount('/content/drive')


    img_height = 180
    img_width = 180

    normalization_layer = tf.keras.layers.Rescaling(1./255)
    normalized_ds = training.map(lambda x, y: (normalization_layer(x), y))

    AUTOTUNE = tf.data.AUTOTUNE

    training = training.cache().prefetch(buffer_size=AUTOTUNE)
    testing = testing.cache().prefetch(buffer_size=AUTOTUNE)

    num_classes = 9

    model = Sequential([
    Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)),
    MaxPooling2D(2, 2),
    Conv2D(64, (3, 3), activation='relu'),
    MaxPooling2D(2, 2),
    Flatten(),
    Dense(128, activation='relu'),
    Dense(num_classes, activation='softmax')
    ])

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

    model.summary()

    history = model.fit(training, batch_size=64, epochs=20,validation_data=testing)


    The Training and Testing variables are prefetchdirectories created using

    tf.keras.utils.image_dataset_from_directory


    How to fix this error.

    Continue reading...

Compartilhe esta Página