{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.7.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":5048,"databundleVersionId":868335,"sourceType":"competition"}],"dockerImageVersionId":30162,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"<center><h1 style=\"color:#1a1a1a;\n                    font-size:3em\">\n        Distracted Driver Detection\n        </h1> \n        <h2 style=\"color:#1a1a1a;\n                    font-size:2em\">\n        Can computer vision spot distracted drivers?\n        </h2>\n</center>","metadata":{}},{"cell_type":"markdown","source":"## Realised by:\n * ### Mohammed JAWHAR\n * ### Amine SNOUSSI \n","metadata":{}},{"cell_type":"markdown","source":"<p style=\"font-size:1.5em\">📜 Table of Contents:</p>\n<div style=\"font-size:1.3em\">    \n    <ul>\n       <li><a href=\"#Intro-section\">Part 1: Loading Dataset 📖</a></li>   \n       <li>\n          <a href=\"#Analysis-section\">Part 2: EDA 🔎</a>\n       </li>\n       <li>\n          <a href=\"#Forcasting-section\">Part 3: CNN Model 🧿</a>\n        </li>\n        <li>\n          <a href=\"#Forcasting-section\">Part 4 : Data Augmentation 🖼️</a>\n        </li>\n        \n    ","metadata":{}},{"cell_type":"markdown","source":"<div id=\"overview\">\n        <h1 style=\"color:#1a1a1a\">\n         ⮞  Part 1 : Loading Dataset \n        </h1>\n</div>","metadata":{}},{"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)\nimport cv2\nimport os\nfrom tqdm import tqdm\nfrom glob import glob\nfrom keras.utils import np_utils\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\n\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Sequential, Model\nfrom keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout, BatchNormalization, GlobalAveragePooling2D\n\n","metadata":{"execution":{"iopub.status.busy":"2024-04-07T12:51:27.530489Z","iopub.execute_input":"2024-04-07T12:51:27.530766Z","iopub.status.idle":"2024-04-07T12:51:33.384879Z","shell.execute_reply.started":"2024-04-07T12:51:27.530734Z","shell.execute_reply":"2024-04-07T12:51:33.384091Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df = pd.read_csv('../input/state-farm-distracted-driver-detection/driver_imgs_list.csv')\ndf.head(5)","metadata":{"execution":{"iopub.status.busy":"2024-04-07T12:51:33.386305Z","iopub.execute_input":"2024-04-07T12:51:33.386536Z","iopub.status.idle":"2024-04-07T12:51:33.440282Z","shell.execute_reply.started":"2024-04-07T12:51:33.386509Z","shell.execute_reply":"2024-04-07T12:51:33.439598Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Groupby subjects\nby_drivers = df.groupby('subject') \n#Group unique drivers\nunique_drivers = by_drivers.groups.keys() # drivers id\n\nprint('There are : ',len(unique_drivers), ' unique drivers')\nprint('There is a mean of ',round(df.groupby('subject').count()['classname'].mean()), ' images by driver.')","metadata":{"execution":{"iopub.status.busy":"2024-04-07T12:51:33.441459Z","iopub.execute_input":"2024-04-07T12:51:33.442246Z","iopub.status.idle":"2024-04-07T12:51:33.468174Z","shell.execute_reply.started":"2024-04-07T12:51:33.442207Z","shell.execute_reply":"2024-04-07T12:51:33.467406Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"num_classes = 10","metadata":{"execution":{"iopub.status.busy":"2024-04-07T12:51:33.469803Z","iopub.execute_input":"2024-04-07T12:51:33.470029Z","iopub.status.idle":"2024-04-07T12:51:33.473645Z","shell.execute_reply.started":"2024-04-07T12:51:33.470004Z","shell.execute_reply":"2024-04-07T12:51:33.472930Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Read with opencv\ndef get_image(path, img_rows, img_cols, color_type=3):\n    \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    img = cv2.resize(img, (img_rows, img_cols)) # Reduce size\n    return img\n\n#Loading training dataset\ndef train_data_load(img_rows=64, img_cols=64, color_type=3):\n    train_images=[]\n    train_labels=[]\n    \n    #Loop over the training folder\n    for classes in tqdm(range(num_classes)):\n        print('Loading directory c{}'.format(classes))\n        files = glob(os.path.join('../input/state-farm-distracted-driver-detection/imgs/train/c' + str(classes), '*.jpg'))\n        for file in files:\n            img = get_image(file, img_rows, img_cols, color_type)\n            train_images.append(img)\n            train_labels.append(classes)\n    return train_images, train_labels\n\ndef read_and_normalize_train_data(img_rows, img_cols, color_type):\n    X, labels = train_data_load(img_rows, img_cols, color_type)\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    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 validation dataset\ndef load_test(size=200000, img_rows=64, img_cols=64, color_type=3):\n    \"\"\"\n    Same as above but for validation dataset\n    \"\"\"\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_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\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    test_data = np.array(test_data, dtype=np.uint8)\n    test_data = test_data.reshape(-1,img_rows,img_cols,color_type)\n    return test_data, test_ids\n    ","metadata":{"execution":{"iopub.status.busy":"2024-04-07T12:51:33.474804Z","iopub.execute_input":"2024-04-07T12:51:33.475066Z","iopub.status.idle":"2024-04-07T12:51:33.493026Z","shell.execute_reply.started":"2024-04-07T12:51:33.475031Z","shell.execute_reply":"2024-04-07T12:51:33.492088Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pip install np_utils\n","metadata":{"execution":{"iopub.status.busy":"2024-04-07T12:51:33.494141Z","iopub.execute_input":"2024-04-07T12:51:33.494400Z","iopub.status.idle":"2024-04-07T12:51:45.559844Z","shell.execute_reply.started":"2024-04-07T12:51:33.494357Z","shell.execute_reply":"2024-04-07T12:51:45.558888Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"img_rows = 64\nimg_cols = 64\ncolor_type = 1\nnb_test_samples = 200\n\n#Loading train images \nx_train, x_test, y_train, y_test = read_and_normalize_train_data(img_rows, img_cols, color_type)\n\n#Loading validation images \ntest_files, test_targets = read_and_normalize_sampled_test_data(nb_test_samples, img_rows, img_cols, color_type)","metadata":{"execution":{"iopub.status.busy":"2024-04-07T12:51:45.561657Z","iopub.execute_input":"2024-04-07T12:51:45.561972Z","iopub.status.idle":"2024-04-07T12:56:15.732967Z","shell.execute_reply.started":"2024-04-07T12:51:45.561932Z","shell.execute_reply":"2024-04-07T12:56:15.732180Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<div id=\"overview\">\n        <h1 style=\"color:#1a1a1a\">\n         ⮞  Part 2 : EDA \n        </h1>\n</div>","metadata":{}},{"cell_type":"markdown","source":"### Data visualisation\n ","metadata":{}},{"cell_type":"code","source":"import plotly.express as px\npx.histogram(df, x=\"classname\", color=\"classname\", title=\"Number of images by categories \")\n","metadata":{"execution":{"iopub.status.busy":"2024-04-07T12:56:15.734167Z","iopub.execute_input":"2024-04-07T12:56:15.734407Z","iopub.status.idle":"2024-04-07T12:56:19.392757Z","shell.execute_reply.started":"2024-04-07T12:56:15.734378Z","shell.execute_reply":"2024-04-07T12:56:19.392002Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Find the frequency of images per driver\ndrivers_id = pd.DataFrame((df['subject'].value_counts()).reset_index())\ndrivers_id.columns = ['driver_id', 'Counts']\npx.histogram(drivers_id, x=\"driver_id\",y=\"Counts\" ,color=\"driver_id\", title=\"Number of images by subjects \")","metadata":{"execution":{"iopub.status.busy":"2024-04-07T12:56:19.393802Z","iopub.execute_input":"2024-04-07T12:56:19.394032Z","iopub.status.idle":"2024-04-07T12:56:19.577362Z","shell.execute_reply.started":"2024-04-07T12:56:19.394005Z","shell.execute_reply":"2024-04-07T12:56:19.576669Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Images overview\n","metadata":{}},{"cell_type":"code","source":"activity_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'}\n\n\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])","metadata":{"execution":{"iopub.status.busy":"2024-04-07T12:56:19.579706Z","iopub.execute_input":"2024-04-07T12:56:19.579920Z","iopub.status.idle":"2024-04-07T12:56:21.634002Z","shell.execute_reply.started":"2024-04-07T12:56:19.579893Z","shell.execute_reply":"2024-04-07T12:56:21.633164Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<div id=\"overview\">\n        <h1 style=\"color:#1a1a1a\">\n         ⮞  Part 3 : CNN Model \n        </h1>\n</div>","metadata":{}},{"cell_type":"markdown","source":"### Architecture :\n\n* 3 Convolutionnal layers (with Relu, Maxpooling and dropout)\n* A flatten layer\n* 2 Dense layers with Relu and Dropouts\n* 1 Dense layer with softmax for the classification","metadata":{}},{"cell_type":"code","source":"batch_size = 40\nn_epochs = 10","metadata":{"execution":{"iopub.status.busy":"2024-04-07T12:56:21.635115Z","iopub.execute_input":"2024-04-07T12:56:21.635368Z","iopub.status.idle":"2024-04-07T12:56:21.639039Z","shell.execute_reply.started":"2024-04-07T12:56:21.635338Z","shell.execute_reply":"2024-04-07T12:56:21.638335Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def create_model():\n    \n    model = Sequential()\n    \n    # CNN1\n    model.add(Conv2D(128, (5, 5), activation='relu', input_shape=(img_rows, img_cols, color_type), padding='same'))\n    model.add(BatchNormalization())\n    # CNN2\n    model.add(Conv2D(128, (5, 5), activation='relu', padding='same'))\n    model.add(BatchNormalization())\n    model.add(MaxPooling2D(pool_size=(2, 2)))\n    model.add(Dropout(0.25))\n    # CNN3\n    model.add(Conv2D(256, (3, 3), activation='relu', padding='same'))\n    model.add(BatchNormalization())\n    # CNN4\n    model.add(Conv2D(256, (3, 3), activation='relu', padding='same'))\n    model.add(BatchNormalization())\n    model.add(MaxPooling2D(pool_size=(2, 2)))\n    model.add(Dropout(0.25))\n\n    # Flattening followed by Dense layers\n    model.add(Flatten())\n    model.add(Dense(1024, activation='relu'))\n    model.add(BatchNormalization())\n    model.add(Dropout(0.5))\n    model.add(Dense(512, activation='relu'))\n    model.add(BatchNormalization())\n    model.add(Dropout(0.5))\n    model.add(Dense(10, activation='softmax'))  # Assuming 10 classes for classification\n\n    return model","metadata":{"execution":{"iopub.status.busy":"2024-04-07T12:56:21.640048Z","iopub.execute_input":"2024-04-07T12:56:21.640299Z","iopub.status.idle":"2024-04-07T12:56:21.654875Z","shell.execute_reply.started":"2024-04-07T12:56:21.640267Z","shell.execute_reply":"2024-04-07T12:56:21.654085Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = create_model()\n\n#Details about the model\nmodel.summary()\n\nmodel.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])\n","metadata":{"execution":{"iopub.status.busy":"2024-04-07T12:56:21.656075Z","iopub.execute_input":"2024-04-07T12:56:21.656321Z","iopub.status.idle":"2024-04-07T12:56:24.618345Z","shell.execute_reply.started":"2024-04-07T12:56:21.656291Z","shell.execute_reply":"2024-04-07T12:56:24.617602Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### Training model","metadata":{}},{"cell_type":"code","source":"history = model.fit(x_train, y_train,\n                   validation_data=(x_test, y_test),\n                   epochs=n_epochs, batch_size=batch_size, verbose=1)\n\nprint('History of the training',history.history)\n","metadata":{"execution":{"iopub.status.busy":"2024-04-07T12:56:24.619410Z","iopub.execute_input":"2024-04-07T12:56:24.619630Z","iopub.status.idle":"2024-04-07T12:58:22.415670Z","shell.execute_reply.started":"2024-04-07T12:56:24.619602Z","shell.execute_reply":"2024-04-07T12:58:22.414874Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def plot_train_history(history):\n    \"\"\"\n    Plot the validation accuracy and validation loss over epochs\n    \"\"\"\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()\n    \nplot_train_history(history)","metadata":{"execution":{"iopub.status.busy":"2024-04-07T12:58:22.416751Z","iopub.execute_input":"2024-04-07T12:58:22.416989Z","iopub.status.idle":"2024-04-07T12:58:22.846883Z","shell.execute_reply.started":"2024-04-07T12:58:22.416960Z","shell.execute_reply":"2024-04-07T12:58:22.846193Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Prediction on test set","metadata":{}},{"cell_type":"code","source":"def plot_test_class(model, test_files, image_number, color_type=1):\n    \"\"\"\n    Function that tests or model on test images and show the results\n    \"\"\"\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    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    print('Predicted: {}'.format(activity_map.get('c{}'.format(np.argmax(y_prediction)))))\n    \n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2024-04-07T12:58:22.848062Z","iopub.execute_input":"2024-04-07T12:58:22.848347Z","iopub.status.idle":"2024-04-07T12:58:22.854946Z","shell.execute_reply.started":"2024-04-07T12:58:22.848310Z","shell.execute_reply":"2024-04-07T12:58:22.854273Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"score1 = model.evaluate(x_test, y_test, verbose=1)\n","metadata":{"execution":{"iopub.status.busy":"2024-04-07T12:58:22.856066Z","iopub.execute_input":"2024-04-07T12:58:22.856300Z","iopub.status.idle":"2024-04-07T12:58:23.927794Z","shell.execute_reply.started":"2024-04-07T12:58:22.856270Z","shell.execute_reply":"2024-04-07T12:58:23.927193Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print('Loss: ', score1[0])\nprint('Accuracy: ', score1[1]*100, ' %')","metadata":{"execution":{"iopub.status.busy":"2024-04-07T12:58:23.929027Z","iopub.execute_input":"2024-04-07T12:58:23.929331Z","iopub.status.idle":"2024-04-07T12:58:23.935404Z","shell.execute_reply.started":"2024-04-07T12:58:23.929293Z","shell.execute_reply":"2024-04-07T12:58:23.934640Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for i in range(10):\n    plot_test_class(model, test_files, i)","metadata":{"execution":{"iopub.status.busy":"2024-04-07T12:58:23.936558Z","iopub.execute_input":"2024-04-07T12:58:23.936829Z","iopub.status.idle":"2024-04-07T12:58:26.166846Z","shell.execute_reply.started":"2024-04-07T12:58:23.936791Z","shell.execute_reply":"2024-04-07T12:58:26.166155Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<div id=\"overview\">\n        <h1 style=\"color:#1a1a1a\">\n         ⮞  Part 4 : Data Augmentation\n        </h1>\n</div>","metadata":{}},{"cell_type":"code","source":"# Using ImageDataGenerator from keras\ntrain_datagen = ImageDataGenerator(rescale = 1.0/255, \n                                   shear_range = 0.2, \n                                   zoom_range = 0.2, \n                                   horizontal_flip = True, \n                                   validation_split = 0.2)\n\ntest_datagen = ImageDataGenerator(rescale=1.0/ 255, validation_split = 0.2)","metadata":{"execution":{"iopub.status.busy":"2024-04-07T12:58:26.168103Z","iopub.execute_input":"2024-04-07T12:58:26.168336Z","iopub.status.idle":"2024-04-07T12:58:26.173333Z","shell.execute_reply.started":"2024-04-07T12:58:26.168308Z","shell.execute_reply":"2024-04-07T12:58:26.172508Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"nb_train_samples = x_train.shape[0]\nnb_validation_samples = x_test.shape[0]\ntraining_generator = train_datagen.flow(x_train, y_train, batch_size=batch_size)\nvalidation_generator = test_datagen.flow(x_test, y_test, batch_size=batch_size)","metadata":{"execution":{"iopub.status.busy":"2024-04-07T12:58:26.174508Z","iopub.execute_input":"2024-04-07T12:58:26.174770Z","iopub.status.idle":"2024-04-07T12:58:26.562848Z","shell.execute_reply.started":"2024-04-07T12:58:26.174735Z","shell.execute_reply":"2024-04-07T12:58:26.561980Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Training with data augmentation","metadata":{}},{"cell_type":"code","source":"history_v2 = model.fit_generator(training_generator,\n                         steps_per_epoch = nb_train_samples // batch_size,\n                         epochs = n_epochs, \n                         verbose = 1,\n                         validation_data = validation_generator,\n                         validation_steps = nb_validation_samples // batch_size)","metadata":{"execution":{"iopub.status.busy":"2024-04-07T12:58:26.563985Z","iopub.execute_input":"2024-04-07T12:58:26.564225Z","iopub.status.idle":"2024-04-07T13:00:22.872876Z","shell.execute_reply.started":"2024-04-07T12:58:26.564195Z","shell.execute_reply":"2024-04-07T13:00:22.872221Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plot_train_history(history_v2)\n","metadata":{"execution":{"iopub.status.busy":"2024-04-07T13:00:22.874166Z","iopub.execute_input":"2024-04-07T13:00:22.874402Z","iopub.status.idle":"2024-04-07T13:00:23.275351Z","shell.execute_reply.started":"2024-04-07T13:00:22.874368Z","shell.execute_reply":"2024-04-07T13:00:23.274629Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Evaluate and compare the performance of the new model\nscore2 = model.evaluate_generator(validation_generator, nb_validation_samples // batch_size)\nprint(\"Loss for model 1\",score1[0])\nprint(\"Loss for model 2 (data augmentation):\", score2[0])\n\nprint(\"Test accuracy for model 1\",score1[1])\nprint(\"Test accuracy for model 2 (data augmentation):\", score2[1])","metadata":{"execution":{"iopub.status.busy":"2024-04-07T13:00:23.276547Z","iopub.execute_input":"2024-04-07T13:00:23.277157Z","iopub.status.idle":"2024-04-07T13:00:24.143247Z","shell.execute_reply.started":"2024-04-07T13:00:23.277099Z","shell.execute_reply":"2024-04-07T13:00:24.142472Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Conclusion for Data Augmentation\n### Data augmentation makes our model more robust.","metadata":{}}]}