estoy programando una cnn que clasifique imágenes entre naranjas y manzanas, pero al llegar a la parte del entrenamiento de
ValueError: logits and labels must have the same shape ((None, 2) vs (None, 1))
Mi arbol de carpetas es el siguiente:
frutas -> train (manzanas, naranjas) - validation (manzanas, naranjas) - test (manzanas, naranjas)
y mi código es el siguiente:
import os
import zipfile
import math
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import tensorflow as tf
from google.colab import files
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, BatchNormalization, Dropout
from tensorflow.keras.optimizers import Adam, SGD, RMSprop
from tensorflow.keras.preprocessing.image import ImageDataGenerator
print('GPU available:', tf.config.list_physical_devices('GPU'))
print('tensorflow version:',tf.__version__)
print('keras version:', tf.keras.__version__)
zip_location = '/content/drive/MyDrive/IA/datasets/frutas.zip'
zip_ref = zipfile.ZipFile(zip_location, 'r')
zip_ref.extractall('/tmp')
zip_ref.close()
base_dir = '/tmp/frutas'
train_dir = os.path.join(base_dir, 'train')
validation_dir = os.path.join(base_dir, 'validation')
test_dir = os.path.join(base_dir, 'test')
apple_train_dir = os.path.join(train_dir, 'manzanas')
apple_test_dir = os.path.join(test_dir, 'manzanas')
apple_validation_dir = os.path.join(validation_dir, 'manzanas')
orange_train_dir = os.path.join(train_dir, 'naranjas')
orange_test_dir = os.path.join(test_dir, 'naranjas')
orange_validation_dir = os.path.join(validation_dir, 'naranjas')
print('Apple train images:', len(os.listdir(apple_train_dir)))
print('Apple validation images:', len(os.listdir(apple_validation_dir)))
print('Apple test images:', len(os.listdir(apple_test_dir)))
print()
print('Orange train images:', len(os.listdir(orange_train_dir)))
print('Orange validation images:', len(os.listdir(orange_validation_dir)))
print('Orange test images:', len(os.listdir(orange_test_dir)))
def print_images(dir, fnames):
num_rows = 4
num_cols = 4
img_index = 0
fig = plt.gcf()
fig.set_size_inches(num_cols * 4, num_rows * 4)
img_index += 8
next_pixel = [os.path.join(dir, fname) for fname in fnames[img_index-8:img_index]]
for i, img_path in enumerate(next_pixel):
sp = plt.subplot(num_rows, num_cols, i + 1)
img = mpimg.imread(img_path)
plt.imshow(img)
print(img.shape)
plt.show()
print('train manzanas')
print_images(apple_train_dir, os.listdir(apple_train_dir))
print('validation manzanas')
print_images(apple_validation_dir, os.listdir(apple_validation_dir))
print('test manzanas')
print_images(apple_test_dir, os.listdir(apple_test_dir))
print('train naranjas')
print_images(orange_train_dir, os.listdir(orange_train_dir))
print('validation naranjas')
print_images(orange_validation_dir, os.listdir(orange_validation_dir))
print('test naranjas')
print_images(orange_test_dir, os.listdir(orange_test_dir))
train_datagen = ImageDataGenerator(rescale = 1.0 / 255.)
validation_datagen = ImageDataGenerator(rescale = 1.0 / 255.)
test_datagen = ImageDataGenerator(rescale = 1.0 / 255.)
train_generator = train_datagen.flow_from_directory(train_dir, batch_size = 20, class_mode = 'binary', target_size = (150, 150))
validation_generator = validation_datagen.flow_from_directory(validation_dir, batch_size = 20, class_mode = 'binary', target_size = (150, 150))
test_generator = test_datagen.flow_from_directory(test_dir, batch_size = 20, class_mode = 'binary', target_size = (150, 150))
train_generator.class_indices, validation_generator.class_indices, test_generator.class_indices
def create_model():
model = Sequential()
model.add(Conv2D(32, (3, 3), activation = 'relu', input_shape = (150, 150, 3)))
model.add(MaxPooling2D((2, 2)))
model.add(Conv2D(64, (3, 3), activation = 'relu'))
model.add(MaxPooling2D((2, 2)))
model.add(Conv2D(128, (3, 3), activation = 'relu'))
model.add(MaxPooling2D((2, 2)))
model.add(Flatten())
model.add(Dense(512, activation = 'relu'))
model.add(Dense(2, activation = 'sigmoid'))
return model
model = create_model()
model.summary()
my_optimizer = RMSprop(learning_rate = 1e-4)
model.compile(loss = 'binary_crossentropy', optimizer = my_optimizer, metrics = ['acc'])
EPOCHS = 100
batch_size = 20
steps_per_epoch = math.floor(train_generator.n / batch_size)
validation_steps = math.floor(validation_generator.n / batch_size)
history = model.fit(train_generator, epochs = EPOCHS, validation_data = validation_generator, verbose = 1)
history_dict = history.history
print(history_dict.keys())
accuracy = history_dict['acc']
val_accuracy = history_dict['val_acc']
loss = history_dict['loss']
val_loss = history_dict['val_loss']
epochs = range(1, len(accuracy) + 1, 1)
plt.plot(epochs, accuracy, 'r--', label = 'Training accuracy')
plt.plot(epochs, val_accuracy, 'b', label = 'Validation accuracy')
plt.title('Training and validation accuracy')
plt.xlabel('epochs')
plt.ylabel('accuracy')
plt.ylim(0, 1)
plt.legend()
plt.figure()
plt.plot(epochs, loss, 'r--', label = 'Training loss')
plt.plot(epochs, val_loss, 'b', label = 'Validation loss')
plt.title('Training and validation loss')
plt.xlabel('epochs')
plt.ylabel('loss')
plt.ylim(0, 1)
plt.legend()
plt.figure()
test_loss, test_acc = model.evaluate(test_generator)
print('Test accuracy:', test_acc)
me falla en la parte donde defino history, para ejecutar el model.fit(), y el error que me da es el siguiente: ValueError: logits and labels must have the same shape ((None, 2) vs (None, 1))
no logro encontrar que puede ser, ¿Alguien sabe en que puedo estar fallando? Muchas gracias