{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"#importing all the global libraries to process the model\nimport os\nfrom glob import glob\nimport random\nimport time\nimport tensorflow\nimport datetime\nos.environ['KERAS_BACKEND'] = 'tensorflow'\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tqdm import tqdm\nfrom IPython.display import FileLink\nimport matplotlib.pyplot as plt\nimport warnings\nwarnings.filterwarnings('ignore')\nimport seaborn as sns \n%matplotlib inline\nfrom IPython.display import display, Image\nimport matplotlib.image as mpimg\nimport cv2\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.datasets import load_files       \nfrom keras.utils import np_utils\nfrom sklearn.utils import shuffle\nfrom sklearn.metrics import log_loss\n\nfrom keras.models import Sequential, Model\nfrom keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout, BatchNormalization, GlobalAveragePooling2D\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.preprocessing import image\nfrom keras.callbacks import ModelCheckpoint, EarlyStopping\nfrom tensorflow.keras.applications import VGG16","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Importing the dataset and labels from the CSV file\n#use the classname as the labels for the images and use the image names \n#to match the labels with the correct images.\ndataset = pd.read_csv('../input/state-farm-distracted-driver-detection/driver_imgs_list.csv')\ndataset.head(5)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Import driver dataset and poppulate few variables.\nby_drivers = dataset.groupby('subject')\nunique_drivers = by_drivers.groups.keys()\nprint(unique_drivers)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"NUMBER_CLASSES = 10","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_cv2_image(path, img_rows, img_cols, color_type=3):\n    # Loading as Grayscale image\n    if color_type == 1:\n        img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)\n    elif color_type == 3:\n        img = cv2.imread(path, cv2.IMREAD_COLOR)\n    # Reduce size\n    img = cv2.resize(img, (img_rows, img_cols)) \n    return img\n\n# Load training data\ndef load_train(img_rows, img_cols, color_type=3):\n    start_time = time.time()\n    train_images = [] \n    train_labels = []\n    # Loop over the training folder \n    for classed in tqdm(range(NUMBER_CLASSES)):\n        print('Loading directory c{}'.format(classed))\n        files = glob(os.path.join('..', 'input','state-farm-distracted-driver-detection','imgs', 'train', 'c' + str(classed), '*.jpg'))\n        for file in files:\n            img = get_cv2_image(file, img_rows, img_cols, color_type)\n            train_images.append(img)\n            train_labels.append(classed)            \n    print(\"Data Loaded in {} second\".format(time.time() - start_time))\n    return train_images, train_labels \n\n# Read and normalise train and validation data set\ndef read_and_normalize_train_data(img_rows, img_cols, color_type):\n    X, labels = load_train(img_rows, img_cols, color_type)\n    #print('X value', X)\n    y = np_utils.to_categorical(labels, 10)\n    x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n    \n    x_train = np.array(x_train, dtype=np.uint8).reshape(-1,img_rows,img_cols,color_type)\n    x_test = np.array(x_test, dtype=np.uint8).reshape(-1,img_rows,img_cols,color_type)\n    \n    return x_train, x_test, y_train, y_test\n\n# Loading test data \ndef load_test(size=200000, img_rows=64, img_cols=64, color_type=3):\n    path = os.path.join('..', 'input','state-farm-distracted-driver-detection','imgs', 'test', '*.jpg')\n    files = sorted(glob(path))\n    X_test, X_test_id = [], []\n    total = 0\n    files_size = len(files)\n    for file in tqdm(files):\n        if total >= size or total >= files_size:\n            break\n        file_base = os.path.basename(file)\n        img = get_cv2_image(file, img_rows, img_cols, color_type)\n        X_test.append(img)\n        X_test_id.append(file_base)\n        total += 1\n    return X_test, X_test_id\n\n#Read and normalise test data \ndef read_and_normalize_sampled_test_data(size, img_rows, img_cols, color_type=3):\n    test_data, test_ids = load_test(size, img_rows, img_cols, color_type)\n    \n    test_data = np.array(test_data, dtype=np.uint8)\n    test_data = test_data.reshape(-1,img_rows,img_cols,color_type)\n    \n    return test_data, test_ids","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Initialising variables\nbatch_size = 40\nnb_epoch = 10\nimg_rows = 224\nimg_cols = 224\ncolor_type = 3","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Processing and initialising variables for train and validation dataset\nx_train, x_test, y_train, y_test = read_and_normalize_train_data(img_rows, img_cols, color_type)\nprint('Train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Processing and initialising variables for test dataset\nnb_test_samples = 1000\ntest_files, test_targets = read_and_normalize_sampled_test_data(nb_test_samples, img_rows, img_cols, color_type)\nprint('Test shape:', test_files.shape)\nprint(test_files.shape[0], 'Test samples')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Details and statistics of the dataset\nnames = [item[17:19] for item in sorted(glob(\"../input/state-farm-distracted-driver-detection/imgs/train/*/\"))]\ntest_files_size = len(np.array(glob(os.path.join('..', 'input','state-farm-distracted-driver-detection','imgs','test', '*.jpg'))))\nx_train_size = len(x_train)\ncategories_size = len(names)\nx_test_size = len(x_test)\nprint('There are %s total images.\\n' % (test_files_size + x_train_size + x_test_size))\nprint('There are %d training images.' % x_train_size)\nprint('There are %d total training categories.' % categories_size)\nprint('There are %d validation images.' % x_test_size)\nprint('There are %d test images.'% test_files_size)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Plot figure size\nplt.figure(figsize = (10,10))\n# Count the number of images per category\nsns.countplot(x = 'classname', data = dataset)\n# Change the Axis names\nplt.ylabel('Count')\nplt.title('Categories Distribution')\n# Show plot\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Frequency of images per driver\ndrivers_id = pd.DataFrame((dataset['subject'].value_counts()).reset_index())\ndrivers_id.columns = ['driver_id', 'Counts']\ndrivers_id","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Plotting class distribution\ndataset['class_type'] = dataset['classname'].str.extract('(\\d)',expand=False).astype(np.float)\nplt.figure(figsize = (20,20))\ndataset.hist('class_type', alpha=0.5, layout=(1,1), bins=10)\nplt.title('Class distribution')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#using a map to define the title for each image.\nactivity_map = {'c0': 'Safe driving', \n                'c1': 'Texting - right', \n                'c2': 'Talking on the phone - right', \n                'c3': 'Texting - left', \n                'c4': 'Talking on the phone - left', \n                'c5': 'Operating the radio', \n                'c6': 'Drinking', \n                'c7': 'Reaching behind', \n                'c8': 'Hair and makeup', \n                'c9': 'Talking to passenger'}","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Plotting image from each directory with description\nplt.figure(figsize = (12, 20))\nimage_count = 1\nBASE_URL = '../input/state-farm-distracted-driver-detection/imgs/train/'\nfor directory in os.listdir(BASE_URL):\n    if directory[0] != '.':\n        for i, file in enumerate(os.listdir(BASE_URL + directory)):\n            if i == 1:\n                break\n            else:\n                fig = plt.subplot(5, 2, image_count)\n                image_count += 1\n                image = mpimg.imread(BASE_URL + directory + '/' + file)\n                plt.imshow(image)\n                plt.title(activity_map[directory])                \n                ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Create a submission file for the predictions\ndef create_submission(predictions, test_id, info):\n    result = pd.DataFrame(predictions, columns=['c0', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9'])\n    result.loc[:, 'img'] = pd.Series(test_id, index=result.index)\n    \n    now = datetime.datetime.now()\n    \n    if not os.path.isdir('kaggle_submissions'):\n        os.mkdir('kaggle_submissions')\n\n    suffix = \"{}_{}\".format(info,str(now.strftime(\"%Y-%m-%d-%H-%M\")))\n    sub_file = os.path.join('kaggle_submissions', 'submission_' + suffix + '.csv')\n    \n    result.to_csv(sub_file, index=False)\n    \n    return sub_file","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"batch_size = 40\nnb_epoch = 10\nimg_rows = 224\nimg_cols = 224\ncolor_type = 3","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!rm -f saved_models/weights_best_vanilla.hdf5","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"models_dir = \"../input/saved-models\"\n#if not os.path.exists(models_dir):\n #   os.makedirs(models_dir)\n    \ncheckpointer = ModelCheckpoint(filepath='saved_models/weights_best_vanilla.hdf5', \n                               monitor='val_loss', mode='min',\n                               verbose=1, save_best_only=True)\nes = EarlyStopping(monitor='val_loss', mode='min', verbose=1, patience=2)\ncallbacks = [checkpointer, es]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Developed the model with a total of 4 Convolutional layers, \n#a Flatten layer and then 2 Dense layers with rmsprop as optimizer, \n#and loss as categorical_crossentropy.\ndef create_model_v1():\n    # Vanilla CNN model\n    model = Sequential()\n    model.add(Conv2D(filters = 64, kernel_size = 3, padding='same', activation = 'relu', input_shape=(img_rows, img_cols, color_type)))\n    model.add(MaxPooling2D(pool_size = 2))\n\n    model.add(Conv2D(filters = 128, padding='same', kernel_size = 3, activation = 'relu'))\n    model.add(MaxPooling2D(pool_size = 2))\n\n    model.add(Conv2D(filters = 256, padding='same', kernel_size = 3, activation = 'relu'))\n    model.add(MaxPooling2D(pool_size = 2))\n\n    model.add(Conv2D(filters = 512, padding='same', kernel_size = 3, activation = 'relu'))\n    model.add(MaxPooling2D(pool_size = 2))\n\n    model.add(Dropout(0.5))\n\n    model.add(Flatten())\n\n    model.add(Dense(500, activation = 'relu'))\n    model.add(Dropout(0.5))\n    model.add(Dense(10, activation = 'softmax'))\n    \n    return model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model_v1 = create_model_v1()\n\n# More details about the layers\nmodel_v1.summary()\n\n# Compiling the model\nmodel_v1.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Training the model\nhistory_v1 = model_v1.fit(x_train, y_train, \n          validation_data=(x_test, y_test),\n          callbacks=callbacks,\n          epochs=nb_epoch, batch_size=batch_size, verbose=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def plot_train_history(history):\n    # Summarize history for accuracy\n    plt.plot(history.history['accuracy'])\n    plt.plot(history.history['val_accuracy'])\n    plt.title('Model accuracy')\n    plt.ylabel('accuracy')\n    plt.xlabel('epoch')\n    plt.legend(['train', 'test'], loc='upper left')\n    plt.show()\n\n    # Summarize history for loss\n    plt.plot(history.history['loss'])\n    plt.plot(history.history['val_loss'])\n    plt.title('Model loss')\n    plt.ylabel('loss')\n    plt.xlabel('epoch')\n    plt.legend(['train', 'test'], loc='upper left')\n    plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plot_train_history(history_v1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Predict and plot the test images\ndef plot_test_class(model, test_files, image_number, color_type=3):\n    img_brute = test_files[image_number]\n    img_brute = cv2.resize(img_brute,(img_rows,img_cols))\n    plt.imshow(img_brute, cmap='gray')\n    \n\n    new_img = img_brute.reshape(-1,img_rows,img_cols,color_type)\n\n    y_prediction = model.predict(new_img, batch_size=batch_size, verbose=1)\n    print('Y prediction: {}'.format(y_prediction))    \n    predicted_txt = format(activity_map.get('c{}'.format(np.argmax(y_prediction))))\n    print('Predicted: {}'.format(activity_map.get('c{}'.format(np.argmax(y_prediction)))))\n    \n    font = cv2.FONT_HERSHEY_SIMPLEX\n    \n    plt.show()\n    \n    \n    ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Getting the accuracy scores\nscore = model_v1.evaluate(x_test, y_test, verbose=1)\nprint('Score: ', score)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Call and plot the test image results\nplot_test_class(model_v1, test_files, 20)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Store the prediction of the test files\npredictions = model_v1.predict(test_files, batch_size=batch_size)\nFileLink(create_submission(predictions, test_targets, score[0]))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model_v1.save('vannila_CNN.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model_v1.save('vanilla_CNN')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow import keras\nmodel = keras.models.load_model('./vanilla_CNN')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import tensorflow as tf\n\n#sunflower_url = \"../input/state-farm-distracted-driver-detection/imgs/test/img_100.jpg\"\n#sunflower_path = tf.keras.utils.get_file('../input/state-farm-distracted-driver-detection/imgs/test/img_100.jpg'), origin=sunflower_url)\n\nimg = keras.preprocessing.image.load_img(\n    '../input/state-farm-distracted-driver-detection/imgs/test/img_100.jpg', target_size=(224, 224)\n)\nimg_array = keras.preprocessing.image.img_to_array(img)\nimg_array = tf.expand_dims(img_array, 0) # Create a batch\nclass_names = ['Safe driving', \n                'Texting - right', \n                'Talking on the phone - right', \n                'Texting - left', \n                'Talking on the phone - left', \n                'Operating the radio', \n                'Drinking', \n                'Reaching behind', \n                'Hair and makeup', \n                'Talking to passenger']\n\ny_prediction = model.predict(img_array)\nprint('Y prediction: {}'.format(y_prediction))    \npredicted_txt = format(activity_map.get('c{}'.format(np.argmax(y_prediction))))\nprint('Predicted: {}'.format(activity_map.get('c{}'.format(np.argmax(y_prediction)))))\n    \nfont = cv2.FONT_HERSHEY_SIMPLEX\n    \nplt.show()\nplt.imshow(img_array[0], cmap ='gray')\n    \n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!zip -r ./saved_model.zip ./vanilla_CNN","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":4}