{"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":"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 keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout\nfrom keras.preprocessing.image import ImageDataGenerator","metadata":{"execution":{"iopub.status.busy":"2022-02-23T06:42:57.834852Z","iopub.execute_input":"2022-02-23T06:42:57.835239Z","iopub.status.idle":"2022-02-23T06:43:03.235466Z","shell.execute_reply.started":"2022-02-23T06:42:57.835125Z","shell.execute_reply":"2022-02-23T06:43:03.234726Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"* 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","metadata":{}},{"cell_type":"code","source":"activity = {'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           }","metadata":{"execution":{"iopub.status.busy":"2022-02-23T06:43:03.236965Z","iopub.execute_input":"2022-02-23T06:43:03.237183Z","iopub.status.idle":"2022-02-23T06:43:03.242080Z","shell.execute_reply.started":"2022-02-23T06:43:03.237151Z","shell.execute_reply":"2022-02-23T06:43:03.241427Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 1st image of all different classes","metadata":{}},{"cell_type":"code","source":"# listdir(path) is used to get the list of all files and directories in path\n# enumerate(iterator) will give the list of tuple containing counter(starting from 0 by default), value\nimport matplotlib.image as mpimg\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                # after 0 loop stop. so only 1st will be printed from every folder\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[directory])","metadata":{"execution":{"iopub.status.busy":"2022-02-23T06:43:03.243349Z","iopub.execute_input":"2022-02-23T06:43:03.243794Z","iopub.status.idle":"2022-02-23T06:43:07.495877Z","shell.execute_reply.started":"2022-02-23T06:43:03.243761Z","shell.execute_reply":"2022-02-23T06:43:07.495133Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Checking Dimensions of all Images in different classes","metadata":{}},{"cell_type":"code","source":"#Checking Dimension of Images:\nBASE_URL = '../input/state-farm-distracted-driver-detection/imgs/train/'\nprint(\"Dimension of Images :-\")\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                # after 0 loop stop. so only 1st will be printed from every folder\n            else:\n                image = mpimg.imread(BASE_URL + directory + '/' + file)\n                print(directory, \" : \", image.shape)","metadata":{"execution":{"iopub.status.busy":"2022-02-23T06:43:07.497769Z","iopub.execute_input":"2022-02-23T06:43:07.497988Z","iopub.status.idle":"2022-02-23T06:43:07.575593Z","shell.execute_reply.started":"2022-02-23T06:43:07.497959Z","shell.execute_reply":"2022-02-23T06:43:07.574936Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Creating Model","metadata":{}},{"cell_type":"code","source":"# Creating Model\n# 3 Convolution Layer, 3 Dense Layer and 1 flatten layer is used. adam optimizer and categorical_crossentropy as loss function\nimport keras\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D, Dense, Activation, MaxPooling2D, Dropout, Flatten\n\nmodel = Sequential()\nmodel.add(Conv2D(filters = 128, kernel_size = (3, 3), activation = 'relu', input_shape = (240, 240, 3), data_format = 'channels_last', padding = \"same\"))\nmodel.add(MaxPooling2D(pool_size = (2, 2)))\nmodel.add(Conv2D(filters = 64, kernel_size = (3, 3), activation = 'relu', padding = \"same\"))\nmodel.add(MaxPooling2D(pool_size = (2, 2)))\nmodel.add(Conv2D(filters = 32, kernel_size = (3, 3), activation = 'relu', padding = \"same\"))\nmodel.add(MaxPooling2D(pool_size = (2, 2)))\nmodel.add(Flatten())\nmodel.add(Dense(units = 1024, activation = 'relu'))\nmodel.add(Dense(units = 256, activation = 'relu'))\nmodel.add(Dense(units = 10, activation = 'sigmoid'))\nmodel.compile(optimizer = 'adam', loss = 'categorical_crossentropy', metrics = ['accuracy'])\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2022-02-23T06:43:07.577458Z","iopub.execute_input":"2022-02-23T06:43:07.577920Z","iopub.status.idle":"2022-02-23T06:43:09.901099Z","shell.execute_reply.started":"2022-02-23T06:43:07.577881Z","shell.execute_reply":"2022-02-23T06:43:09.900417Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Preprocessing Images ","metadata":{}},{"cell_type":"code","source":"from keras.preprocessing.image import ImageDataGenerator\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\ntraining_set = train_datagen.flow_from_directory('../input/state-farm-distracted-driver-detection/imgs/train/', \n                                                 target_size = (240, 240), \n                                                 batch_size = 32,\n                                                 subset = 'training')\n\nvalidation_set = train_datagen.flow_from_directory('../input/state-farm-distracted-driver-detection/imgs/train/', \n                                                   target_size = (240, 240), \n                                                   batch_size = 32,\n                                                   subset = 'validation')","metadata":{"execution":{"iopub.status.busy":"2022-02-23T06:43:09.902450Z","iopub.execute_input":"2022-02-23T06:43:09.902725Z","iopub.status.idle":"2022-02-23T06:43:29.165898Z","shell.execute_reply.started":"2022-02-23T06:43:09.902678Z","shell.execute_reply":"2022-02-23T06:43:29.165030Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Fitting and Checking Accuracy of Model","metadata":{}},{"cell_type":"code","source":"model.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-02-23T06:43:29.167448Z","iopub.execute_input":"2022-02-23T06:43:29.167961Z","iopub.status.idle":"2022-02-23T07:42:25.384904Z","shell.execute_reply.started":"2022-02-23T06:43:29.167923Z","shell.execute_reply":"2022-02-23T07:42:25.384253Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Model is working with 98% accuracy","metadata":{}}]}