<jupyter_start><jupyter_text>Preparing Dataset<jupyter_code># Specify paths to the training and validation dataset directories

BATCH_SIZE = 32
TARGET_SIZE = (224, 224)

data_generator = ImageDataGenerator(rescale=1./255, validation_split=0.2)
# Generate batches of tensor image data for training

train_data_generator = data_generator.flow_from_directory(dataset_dir,
                                                               target_size = TARGET_SIZE,
                                                               batch_size = BATCH_SIZE,
                                                               class_mode = "categorical",
                                                               shuffle = False,
                                                               subset = "training")

# Generate batches of tensor image data for validation
validation_data_generator = data_generator.flow_from_directory(dataset_dir,
                                                               target_size = TARGET_SIZE,
                                                               batch_size = BATCH_SIZE,
                                                               class_mode = "categorical",
                                                               shuffle = False,
                                                               subset = "validation")

nb_train_samples = train_data_generator.samples
nb_validation_samples = validation_data_generator.samples
class_labels = train_data_generator.class_indices
print(class_labels)
sample_training_images, labels = next(train_data_generator)

def plot_images(images_arr, labels):
    fig, axes = plt.subplots(4, 4 , figsize=(10,10))
    axes = axes.flatten()
    for img, lbs, ax in zip(images_arr, labels, axes):
        ax.imshow(img)
        ax.set_title(lbs)
        ax.axis("off")
    plt.tight_layout
    plt.show()

plot_images(sample_training_images[:16], labels[:16])<jupyter_output>C:\Users\Fabio\anaconda3\lib\site-packages\matplotlib\text.py:1163: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison
  if s != self._text:<jupyter_text>Architecture<jupyter_code>from tensorflow.keras.applications.mobilenet_v2 import MobileNetV2

input_shape = (TARGET_SIZE[0], TARGET_SIZE[1], 3)

pretrained_model = MobileNetV2(input_shape = input_shape, weights = 'imagenet', include_top = False)
pretrained_model.trainable = False

model = Sequential()

model.add(pretrained_model)

model.add(Flatten())
model.add(Dense(128))
model.add(Activation('relu'))
model.add(Dropout(0.3))
model.add(Dense(2))
model.add(Activation('softmax'))

model.summary()
# Define early stopping and model checkpoint for optimizing epoch number and saving the best model

from tensorflow.keras.callbacks import EarlyStopping
from tensorflow.keras.callbacks import ModelCheckpoint

es = EarlyStopping(monitor="val_loss", mode='min', verbose = 1, patience = 20)

mc = ModelCheckpoint(model_dir + model_name, monitor = 'val_accuracy', mode = 'max', verbose = 1,
                    save_best_only = True)
# Compile and fit your model

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

epochs = 20

history = model.fit(train_data_generator,
                             steps_per_epoch = train_data_generator.samples/train_data_generator.batch_size,
                             epochs = epochs,
                             validation_data = validation_data_generator,
                             validation_steps = validation_data_generator.samples/validation_data_generator.batch_size,
                             callbacks =[es, mc])<jupyter_output><empty_output><jupyter_text>Evaluation<jupyter_code># Plot accuracy and loss for testing and validation

acc = history.history['accuracy']
val_acc = history.history['val_accuracy']

loss = history.history['loss']
val_loss = history.history['val_loss']

plt.figure(figsize=(12, 4))
plt.subplot(1, 2, 1)
plt.plot(acc, label='Training Accuracy')
plt.plot(val_acc, label='Validation Accuracy')
plt.legend(loc='lower right')
plt.ylabel('Accuracy Value')
plt.xlabel('Epoch')
plt.title('Training and Validation Accuracy')

plt.subplot(1, 2, 2)
plt.plot(loss, label='Training Loss')
plt.plot(val_loss, label='Validation Loss')
plt.legend(loc='upper right')
plt.ylabel('Loss Value')
plt.xlabel('Epoch')
plt.title('Training and Validation Loss')
plt.show()
# Lê o melhor modelo salvo
from tensorflow.keras.models import load_model

# Load the best saved model
model = load_model(model_dir + model_name)
from sklearn.metrics import classification_report, confusion_matrix
Y_pred = model.predict(validation_data_generator, nb_validation_samples // BATCH_SIZE+1)
y_pred = np.argmax(Y_pred, axis=1)

print('Confusion Matrix \n')
print(confusion_matrix(validation_data_generator.classes, y_pred))
print('\n')
print('Classification Report \n')
target_names = ['with_mask', 'without_mask']
print(classification_report(validation_data_generator.classes, y_pred, target_names=target_names))<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.09356038363671952, 'fraction_numerical': 0.011352515169309062, 'mean_word_length': 2.882978723404255, 'pattern_counts': {'":': 0, '<': 12, '<?xml version=': 0, '>': 12, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 20, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '3', 'dir': 'jupyter-structured-clean-dedup', 'id': '653583', 'license': 'MIT', 'n_tokens_mistral': 1483, 'n_tokens_neox': 1402, 'n_words': 304, 'path': 'Train-and-Evaluation_Face-Mask-Detector.ipynb', 'repo_name': 'LuizAlencar17/face-mask-detector', 'size': '5109'}