{"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        print(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-06-25T04:02:56.398728Z","iopub.execute_input":"2021-06-25T04:02:56.399358Z","iopub.status.idle":"2021-06-25T04:03:32.219058Z","shell.execute_reply.started":"2021-06-25T04:02:56.399231Z","shell.execute_reply":"2021-06-25T04:03:32.217115Z"},"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-06-25T04:28:33.911226Z","iopub.execute_input":"2021-06-25T04:28:33.911578Z","iopub.status.idle":"2021-06-25T04:28:33.919067Z","shell.execute_reply.started":"2021-06-25T04:28:33.911548Z","shell.execute_reply":"2021-06-25T04:28:33.917947Z"},"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-06-25T04:28:36.460133Z","iopub.execute_input":"2021-06-25T04:28:36.46048Z","iopub.status.idle":"2021-06-25T04:28:36.878877Z","shell.execute_reply.started":"2021-06-25T04:28:36.46045Z","shell.execute_reply":"2021-06-25T04:28:36.877898Z"},"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","metadata":{"execution":{"iopub.status.busy":"2021-06-25T04:28:50.820805Z","iopub.execute_input":"2021-06-25T04:28:50.821134Z","iopub.status.idle":"2021-06-25T04:28:50.826983Z","shell.execute_reply.started":"2021-06-25T04:28:50.821104Z","shell.execute_reply":"2021-06-25T04:28:50.826346Z"},"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-06-25T04:03:32.223256Z","iopub.status.idle":"2021-06-25T04:03:32.223655Z"},"trusted":true},"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-06-25T04:03:32.224781Z","iopub.status.idle":"2021-06-25T04:03:32.225236Z"},"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-06-25T04:03:32.226475Z","iopub.status.idle":"2021-06-25T04:03:32.226878Z"},"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-06-25T04:03:32.227761Z","iopub.status.idle":"2021-06-25T04:03:32.228182Z"},"trusted":true},"execution_count":null,"outputs":[]}]}