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

# ## Image Preperation

# #### Data set: https://github.com/ardamavi/Sign-Language-Digits-Dataset

import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Activation, Dense, Flatten, BatchNormalization, Conv2D, MaxPool2D
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.metrics import categorical_crossentropy
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from sklearn.metrics import confusion_matrix
import itertools
import os
import shutil
import random
import matplotlib.pyplot as plt
# %matplotlib inline

pwd # To show current Jupyter notebook directory

train_path = 'Sign-Language-Digits-Dataset/train'
valid_path = 'Sign-Language-Digits-Dataset/valid'
test_path = 'Sign-Language-Digits-Dataset/test'

train_batches = ImageDataGenerator(preprocessing_function = keras.applications.mobilenet.preprocess_input).flow_from_directory(
    train_path, target_size = (224, 224), batch_size = 10)
valid_batches = ImageDataGenerator(preprocessing_function = keras.applications.mobilenet.preprocess_input).flow_from_directory(
    valid_path, target_size = (224, 224), batch_size = 10)
test_batches = ImageDataGenerator(preprocessing_function = keras.applications.mobilenet.preprocess_input).flow_from_directory(
    test_path, target_size = (224, 224), batch_size = 10, shuffle = False)

# ## Modify Model

mobile = keras.applications.mobilenet.MobileNet()

mobile.summary()

x = mobile.layers[-6].output
predictions = Dense(10, activation = 'softmax')(x)

model = keras.Model(inputs = mobile.input, outputs = predictions)

model.summary()

for layer in model.layers[:23]:
    layer.trainable = False

# ## Training Model

model.compile(Adam(learning_rate = 0.0001), loss = 'categorical_crossentropy', metrics = ['accuracy'])

model.fit_generator(train_batches, steps_per_epoch = 18, validation_data = valid_batches, validation_steps = 3, epochs = 60, verbose = 2)

# ## Predict Sign Language Digits

test_labels = test_batches.classes

predictions = model.predict(test_batches, steps = 5, verbose = 0)


# This function has been taken from the website of scikit Learn. link: https://scikit-learn.org/0.18/auto_examples/model_selection/plot_confusion_matrix.html
def plot_confusion_matrix(cm, classes,
                          normalize=False,
                          title='Confusion matrix',
                          cmap=plt.cm.Blues):
    """
    This function prints and plots the confusion matrix.
    Normalization can be applied by setting `normalize=True`.
    """
    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(classes))
    plt.xticks(tick_marks, classes, rotation=45)
    plt.yticks(tick_marks, classes)

    if normalize:
        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
        print("Normalized confusion matrix")
    else:
        print('Confusion matrix, without normalization')

    print(cm)

    thresh = cm.max() / 2.
    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
        plt.text(j, i, cm[i, j],
                 horizontalalignment="center",
                 color="white" if cm[i, j] > thresh else "black")

    plt.tight_layout()
    plt.ylabel('True label')
    plt.xlabel('Predicted label')


cm = confusion_matrix(test_labels, predictions.argmax(axis = 1))

test_batches.class_indices

cm_plot_labels = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
plot_confusion_matrix(cm, cm_plot_labels, title = 'Confusion Matrix')



StarcoderdataJupyterScriptsDedupFiltered