<jupyter_start><jupyter_text>Dataset Link: https://www.kaggle.com/omkargurav/face-mask-dataset<jupyter_code>import os
import numpy as np
from tensorflow.keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D
from sklearn.model_selection import train_test_split
import seaborn as sns
import matplotlib.pyplot as plt
from keras.preprocessing.image import ImageDataGenerator
import warnings
warnings.filterwarnings("ignore")
import cv2<jupyter_output><empty_output><jupyter_text>Loading Images<jupyter_code>path = "YUZ"

myList = os.listdir(path)
noOfClasses = len(myList)

print("Label(sınıf) Sayısı", noOfClasses)<jupyter_output>Label(sınıf) Sayısı 2<jupyter_text>Resizing images as (32,32) for Model Requirement<jupyter_code>images = []
classNo = []

for i in range(noOfClasses):
    myImageList = os.listdir(path + "\\"+str(i))
    for j in myImageList:
        img = cv2.imread(path + "\\"+str(i)+"\\"+j)
        img = cv2.resize(img,(128,128))
        images.append(img)
        classNo.append(i)
        
print(len(images))
print(len(classNo))<jupyter_output>7553
7553<jupyter_text>Converting Images to Array<jupyter_code>images = np.array(images)
classNo = np.array(classNo)

print(images.shape)<jupyter_output>(7553, 128, 128, 3)<jupyter_text>Splitting Data (%80 Train, %20 Validation)<jupyter_code>#Veriyi Ayırma
x_train, x_validation, y_train, y_validation = train_test_split(images,classNo,test_size = 0.2, random_state = 42)

print(images.shape)
print(x_train.shape)
print(x_validation.shape)<jupyter_output>(7553, 128, 128, 3)
(6042, 128, 128, 3)
(1511, 128, 128, 3)<jupyter_text>Preprocess<jupyter_code>def preProcess(img):
    img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    img = cv2.equalizeHist(img)
    img = img / 255
    
    return img

x_train = np.array(list(map(preProcess, x_train)))
x_validation = np.array(list(map(preProcess,x_validation)))

x_train = x_train.reshape(-1,128,128,1)
x_validation = x_validation.reshape(-1,128,128,1)<jupyter_output><empty_output><jupyter_text>Data Generate<jupyter_code>image_gen = ImageDataGenerator(rotation_range = 20,
                               width_shift_range = 0.1,
                               height_shift_range = 0.1,
                               shear_range = 0.1,
                               zoom_range = 0.1,
                               horizontal_flip = True,
                               fill_mode = "nearest")

image_gen.fit(x_train)<jupyter_output><empty_output><jupyter_text>Creating Model<jupyter_code>model = Sequential()

model.add(Conv2D(filters=32, kernel_size= (4,4), input_shape = (128,128,1), activation= "relu"))
model.add(MaxPool2D(pool_size=(2,2)))

model.add(Conv2D(filters=32, kernel_size= (4,4), input_shape = (128,128,1), activation= "relu"))
model.add(MaxPool2D(pool_size=(2,2)))

model.add(Conv2D(filters=32, kernel_size= (4,4), input_shape = (128,128,1), activation= "relu"))
model.add(MaxPool2D(pool_size=(2,2)))

model.add(Flatten())

model.add(Dense(128,activation="relu"))
model.add(Dropout(0.5))

model.add(Dense(1,activation="sigmoid")) 

model.compile(loss = "binary_crossentropy", optimizer ="adam",
              metrics = ["accuracy"])
from tensorflow.keras.callbacks import EarlyStopping 
early_stop = EarlyStopping(monitor = "val_loss",patience=2)

model.fit(x_train,y_train,epochs=10,validation_data = (x_validation,y_validation),callbacks = [early_stop])<jupyter_output>Epoch 1/10
189/189 [==============================] - 66s 346ms/step - loss: 0.6050 - accuracy: 0.6592 - val_loss: 0.5150 - val_accuracy: 0.7498
Epoch 2/10
189/189 [==============================] - 67s 354ms/step - loss: 0.4362 - accuracy: 0.7953 - val_loss: 0.3913 - val_accuracy: 0.8226
Epoch 3/10
189/189 [==============================] - 73s 386ms/step - loss: 0.3426 - accuracy: 0.8461 - val_loss: 0.3289 - val_accuracy: 0.8498
Epoch 4/10
189/189 [==============================] - 69s 363ms/step - loss: 0.2830 - accuracy: 0.8777 - val_loss: 0.3021 - val_accuracy: 0.8743
Epoch 5/10
189/189 [==============================] - 67s 352ms/step - loss: 0.2208 - accuracy: 0.9042 - val_loss: 0.2810 - val_accuracy: 0.8829
Epoch 6/10
189/189 [==============================] - 72s 382ms/step - loss: 0.1823 - accuracy: 0.9239 - val_loss: 0.2769 - val_accuracy: 0.8848
Epoch 7/10
189/189 [==============================] - 69s 366ms/step - loss: 0.1439 - accuracy: 0.9434 - val_loss: 0.2881 - val_ac[...]<jupyter_text>Saving Model<jupyter_code>import pandas as pd
model.save("modelfolder/")
model.save_weights("modelfolder/")
metrics = model.history.history
metrics = pd.DataFrame(model.history.history)
metrics<jupyter_output><empty_output><jupyter_text>Loss and Accuracy Graphics<jupyter_code>plt.figure()
plt.plot(metrics["loss"], label = "Train Loss")
plt.plot(metrics["val_loss"], label = "Validation Loss")
plt.legend()
plt.show()
plt.figure()
plt.plot(metrics["accuracy"], label = "Train Accuracy")
plt.plot(metrics["val_accuracy"], label = "Validation Accuracy")
plt.legend()
plt.show()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.17752764612954186, 'fraction_numerical': 0.07819905213270142, 'mean_word_length': 4.80848623853211, 'pattern_counts': {'":': 0, '<': 36, '<?xml version=': 0, '>': 36, 'https://': 1, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '10', 'dir': 'jupyter-structured-clean-dedup', 'id': '333368', 'license': 'Apache-2.0', 'n_tokens_mistral': 2145, 'n_tokens_neox': 1843, 'n_words': 323, 'path': 'Source Code/Model Create Part.ipynb', 'repo_name': 'AkifCanSonmez/Face_Mask_Detection', 'size': '5064'}