text_plain_output_1.png image_output_1.png
from keras import layers

from keras import models

from keras.applications import VGG16

from sklearn.model_selection import train_test_split

import cv2

import keras

import matplotlib.pyplot as plt

import numpy as np

import numpy as np # linear algebra

import os

import os

import numpy as np
import pandas as pd
import os

import numpy as np
import pandas as pd
import os
import keras
from keras.layers import Conv2D, MaxPool2D, Flatten, Dense, Dropout, BatchNormalization
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras import regularizers
from sklearn.model_selection import train_test_split
import cv2
import matplotlib.pyplot as plt
import seaborn as sns
from keras.applications import VGG16
from keras import models
from keras import layers
from keras import optimizers

os.listdir('../input/isl-dataset-double-handed')

train_dir = '../input/isl-dataset-double-handed/ISL_Dataset'

def load_unique():
    size_img = 224,224 
    images_for_plot = []
    labels_for_plot = []
    for folder in os.listdir(train_dir):
        for file in os.listdir(train_dir + '/' + folder):
            filepath = train_dir + '/' + folder + '/' + file
            image = cv2.imread(filepath)
            final_img = cv2.resize(image, size_img)
            final_img = cv2.cvtColor(final_img, cv2.COLOR_BGR2RGB)
            images_for_plot.append(final_img)
            labels_for_plot.append(folder)
            break
    return images_for_plot, labels_for_plot

images_for_plot, labels_for_plot = load_unique()
print("unique_labels = ", labels_for_plot)

fig = plt.figure(figsize = (15,15))
def plot_images(fig, image, label, row, col, index):
    fig.add_subplot(row, col, index)
    plt.axis('off')
    plt.imshow(image)
    plt.title(label)
    return

image_index = 0
row = 4
col = 6
for i in range(1,25):
    plot_images(fig, images_for_plot[image_index], labels_for_plot[image_index], row, col, i)
    image_index = image_index + 1
plt.show()

l1 = []
def load_data():
    """
    Loads data and preprocess. Returns train and test data along with labels.
    """
    images = []
    labels = []
    size = (224, 224)
    for folder in os.listdir(train_dir):
        for image in os.listdir(train_dir + '/' + folder):
            temp_img = cv2.imread(train_dir + '/' + folder + '/' + image)
            temp_img = cv2.resize(temp_img, size)
            images.append(temp_img)
            labels.append(ord(folder) - 97)
    images = np.array(images)
    for i in range(len(images)):
        images[i] = images[i].astype('float32') / 255
    l1 = labels
    labels = keras.utils.to_categorical(labels)
    X_train, X_test, Y_train, Y_test = train_test_split(images, labels, test_size=0.25)
    return (X_train, X_test, Y_train, Y_test, l1)

def create_model1():
    vgg_conv = VGG16(weights='imagenet', include_top=False, input_shape=(224, 224, 3))
    for layer in vgg_conv.layers[:-4]:
        layer.trainable = False
    model = models.Sequential()
    model.add(vgg_conv)
    model.add(layers.Flatten())
    model.add(layers.Dense(1024, activation='relu'))
    model.add(layers.Dropout(0.5))
    model.add(layers.Dense(26, activation='softmax'))
    model.compile(optimizer='adam', loss=keras.losses.categorical_crossentropy, metrics=['accuracy'])
    model.summary()
    return model

def fit_model():
    model_hist = model.fit(X_train, Y_train, batch_size=64, epochs=8, validation_split=0.15)
    return model_hist

model = create_model1()
curr_model_hist = fit_model()

evaluate_metrics = model.evaluate(X_test, Y_test)
print('\nEvaluation Accuracy = ', '{:.2f}%'.format(evaluate_metrics[1] * 100), '\nEvaluation loss = ', '{:.6f}'.format(evaluate_metrics[0]))