[Python] How to make a multi-label machine model training model?

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

  1. Stack

    Stack Membro Participativo

    I'm currently trying with tensorflor and keras with python my machine learning model, but I don't understand much of machine learning and I'm trying to improve my code to be more accurate on the readings.

    I have 42 classes with each one with 121 images, but I don't know how to make it more accurate.

    This is my code:

    import tensorflow as tf
    from tensorflow.keras import layers, models

    BATCH_SIZE = 4
    IMG_SIZE = (500, 500)
    DATASET_PATH = r"img"

    train_ds = tf.keras.utils.image_dataset_from_directory(
    DATASET_PATH,
    validation_split=0.2,
    subset="training",
    seed=123,
    image_size=IMG_SIZE,
    batch_size=BATCH_SIZE
    )

    val_ds = tf.keras.utils.image_dataset_from_directory(
    DATASET_PATH,
    validation_split=0.2,
    subset="validation",
    seed=123,
    image_size=IMG_SIZE,
    batch_size=BATCH_SIZE
    )

    class_names = train_ds.class_names
    print("Classes encontradas:", class_names)

    data_augmentation = models.Sequential([
    layers.RandomFlip("horizontal_and_vertical"),
    layers.RandomRotation(0.2),
    layers.RandomZoom(0.2),
    layers.RandomBrightness(0.2)
    ])

    train_ds = train_ds.map(lambda x, y: (data_augmentation(x), y))

    normalization_layer = layers.Rescaling(1. / 255)
    train_ds = train_ds.map(lambda x, y: (normalization_layer(x), y))
    val_ds = val_ds.map(lambda x, y: (normalization_layer(x), y))

    base_model = tf.keras.applications.MobileNetV2(
    input_shape=IMG_SIZE + (3,),
    include_top=False,
    weights='imagenet'
    )

    base_model.trainable = False

    for layer in base_model.layers[-20:]:
    layer.trainable = True

    global_average_layer = layers.GlobalAveragePooling2D()
    output_layer = layers.Dense(len(class_names), activation='softmax')

    model = models.Sequential([
    base_model,
    layers.GlobalAveragePooling2D(),
    layers.Dropout(0.5),
    layers.Dense(len(class_names), activation='softmax')
    ])

    lr_schedule = tf.keras.optimizers.schedules.ExponentialDecay(
    initial_learning_rate=0.001,
    decay_steps=1000,
    decay_rate=0.9
    )

    model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=1e-5),
    loss=tf.keras.losses.SparseCategoricalCrossentropy(),
    metrics=['accuracy'])

    early_stopping = tf.keras.callbacks.EarlyStopping(
    monitor='val_loss',
    patience=10,
    restore_best_weights=True
    )

    history = model.fit(train_ds, validation_data=val_ds, epochs=100, callbacks=[early_stopping])

    model.save("image_recognition_model.keras")


    If possible I just want want some tips to improve it.

    The images in the database are taken in the same angle and background with various positions of the object, I'm making something wrong?

    Continue reading...

Compartilhe esta Página