# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# ## Dataset Link: https://www.kaggle.com/omkargurav/face-mask-dataset

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

# ## Loading Images

# +
path = "YUZ"

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

print("Label(sınıf) Sayısı", noOfClasses)
# -

# ## Resizing images as (32,32) for Model Requirement

# +
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))
# -

# ## Converting Images to Array
#

# +
images = np.array(images)
classNo = np.array(classNo)

print(images.shape)
# -

# ##  Splitting Data (%80 Train, %20 Validation)

# +
#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)


# -

# ## Preprocess

# +
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)


# -

# ## Data Generate

# +
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)

# -

# ## Creating Model

# +
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])
# -

# ## Saving Model

import pandas as pd

model.save("modelfolder/")
model.save_weights("modelfolder/")

metrics = model.history.history

metrics = pd.DataFrame(model.history.history)
metrics

# ##  Loss and Accuracy Graphics

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()

StarcoderdataJupyterScriptsDedupFiltered