{"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":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport 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# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        os.path.join(dirname, filename)\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2021-07-09T07:16:58.106774Z","iopub.execute_input":"2021-07-09T07:16:58.107081Z","iopub.status.idle":"2021-07-09T07:19:19.970621Z","shell.execute_reply.started":"2021-07-09T07:16:58.10701Z","shell.execute_reply":"2021-07-09T07:19:19.969741Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Importing Modules","metadata":{}},{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport tensorflow as tf\nimport os\nimport cv2\nfrom glob import glob\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport random\n\nfrom keras.preprocessing import image\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.optimizers import RMSprop,Adam\nfrom sklearn.model_selection import train_test_split\nimport tensorflow as tf\nprint(tf.__version__)","metadata":{"execution":{"iopub.status.busy":"2021-07-09T07:19:19.972028Z","iopub.execute_input":"2021-07-09T07:19:19.972381Z","iopub.status.idle":"2021-07-09T07:19:25.535846Z","shell.execute_reply.started":"2021-07-09T07:19:19.972318Z","shell.execute_reply":"2021-07-09T07:19:25.534966Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Loading Data","metadata":{}},{"cell_type":"code","source":"BASE_DIR=('../input/state-farm-distracted-driver-detection/imgs/')\ntrain_dir=os.path.join(BASE_DIR,'train/')\ntest_dir=os.path.join(BASE_DIR,'test/')\n\nprint('Number of images in training set = ',str(len(glob(train_dir+'*/*'))))\nprint('Number of images in testing set = ',str(len(glob(test_dir+'*'))))","metadata":{"execution":{"iopub.status.busy":"2021-07-09T07:19:25.537652Z","iopub.execute_input":"2021-07-09T07:19:25.538173Z","iopub.status.idle":"2021-07-09T07:19:25.895384Z","shell.execute_reply.started":"2021-07-09T07:19:25.538131Z","shell.execute_reply":"2021-07-09T07:19:25.894554Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Making Train, validation and test directories","metadata":{}},{"cell_type":"code","source":"class_labels=['safe driving','texting - right','talking on the phone - right','texting - left','talking on the phone - left','operating the radio','drinking','reaching behind','hair and makeup','talking to passenger']\n\n#training directories\nfor label in class_labels:\n    tf.io.gfile.makedirs('/kaggle/working/train_dataset/'+label+'/')\n    \n#validation directories\nfor label in class_labels:\n    tf.io.gfile.makedirs('/kaggle/working/val_dataset/'+label+'/')\n    \n#test directories\nfor label in class_labels:\n    tf.io.gfile.makedirs('/kaggle/working/test_dataset/'+label+'/')\n\n    \n","metadata":{"execution":{"iopub.status.busy":"2021-07-09T07:19:25.898484Z","iopub.execute_input":"2021-07-09T07:19:25.898747Z","iopub.status.idle":"2021-07-09T07:19:26.046028Z","shell.execute_reply.started":"2021-07-09T07:19:25.898721Z","shell.execute_reply":"2021-07-09T07:19:26.045081Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"code","source":"os.listdir(\"/kaggle/working/train_dataset/\")","metadata":{"execution":{"iopub.status.busy":"2021-07-09T07:19:26.047791Z","iopub.execute_input":"2021-07-09T07:19:26.048254Z","iopub.status.idle":"2021-07-09T07:19:26.060289Z","shell.execute_reply.started":"2021-07-09T07:19:26.048212Z","shell.execute_reply":"2021-07-09T07:19:26.059429Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### The predicted 10 classes\n* 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":"SAFE_DRIVING=os.path.join(train_dir,'c0/')\nTEXTING_RIGHT=os.path.join(train_dir,'c1/')\nTALKING_ON_PHONE_RIGHT=os.path.join(train_dir,'c2/')\nTEXTING_LEFT=os.path.join(train_dir,'c3/')\nTALKING_ON_PHONE_LEFT=os.path.join(train_dir,'c4/')\nOPERATING_THE_RADIO=os.path.join(train_dir,'c5/')\nDRINKING=os.path.join(train_dir,'c6/')\nREACHING_BEHIND=os.path.join(train_dir,'c7/')\nHAIR_MAKEUP=os.path.join(train_dir,'c8/')\nTALKING_TO_PASSENGER=os.path.join(train_dir,'c9/')\n\nprint(\"Safe driving = \",len(os.listdir(SAFE_DRIVING)))\nprint(\"Texting right = \",len(os.listdir(TEXTING_RIGHT)))\nprint(\"Talking on phone right = \",len(os.listdir(TALKING_ON_PHONE_RIGHT)))\nprint(\"Texting left = \",len(os.listdir(TEXTING_LEFT)))\nprint(\"Talking on phone left = \",len(os.listdir(TALKING_ON_PHONE_LEFT)))\nprint(\"Operating the radio = \",len(os.listdir(OPERATING_THE_RADIO)))\nprint(\"Drinking = \",len(os.listdir(DRINKING)))\nprint(\"Reaching behind = \",len(os.listdir(REACHING_BEHIND)))\nprint(\"Hair makeup = \",len(os.listdir(HAIR_MAKEUP)))\nprint(\"Talking to passenger = \",len(os.listdir(TALKING_TO_PASSENGER)))","metadata":{"execution":{"iopub.status.busy":"2021-07-09T07:19:26.061508Z","iopub.execute_input":"2021-07-09T07:19:26.061845Z","iopub.status.idle":"2021-07-09T07:19:26.087871Z","shell.execute_reply.started":"2021-07-09T07:19:26.06181Z","shell.execute_reply":"2021-07-09T07:19:26.087149Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Distribution of images in respective directories\n\nimport pathlib \nimport cv2\nimport shutil\n\ndef distribution(param1, param2, param3):\n\n#     data_dir = pathlib.Path(param2)\n#     data_dir\n\n    a=os.listdir(param3)\n\n    test = a[:200]\n    val = a[201:401]\n    train = a[402:]\n\n\n    for images in test:\n#         print(f\"../input/state-farm-distracted-driver-detection/imgs/train/{param1}/\"+images, f\"/kaggle/working/test_dataset/{param2}/\")\n        shutil.copy(f\"../input/state-farm-distracted-driver-detection/imgs/train/{param1}/\"+images, f\"/kaggle/working/test_dataset/{param2}/\")\n    for images in val:\n        shutil.copy(f\"../input/state-farm-distracted-driver-detection/imgs/train/{param1}/\"+images, f\"/kaggle/working/val_dataset/{param2}/\")\n\n    for images in train:\n        shutil.copy(f\"../input/state-farm-distracted-driver-detection/imgs/train/{param1}/\"+images, f\"/kaggle/working/train_dataset/{param2}/\")\n\n\n    print(f\"The count of images for test_dataset > {param2} \",len(os.listdir(f\"/kaggle/working/test_dataset/{param2}\")))\n    print(f\"The count of images for val_dataset > {param2} \",len(os.listdir(f\"/kaggle/working/val_dataset/{param2}\")))\n    print(f\"The count of images for train_dataset > {param2} \",len(os.listdir(f\"/kaggle/working/train_dataset/{param2}\")))\n    \n    \n","metadata":{"execution":{"iopub.status.busy":"2021-07-09T07:19:26.088892Z","iopub.execute_input":"2021-07-09T07:19:26.089208Z","iopub.status.idle":"2021-07-09T07:19:26.096201Z","shell.execute_reply.started":"2021-07-09T07:19:26.089175Z","shell.execute_reply":"2021-07-09T07:19:26.095341Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dir_list = [SAFE_DRIVING, TEXTING_RIGHT, TALKING_ON_PHONE_RIGHT, TEXTING_LEFT, TALKING_ON_PHONE_LEFT, OPERATING_THE_RADIO, DRINKING, REACHING_BEHIND, HAIR_MAKEUP, TALKING_TO_PASSENGER]\ni=0\nfor class_label in class_labels:\n    print(f\"c{i}\")\n    distribution(f\"c{i}\", class_label, dir_list[i]) \n    i+=1\n","metadata":{"execution":{"iopub.status.busy":"2021-07-09T07:19:26.098785Z","iopub.execute_input":"2021-07-09T07:19:26.099271Z","iopub.status.idle":"2021-07-09T07:20:10.456692Z","shell.execute_reply.started":"2021-07-09T07:19:26.099234Z","shell.execute_reply":"2021-07-09T07:20:10.454518Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Starting with Image Preprocessing**","metadata":{}},{"cell_type":"code","source":"import PIL\nimport pathlib\n\ndata_dir = \"/kaggle/working/train_dataset/\"\n\ndata_dir = pathlib.Path(data_dir)\n\n\nprint(\"The count of total images for training set \",len(list(data_dir.glob('*/*.jpg'))))\n","metadata":{"execution":{"iopub.status.busy":"2021-07-09T07:20:10.457738Z","iopub.status.idle":"2021-07-09T07:20:10.458128Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"driving = list(data_dir.glob('safe driving/*'))\ndriving[:5]","metadata":{"execution":{"iopub.status.busy":"2021-07-09T07:20:10.459162Z","iopub.status.idle":"2021-07-09T07:20:10.45973Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import PIL\n\nPIL.Image.open(str(driving[0]))","metadata":{"execution":{"iopub.status.busy":"2021-07-09T07:20:10.460705Z","iopub.status.idle":"2021-07-09T07:20:10.461278Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"all_training_images = {\n    'safe driving' :  list(data_dir.glob('safe driving/*')),\n    'texting - right' :  list(data_dir.glob('texting - right/*')),\n    'talking on the phone - right' :  list(data_dir.glob('talking on the phone - right/*')),\n    'texting - left' :  list(data_dir.glob('texting - left/*')),\n    'talking on the phone - left' :  list(data_dir.glob('talking on the phone - left/*')),\n    'operating the radio' :  list(data_dir.glob('operating the radio/*')),\n    'drinking' :  list(data_dir.glob('drinking/*')),\n    'reaching behind' :  list(data_dir.glob('reaching behind/*')),\n    'hair and makeup' :  list(data_dir.glob('hair and makeup/*')),\n    'talking to passenger' :  list(data_dir.glob('talking to passenger/*')),\n    \n}","metadata":{"execution":{"iopub.status.busy":"2021-07-09T07:20:10.462394Z","iopub.status.idle":"2021-07-09T07:20:10.462942Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"PIL.Image.open(all_training_images['safe driving'][1])","metadata":{"execution":{"iopub.status.busy":"2021-07-09T07:20:10.464208Z","iopub.status.idle":"2021-07-09T07:20:10.464768Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Gives all the count of images in all the directories of training dataset\n\n\nfor class_label, img_count in all_training_images.items():\n    print(class_label)\n    print(len(img_count))","metadata":{"execution":{"iopub.status.busy":"2021-07-09T07:20:10.465881Z","iopub.status.idle":"2021-07-09T07:20:10.466458Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import cv2\n\n# Resizing the images\nX, Y = [], []\n\n\nfor class_label, img_count in all_training_images.items():\n    print(class_label)\n    for image in img_count:\n        img = cv2.imread(str(image))\n        resized_img = cv2.resize(img,(180,180))\n        X.append(resized_img)\n        Y.append(class_label)","metadata":{"execution":{"iopub.status.busy":"2021-07-09T07:20:10.467569Z","iopub.status.idle":"2021-07-09T07:20:10.468147Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X = np.array(X)\nY = np.array(Y)","metadata":{"execution":{"iopub.status.busy":"2021-07-09T07:20:10.469366Z","iopub.status.idle":"2021-07-09T07:20:10.469912Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Creating model\n","metadata":{}},{"cell_type":"code","source":"# model=tf.keras.models.Sequential([\n#     # This is the first convolution\n#     tf.keras.layers.Conv2D(16, (3,3), activation='relu',padding='same', input_shape=(180, 180, 1)),\n#     tf.keras.layers.MaxPooling2D(2, 2),\n#     # The second convolution\n#     tf.keras.layers.Conv2D(32, (3,3), activation='relu',padding='same'),\n#     tf.keras.layers.MaxPooling2D(2,2),\n#     # The third convolution\n#     tf.keras.layers.Conv2D(64, (3,3), activation='relu',padding='same'),\n#     tf.keras.layers.MaxPooling2D(2,2),\n#     # The fourth convolution\n#     tf.keras.layers.Conv2D(64, (3,3), activation='relu',padding='same'),\n#     tf.keras.layers.MaxPooling2D(2,2),\n#     # The fifth convolution\n#     tf.keras.layers.Conv2D(64, (3,3), activation='relu',padding='same'),\n#     tf.keras.layers.MaxPooling2D(2,2),\n#     # Flatten the results to feed into a DNN\n#     tf.keras.layers.Flatten(),\n#     # 512 neuron hidden layer\n#     tf.keras.layers.Dense(512, activation='relu'),\n#     # Only 1 output neuron. It will contain a value from 0-1 \n#     tf.keras.layers.Dense(10, activation='sigmoid')\n# ])","metadata":{"execution":{"iopub.status.busy":"2021-07-09T07:20:10.471045Z","iopub.status.idle":"2021-07-09T07:20:10.471635Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(optimizer=RMSprop(lr=0.001),\n              metrics=['accuracy','Precision','Recall'])","metadata":{"execution":{"iopub.status.busy":"2021-07-09T07:20:10.472684Z","iopub.status.idle":"2021-07-09T07:20:10.473271Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_datagen=ImageDataGenerator(rescale=1.0/255,\n                                 rotation_range=30,\n                                 width_shift_range=0.2,\n                                 height_shift_range=0.2,\n                                 zoom_range=0.2,\n                                 )\n\n\ntest_datagen=ImageDataGenerator(rescale=1.0/255)\n\ntrain_generator=train_datagen.flow_from_directory(train_dir,color_mode=\"grayscale\",target_size=(180,180),batch_size=128,class_mode='categorical',classes=['SAFE_DRIVING','TEXTING_RIGHT','TALKING_ON_PHONE_RIGHT','TEXTING_LEFT','TALKING_ON_PHONE_LEFT','OPERATING_THE_RADIO','DRINKING','REACHING_BEHIND','HAIR_MAKEUP','TALKING_TO_PASSENGER'])\n\ntest_generator=test_datagen.flow_from_directory(test_dir,color_mode=\"grayscale\",target_size=(180,180),batch_size=128,class_mode='categorical')","metadata":{"execution":{"iopub.status.busy":"2021-07-09T07:20:10.474444Z","iopub.status.idle":"2021-07-09T07:20:10.474992Z"},"trusted":true},"execution_count":null,"outputs":[]}]}