{"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\n# import numpy as np # linear algebra\n# import 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\n# import os\n# for 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-09-08T04:39:20.928545Z","iopub.execute_input":"2021-09-08T04:39:20.928886Z","iopub.status.idle":"2021-09-08T04:39:20.932881Z","shell.execute_reply.started":"2021-09-08T04:39:20.928844Z","shell.execute_reply":"2021-09-08T04:39:20.931913Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Importing Modules","metadata":{}},{"cell_type":"code","source":"\nimport 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-09-08T04:39:20.941281Z","iopub.execute_input":"2021-09-08T04:39:20.941597Z","iopub.status.idle":"2021-09-08T04:39:20.950845Z","shell.execute_reply.started":"2021-09-08T04:39:20.941572Z","shell.execute_reply":"2021-09-08T04:39:20.949848Z"},"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-09-08T04:39:20.952514Z","iopub.execute_input":"2021-09-08T04:39:20.952930Z","iopub.status.idle":"2021-09-08T04:39:28.636738Z","shell.execute_reply.started":"2021-09-08T04:39:20.952891Z","shell.execute_reply":"2021-09-08T04:39:28.635224Z"},"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-09-08T04:39:28.638507Z","iopub.execute_input":"2021-09-08T04:39:28.638856Z","iopub.status.idle":"2021-09-08T04:39:28.646781Z","shell.execute_reply.started":"2021-09-08T04:39:28.638819Z","shell.execute_reply":"2021-09-08T04:39:28.645825Z"},"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-09-08T04:39:28.648780Z","iopub.execute_input":"2021-09-08T04:39:28.649141Z","iopub.status.idle":"2021-09-08T04:39:28.660396Z","shell.execute_reply.started":"2021-09-08T04:39:28.649105Z","shell.execute_reply":"2021-09-08T04:39:28.659296Z"},"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-09-08T04:39:28.661832Z","iopub.execute_input":"2021-09-08T04:39:28.662264Z","iopub.status.idle":"2021-09-08T04:39:28.687595Z","shell.execute_reply.started":"2021-09-08T04:39:28.662220Z","shell.execute_reply":"2021-09-08T04:39:28.686802Z"},"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-09-08T04:39:28.689774Z","iopub.execute_input":"2021-09-08T04:39:28.690070Z","iopub.status.idle":"2021-09-08T04:39:28.697605Z","shell.execute_reply.started":"2021-09-08T04:39:28.690037Z","shell.execute_reply":"2021-09-08T04:39:28.696296Z"},"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-09-08T04:39:28.700778Z","iopub.execute_input":"2021-09-08T04:39:28.701393Z","iopub.status.idle":"2021-09-08T04:42:13.735806Z","shell.execute_reply.started":"2021-09-08T04:39:28.701350Z","shell.execute_reply":"2021-09-08T04:42:13.734411Z"},"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-09-08T04:42:13.738930Z","iopub.execute_input":"2021-09-08T04:42:13.739206Z","iopub.status.idle":"2021-09-08T04:42:13.960686Z","shell.execute_reply.started":"2021-09-08T04:42:13.739178Z","shell.execute_reply":"2021-09-08T04:42:13.959836Z"},"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-09-08T04:42:13.961936Z","iopub.execute_input":"2021-09-08T04:42:13.962460Z","iopub.status.idle":"2021-09-08T04:42:13.978281Z","shell.execute_reply.started":"2021-09-08T04:42:13.962419Z","shell.execute_reply":"2021-09-08T04:42:13.977517Z"},"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-09-08T04:42:13.979470Z","iopub.execute_input":"2021-09-08T04:42:13.979811Z","iopub.status.idle":"2021-09-08T04:42:14.100241Z","shell.execute_reply.started":"2021-09-08T04:42:13.979775Z","shell.execute_reply":"2021-09-08T04:42:14.099453Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Mapping","metadata":{}},{"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-09-08T04:42:14.101248Z","iopub.execute_input":"2021-09-08T04:42:14.101589Z","iopub.status.idle":"2021-09-08T04:42:14.179358Z","shell.execute_reply.started":"2021-09-08T04:42:14.101554Z","shell.execute_reply":"2021-09-08T04:42:14.178441Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### View safe driving image","metadata":{}},{"cell_type":"code","source":"PIL.Image.open(all_training_images['safe driving'][1])","metadata":{"execution":{"iopub.status.busy":"2021-09-08T04:42:14.180590Z","iopub.execute_input":"2021-09-08T04:42:14.180920Z","iopub.status.idle":"2021-09-08T04:42:14.282086Z","shell.execute_reply.started":"2021-09-08T04:42:14.180885Z","shell.execute_reply":"2021-09-08T04:42:14.281236Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Getting count of each directory","metadata":{}},{"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-09-08T04:42:14.283312Z","iopub.execute_input":"2021-09-08T04:42:14.283637Z","iopub.status.idle":"2021-09-08T04:42:14.291951Z","shell.execute_reply.started":"2021-09-08T04:42:14.283603Z","shell.execute_reply":"2021-09-08T04:42:14.290965Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Setting variable of path of all three directories","metadata":{}},{"cell_type":"code","source":"updated_train_dir=\"/kaggle/working/train_dataset/\"\nupdated_val_dir=\"/kaggle/working/val_dataset/\"\nupdated_test_dir=\"/kaggle/working/test_dataset/\"\nprint(os.listdir(updated_train_dir))\nprint(os.listdir(updated_val_dir))\nprint(os.listdir(updated_test_dir))","metadata":{"execution":{"iopub.status.busy":"2021-09-08T04:42:14.293363Z","iopub.execute_input":"2021-09-08T04:42:14.293692Z","iopub.status.idle":"2021-09-08T04:42:14.301972Z","shell.execute_reply.started":"2021-09-08T04:42:14.293659Z","shell.execute_reply":"2021-09-08T04:42:14.300835Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Creating Image data generator ","metadata":{}},{"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# val_datagen=ImageDataGenerator(rescale=1.0/255)\n\n# test_datagen=ImageDataGenerator(rescale=1.0/255)\n\n# train_generator=train_datagen.flow_from_directory(updated_train_dir,color_mode=\"grayscale\",target_size=(180,180),class_mode='categorical')\n\n# val_generator=val_datagen.flow_from_directory(updated_val_dir,color_mode=\"grayscale\",target_size=(180,180),class_mode='categorical')\n\n# test_generator=test_datagen.flow_from_directory(updated_test_dir,color_mode=\"grayscale\",target_size=(180,180),class_mode='categorical')","metadata":{"execution":{"iopub.status.busy":"2021-09-08T04:42:14.303546Z","iopub.execute_input":"2021-09-08T04:42:14.303951Z","iopub.status.idle":"2021-09-08T04:42:14.308516Z","shell.execute_reply.started":"2021-09-08T04:42:14.303916Z","shell.execute_reply":"2021-09-08T04:42:14.307513Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Creating models\n","metadata":{}},{"cell_type":"code","source":"train_datagen3=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\nval_datagen3=ImageDataGenerator(rescale=1.0/255)\n\ntest_datagen3=ImageDataGenerator(rescale=1.0/255)\nheight = 200\nwidth = 280\ntrain_generator3=train_datagen3.flow_from_directory(updated_train_dir,target_size=(width,height),batch_size=128,class_mode='categorical')\n\nval_generator3=val_datagen3.flow_from_directory(updated_val_dir,target_size=(width,height),batch_size=128,class_mode='categorical')\n\ntest_generator3=test_datagen3.flow_from_directory(updated_test_dir,target_size=(width,height),batch_size=128,class_mode='categorical')","metadata":{"execution":{"iopub.status.busy":"2021-09-08T04:42:14.310031Z","iopub.execute_input":"2021-09-08T04:42:14.310468Z","iopub.status.idle":"2021-09-08T04:42:14.986055Z","shell.execute_reply.started":"2021-09-08T04:42:14.310432Z","shell.execute_reply":"2021-09-08T04:42:14.985285Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# from tensorflow.keras.applications.resnet50 import ResNet50\n# from tensorflow.keras.applications.vgg16 import VGG16","metadata":{"execution":{"iopub.status.busy":"2021-09-08T04:42:14.987319Z","iopub.execute_input":"2021-09-08T04:42:14.987656Z","iopub.status.idle":"2021-09-08T04:42:14.992087Z","shell.execute_reply.started":"2021-09-08T04:42:14.987619Z","shell.execute_reply":"2021-09-08T04:42:14.991013Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# pretrained_model3 = ResNet50(weights= 'imagenet', include_top=False, input_shape= (180,180,3))\n# pretrained_model3 = VGG16(weights= 'imagenet', include_top=False, input_shape= (180,180,3))\n#freazing the trained layers\n# for layers in pretrained_model3.layers:\n#     layers.trainable = False\n# pretrained_model3.summary()\n","metadata":{"execution":{"iopub.status.busy":"2021-09-08T04:42:14.993535Z","iopub.execute_input":"2021-09-08T04:42:14.993866Z","iopub.status.idle":"2021-09-08T04:42:14.999842Z","shell.execute_reply.started":"2021-09-08T04:42:14.993832Z","shell.execute_reply":"2021-09-08T04:42:14.998925Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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=(width, height, 3)),\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(1024, activation='relu'),\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='softmax')\n])","metadata":{"execution":{"iopub.status.busy":"2021-09-08T04:42:15.003875Z","iopub.execute_input":"2021-09-08T04:42:15.004137Z","iopub.status.idle":"2021-09-08T04:42:17.017286Z","shell.execute_reply.started":"2021-09-08T04:42:15.004114Z","shell.execute_reply":"2021-09-08T04:42:17.016455Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(optimizer=Adam(lr=0.0001),\n              loss='categorical_crossentropy',\n               metrics=['accuracy','Precision','Recall'])","metadata":{"execution":{"iopub.status.busy":"2021-09-08T04:42:17.018951Z","iopub.execute_input":"2021-09-08T04:42:17.019299Z","iopub.status.idle":"2021-09-08T04:42:17.034925Z","shell.execute_reply.started":"2021-09-08T04:42:17.019262Z","shell.execute_reply":"2021-09-08T04:42:17.034171Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# last_layer=pretrained_model3.get_layer('block5_pool')\n# last_output = last_layer.output\n\n# x=tf.keras.layers.Flatten()(last_output)\n# x=tf.keras.layers.Dense(2048,activation='relu')(x)\n# x=tf.keras.layers.Dense(1024,activation='relu')(x)\n# x=tf.keras.layers.Dropout(0.2)(x)\n# x=tf.keras.layers.Dense(256,activation='relu')(x)\n# x=tf.keras.layers.Dropout(0.2)(x)\n# x=tf.keras.layers.Dense(10,activation='sigmoid')(x)\n# # detect and init the TPU\n# # tpu = tf.distribute.cluster_resolver.TPUClusterResolver.connect()\n\n# # # instantiate a distribution strategy\n# # tpu_strategy = tf.distribute.experimental.TPUStrategy(tpu)\n# # with tpu_strategy.scope():\n# model3=tf.keras.Model(pretrained_model3.input,x)\n\n# model3.compile(optimizer=RMSprop(lr=0.0001),\n#               loss='categorical_crossentropy',\n#                metrics=['accuracy','Precision','Recall'])","metadata":{"execution":{"iopub.status.busy":"2021-09-08T04:42:17.036160Z","iopub.execute_input":"2021-09-08T04:42:17.036485Z","iopub.status.idle":"2021-09-08T04:42:17.040780Z","shell.execute_reply.started":"2021-09-08T04:42:17.036451Z","shell.execute_reply":"2021-09-08T04:42:17.039524Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history3=model.fit(train_generator3,validation_data=val_generator3,epochs=30,verbose=2)","metadata":{"execution":{"iopub.status.busy":"2021-09-08T04:42:17.042352Z","iopub.execute_input":"2021-09-08T04:42:17.042843Z","iopub.status.idle":"2021-09-08T07:12:13.314863Z","shell.execute_reply.started":"2021-09-08T04:42:17.042804Z","shell.execute_reply":"2021-09-08T07:12:13.314055Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"acc3 = history3.history['accuracy']\nval_acc3 = history3.history['val_accuracy']\n\ntrain_precision3=history3.history['precision']\nval_precision3=history3.history['val_precision']\n\ntrain_recall3=history3.history['recall']\nval_recall3=history3.history['val_recall']\n\nloss3 = history3.history['loss']\nval_loss3 = history3.history['val_loss']\nepochs = range(len(acc3))\n\nplt.plot(epochs, acc3, 'r', label='Training accuracy')\nplt.plot(epochs, val_acc3, 'b', label='Validation accuracy')\nplt.title('Training and validation accuracy')\nplt.legend()\nplt.figure()\n\nplt.plot(epochs, train_precision3, 'r', label='Training precision')\nplt.plot(epochs, val_precision3, 'b', label='Validation precision')\nplt.title('Training and validation precision')\nplt.legend()\nplt.figure()\n\nplt.plot(epochs, train_recall3, 'r', label='Training recall')\nplt.plot(epochs, val_recall3, 'b', label='Validation recall')\nplt.title('Training and validation recall')\nplt.legend()\nplt.figure()\n\nplt.plot(epochs, loss3, 'r', label='Training Loss')\nplt.plot(epochs, val_loss3, 'b', label='Validation Loss')\nplt.title('Training and validation loss')\nplt.legend()\n\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2021-09-08T07:12:13.316545Z","iopub.execute_input":"2021-09-08T07:12:13.316908Z","iopub.status.idle":"2021-09-08T07:12:13.896010Z","shell.execute_reply.started":"2021-09-08T07:12:13.316871Z","shell.execute_reply":"2021-09-08T07:12:13.895242Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"eval_result3 = model.evaluate_generator(test_generator3)\n# print(eval_result3)\nprint('loss rate at evaluation data :', eval_result3[0])\nprint('accuracy rate at evaluation data :', eval_result3[1])\n\nmodel.save('PNP.h5')","metadata":{"execution":{"iopub.status.busy":"2021-09-08T07:49:47.378047Z","iopub.execute_input":"2021-09-08T07:49:47.378415Z","iopub.status.idle":"2021-09-08T07:49:47.391866Z","shell.execute_reply.started":"2021-09-08T07:49:47.378370Z","shell.execute_reply":"2021-09-08T07:49:47.390460Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\npath =os.listdir(\"../input/state-farm-distracted-driver-detection\")\npath","metadata":{"execution":{"iopub.status.busy":"2021-09-08T07:48:21.021712Z","iopub.execute_input":"2021-09-08T07:48:21.022090Z","iopub.status.idle":"2021-09-08T07:48:21.031197Z","shell.execute_reply.started":"2021-09-08T07:48:21.022061Z","shell.execute_reply":"2021-09-08T07:48:21.029890Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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.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='softmax')\n# ])","metadata":{"execution":{"iopub.status.busy":"2021-09-08T07:12:25.922182Z","iopub.execute_input":"2021-09-08T07:12:25.922591Z","iopub.status.idle":"2021-09-08T07:12:25.928513Z","shell.execute_reply.started":"2021-09-08T07:12:25.922550Z","shell.execute_reply":"2021-09-08T07:12:25.927686Z"},"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-09-08T07:12:25.929764Z","iopub.execute_input":"2021-09-08T07:12:25.930326Z","iopub.status.idle":"2021-09-08T07:12:25.935411Z","shell.execute_reply.started":"2021-09-08T07:12:25.930290Z","shell.execute_reply":"2021-09-08T07:12:25.934499Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# model.summary()","metadata":{"execution":{"iopub.status.busy":"2021-09-08T07:12:25.936947Z","iopub.execute_input":"2021-09-08T07:12:25.937381Z","iopub.status.idle":"2021-09-08T07:12:25.943400Z","shell.execute_reply.started":"2021-09-08T07:12:25.937346Z","shell.execute_reply":"2021-09-08T07:12:25.942607Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Training a model","metadata":{}},{"cell_type":"code","source":"# Ylabels=['drinking', 'safe driving', 'talking to passenger', 'reaching behind', 'operating the radio', 'talking on the phone - right', 'texting - left', 'hair and makeup', 'talking on the phone - left', 'texting - right']","metadata":{"execution":{"iopub.status.busy":"2021-09-08T07:12:25.944791Z","iopub.execute_input":"2021-09-08T07:12:25.945202Z","iopub.status.idle":"2021-09-08T07:12:25.951530Z","shell.execute_reply.started":"2021-09-08T07:12:25.945164Z","shell.execute_reply":"2021-09-08T07:12:25.950451Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# history=model.fit(train_generator,epochs=30,verbose=2)","metadata":{"execution":{"iopub.status.busy":"2021-09-08T07:12:25.952721Z","iopub.execute_input":"2021-09-08T07:12:25.953118Z","iopub.status.idle":"2021-09-08T07:12:25.974348Z","shell.execute_reply.started":"2021-09-08T07:12:25.953084Z","shell.execute_reply":"2021-09-08T07:12:25.973547Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Plotting","metadata":{}},{"cell_type":"code","source":"# acc = history.history['accuracy']\n# val_acc = history.history['val_accuracy']\n\n# train_precision=history.history['precision']\n# val_precision=history.history['val_precision']\n\n# train_recall=history.history['recall']\n# val_recall=history.history['val_recall']\n\n# loss = history.history['loss']\n# val_loss = history.history['val_loss']\n\n# epochs = range(len(acc))\n\n# plt.plot(epochs, acc, 'r', label='Training accuracy')\n# plt.plot(epochs, val_acc, 'b', label='Validation accuracy')\n# plt.title('Training and validation accuracy')\n# plt.legend()\n# plt.figure()\n\n# plt.plot(epochs, train_precision, 'r', label='Training precision')\n# plt.plot(epochs, val_precision, 'b', label='Validation precision')\n# plt.title('Training and validation precision')\n# plt.legend()\n# plt.figure()\n\n# plt.plot(epochs, train_recall, 'r', label='Training recall')\n# plt.plot(epochs, val_recall, 'b', label='Validation recall')\n# plt.title('Training and validation recall')\n# plt.legend()\n# plt.figure()\n\n# plt.plot(epochs, loss, 'r', label='Training Loss')\n# plt.plot(epochs, val_loss, 'b', label='Validation Loss')\n# plt.title('Training and validation loss')\n# plt.legend()\n\n# plt.show()\n","metadata":{"execution":{"iopub.status.busy":"2021-09-08T07:12:25.975618Z","iopub.execute_input":"2021-09-08T07:12:25.976082Z","iopub.status.idle":"2021-09-08T07:12:25.983480Z","shell.execute_reply.started":"2021-09-08T07:12:25.976048Z","shell.execute_reply":"2021-09-08T07:12:25.982683Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# import cv2\n\n# # Resizing the images\n# X, Y = [], []\n\n\n# for 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-09-08T07:12:25.986386Z","iopub.execute_input":"2021-09-08T07:12:25.986621Z","iopub.status.idle":"2021-09-08T07:12:25.992075Z","shell.execute_reply.started":"2021-09-08T07:12:25.986598Z","shell.execute_reply":"2021-09-08T07:12:25.991212Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# X = np.array(X)\n# Y = np.array(Y)","metadata":{"execution":{"iopub.status.busy":"2021-09-08T07:12:25.993534Z","iopub.execute_input":"2021-09-08T07:12:25.993908Z","iopub.status.idle":"2021-09-08T07:12:26.000456Z","shell.execute_reply.started":"2021-09-08T07:12:25.993872Z","shell.execute_reply":"2021-09-08T07:12:25.999596Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Creating model\n","metadata":{}}]}