[Python] Arguments `target` and `output` must have the same rank (ndim). Received:...

Discussão em 'Python' iniciado por Stack, Abril 13, 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 Traceback (most recent call last)
    <ipython-input-100-98095d26e04d> in <cell line: 0>()
    1 # Train the model
    ----> 2 history = model.fit(training, batch_size=batch_size, epochs=epoch,validation_data=testing)

    1 frames
    /usr/local/lib/python3.11/dist-packages/keras/src/backend/tensorflow/nn.py in categorical_crossentropy(target, output, from_logits, axis)
    651 )
    652 if len(target.shape) != len(output.shape):
    --> 653 raise ValueError(
    654 "Arguments `target` and `output` must have the same rank "
    655 "(ndim). Received: "

    ValueError: Arguments `target` and `output` must have the same rank (ndim). Received: target.shape=(None,), output.shape=(None, 9)


    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 google.colab import drive
    from google.colab.patches import cv2_imshow
    drive.mount('/content/drive')


    img_height = 180
    img_width = 180
    batch_size = 32
    epoch = 20


    normalization_layer = tf.keras.layers.Rescaling(1./255)
    normalized_ds = training.map(lambda x, y: (normalization_layer(x), y))
    image_batch, labels_batch = next(iter(normalized_ds))
    first_image = image_batch[0]
    print(np.min(first_image), np.max(first_image))


    AUTOTUNE = tf.data.AUTOTUNE

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


    from tensorflow.keras.models import Sequential
    from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense
    from tensorflow.keras.utils import to_categorical

    num_classes = 9

    model = Sequential([
    Conv2D(32, (3, 3), activation='relu'),
    MaxPooling2D(2, 2),
    Conv2D(64, (3, 3), activation='relu'),
    MaxPooling2D(2, 2),
    Conv2D(128, (3, 3), activation='relu'),
    MaxPooling2D(2, 2),
    Flatten(),
    Dense(256, activation='relu'),
    Dense(num_classes, activation='softmax')
    ])
    model.build(input_shape=(batch_size, img_height, img_width, 3))


    # Compilação do modelo
    model.compile(optimizer='adam',
    loss='categorical_crossentropy',
    metrics=['accuracy'])



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


    The Training and Testing variables are prefetchdirectories created using

    tf.keras.utils.image_dataset_from_directory


    How do I fix this error.

    Continue reading...

Compartilhe esta Página