{"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_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# Distracted Driver Detection","metadata":{}},{"cell_type":"markdown","source":"# Importing Libraries","metadata":{}},{"cell_type":"code","source":"import os\nimport tensorflow\nos.environ['KERAS_BACKEND'] = 'tensorflow'\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # 3 = INFO, WARNING, and ERROR messages are not printed\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport warnings\nwarnings.filterwarnings('ignore')\n\nfrom sklearn.model_selection import train_test_split\n\nfrom sklearn.metrics import confusion_matrix\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout\nfrom keras.preprocessing.image import ImageDataGenerator","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-05-26T21:07:21.432671Z","iopub.execute_input":"2022-05-26T21:07:21.432950Z","iopub.status.idle":"2022-05-26T21:07:21.438994Z","shell.execute_reply.started":"2022-05-26T21:07:21.432899Z","shell.execute_reply":"2022-05-26T21:07:21.438167Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Import the dataset","metadata":{}},{"cell_type":"code","source":"dataset = pd.read_csv('../input/driver_imgs_list.csv')\ndataset.head(5)","metadata":{"execution":{"iopub.status.busy":"2022-05-26T18:49:30.225078Z","iopub.execute_input":"2022-05-26T18:49:30.225694Z","iopub.status.idle":"2022-05-26T18:49:30.307549Z","shell.execute_reply.started":"2022-05-26T18:49:30.225626Z","shell.execute_reply":"2022-05-26T18:49:30.305652Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Building the model\n\nI will develop the model with a total of 3 Convolutional layers, then a Flatten layer and then 3 Dense layers. I'll use the optimizer as **adam**, and loss as **categorical_crossentropy**.","metadata":{}},{"cell_type":"code","source":"classifier = Sequential()\nclassifier.add(Conv2D(filters = 128, kernel_size = (3, 3), activation = 'relu', input_shape = (240, 240, 3), data_format = 'channels_last'))\nclassifier.add(MaxPooling2D(pool_size = (2, 2)))\nclassifier.add(Conv2D(filters = 64, kernel_size = (3, 3), activation = 'relu'))\nclassifier.add(MaxPooling2D(pool_size = (2, 2)))\nclassifier.add(Conv2D(filters = 32, kernel_size = (3, 3), activation = 'relu'))\nclassifier.add(MaxPooling2D(pool_size = (2, 2)))\nclassifier.add(Flatten())\nclassifier.add(Dense(units = 1024, activation = 'relu'))\nclassifier.add(Dense(units = 256, activation = 'relu'))\nclassifier.add(Dense(units = 10, activation = 'sigmoid'))\nclassifier.compile(optimizer = 'adam', loss = 'categorical_crossentropy', metrics = ['accuracy'])\nclassifier.summary()","metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","execution":{"iopub.status.busy":"2022-05-26T18:49:30.312337Z","iopub.execute_input":"2022-05-26T18:49:30.314790Z","iopub.status.idle":"2022-05-26T18:49:30.629210Z","shell.execute_reply.started":"2022-05-26T18:49:30.314720Z","shell.execute_reply":"2022-05-26T18:49:30.628452Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Creating training data\n\nI will generate more images using **ImageDataGenerator** and split the training data into 80% train and 20% validation split.","metadata":{}},{"cell_type":"code","source":"train_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)","metadata":{"execution":{"iopub.status.busy":"2022-05-26T18:49:30.633471Z","iopub.execute_input":"2022-05-26T18:49:30.635638Z","iopub.status.idle":"2022-05-26T18:49:30.642766Z","shell.execute_reply.started":"2022-05-26T18:49:30.635586Z","shell.execute_reply":"2022-05-26T18:49:30.641990Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n\ntraining_set = train_datagen.flow_from_directory('../input/imgs/train', \n                                                 target_size = (240, 240), \n                                                 batch_size = 32,\n                                                 subset = \"training\")\n\nvalidation_set = train_datagen.flow_from_directory('../input/imgs/train', \n                                                   target_size = (240, 240), \n                                                   batch_size = 32,\n                                                   subset = 'validation')","metadata":{"execution":{"iopub.status.busy":"2022-05-26T18:49:30.646846Z","iopub.execute_input":"2022-05-26T18:49:30.649094Z","iopub.status.idle":"2022-05-26T18:49:53.871861Z","shell.execute_reply.started":"2022-05-26T18:49:30.649042Z","shell.execute_reply":"2022-05-26T18:49:53.870983Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Train the model\n\nUsing **fit_generator**, I'll train the model.","metadata":{}},{"cell_type":"code","source":"history=classifier.fit_generator(training_set,\n                         steps_per_epoch = 17943/32,\n                         epochs = 10,\n                         validation_data = validation_set,\n                         validation_steps = 4481/32)","metadata":{"execution":{"iopub.status.busy":"2022-05-26T18:49:53.873288Z","iopub.execute_input":"2022-05-26T18:49:53.873575Z","iopub.status.idle":"2022-05-26T19:56:37.058430Z","shell.execute_reply.started":"2022-05-26T18:49:53.873526Z","shell.execute_reply":"2022-05-26T19:56:37.057475Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# plot accuracy and loss history\nacc = history.history['acc']\nval_acc = history.history['val_acc']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nplt.figure(figsize=(20, 8))\nplt.subplot(1, 2, 1)\nplt.plot(acc, label='Training Accuracy')\nplt.plot(val_acc, label='Validation Accuracy')\nplt.ylim((0.8,1))\nplt.grid(True)\nplt.xlabel(\"Epochs (-)\")\nplt.ylabel(\"Accuracy (-)\")\nplt.legend(loc='lower right')\nplt.title('Training and Validation Accuracy')\n\nplt.subplot(1, 2, 2)\nplt.plot(loss, label='Training Loss')\nplt.plot(val_loss, label='Validation Loss')\nplt.legend(loc='upper right')\nplt.ylim((0.0,0.5))\nplt.grid(True)\nplt.xlabel(\"Epochs (-)\")\nplt.ylabel(\"Loss (-)\")\nplt.title('Training and Validation Loss')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-05-26T20:07:07.306091Z","iopub.execute_input":"2022-05-26T20:07:07.306445Z","iopub.status.idle":"2022-05-26T20:07:07.927866Z","shell.execute_reply.started":"2022-05-26T20:07:07.306388Z","shell.execute_reply":"2022-05-26T20:07:07.926909Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"loss,accuracy=classifier.evaluate_generator(validation_set,steps=4481/32)","metadata":{"execution":{"iopub.status.busy":"2022-05-26T20:50:33.859440Z","iopub.execute_input":"2022-05-26T20:50:33.859738Z","iopub.status.idle":"2022-05-26T20:51:49.660170Z","shell.execute_reply.started":"2022-05-26T20:50:33.859684Z","shell.execute_reply":"2022-05-26T20:51:49.659244Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"Accuracy of Model is\",accuracy*100,\"%\")","metadata":{"execution":{"iopub.status.busy":"2022-05-26T20:51:53.811155Z","iopub.execute_input":"2022-05-26T20:51:53.811475Z","iopub.status.idle":"2022-05-26T20:51:53.816982Z","shell.execute_reply.started":"2022-05-26T20:51:53.811419Z","shell.execute_reply":"2022-05-26T20:51:53.815978Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pred=classifier.predict_generator(validation_set,steps=4481/32,use_multiprocessing=True)","metadata":{"execution":{"iopub.status.busy":"2022-05-26T20:55:54.852752Z","iopub.execute_input":"2022-05-26T20:55:54.853140Z","iopub.status.idle":"2022-05-26T20:57:17.322962Z","shell.execute_reply.started":"2022-05-26T20:55:54.853066Z","shell.execute_reply":"2022-05-26T20:57:17.320925Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"np.argmax(pred,axis=1)","metadata":{"execution":{"iopub.status.busy":"2022-05-26T21:05:37.869899Z","iopub.execute_input":"2022-05-26T21:05:37.870182Z","iopub.status.idle":"2022-05-26T21:05:37.876281Z","shell.execute_reply.started":"2022-05-26T21:05:37.870131Z","shell.execute_reply":"2022-05-26T21:05:37.875513Z"},"trusted":true},"execution_count":null,"outputs":[]}]}