{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":" saved outside of the current session","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"#importing required libraries\nimport csv\nimport numpy as np\nimport pandas as pd\nimport os\nfrom shutil import copyfile\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.callbacks import EarlyStopping\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Dense , Flatten,Dropout\nfrom sklearn.metrics import accuracy_score,precision_score,recall_score,f1_score\nfrom tensorflow.keras import Sequential\nfrom keras.utils.vis_utils import plot_model\nimport matplotlib.pyplot as plt\nimport seaborn as sns","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# mapping image and its class\nimage_class_dic={}\nwith open(\"../input/state-farm-distracted-driver-detection/driver_imgs_list.csv\") as f:\n    reader=csv.reader(f)\n    next(reader)\n    for row in reader:\n        image_class_dic[row[2]]=row[1]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#training directory path\nTRAIN_DIR=\"../input/state-farm-distracted-driver-detection/imgs/train\"\n#creating dict to convert class to its meaning\nclass_name = dict()\nclass_name[\"c0\"] = \"SAFE_DRIVING\"\nclass_name[\"c1\"] = \"TEXTING_RIGHT\"\nclass_name[\"c2\"] = \"TALKING_PHONE_RIGHT\"\nclass_name[\"c3\"] = \"TEXTING_LEFT\"\nclass_name[\"c4\"] = \"TALKING_PHONE_LEFT\"\nclass_name[\"c5\"] = \"OPERATING_RADIO\"\nclass_name[\"c6\"] = \"DRINKING\"\nclass_name[\"c7\"] = \"REACHING_BEHIND\"\nclass_name[\"c8\"] = \"HAIR_AND_MAKEUP\"\nclass_name[\"c9\"] = \"TALKING_TO_PASSENGER\"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#creating model and its architecture and giving lossfunction and optimizer\n\nmodel = Sequential()\n\nmodel.add(Conv2D(filters=64, kernel_size=2, padding='same', activation='relu', input_shape=(100,100,3)))\nmodel.add(MaxPooling2D(pool_size=2))\nmodel.add(Conv2D(filters=128, kernel_size=2, padding='same', activation='relu'))\nmodel.add(MaxPooling2D(pool_size=2))\nmodel.add(Conv2D(filters=256, kernel_size=2, padding='same', activation='relu'))\nmodel.add(MaxPooling2D(pool_size=2))\nmodel.add(Conv2D(filters=512, kernel_size=2, padding='same', activation='relu'))\nmodel.add(MaxPooling2D(pool_size=2))\nmodel.add(Dropout(0.5))\nmodel.add(Flatten())\nmodel.add(Dense(500, activation='relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(10, activation='softmax'))\nmodel.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])\n\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#creating image data generator\n\n\ntrain_datagen = ImageDataGenerator(rescale=1./255,\n    shear_range=0.2,\n    zoom_range=0.2,\n    validation_split=0.2) # set validation split\n\ntrain_generator = train_datagen.flow_from_directory(\n    TRAIN_DIR,\n    target_size=(100, 100),\n    batch_size=120,\n    class_mode='categorical',\n    subset='training') # set as training data\n\nvalidation_generator = train_datagen.flow_from_directory(\n    TRAIN_DIR, # same directory as training data\n    target_size=(100, 100),\n    batch_size=120,\n    class_mode='categorical',\n    subset='validation') # set as validation data\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#if our accuracty is not improving in further steps we are going to stop it early\ncs=EarlyStopping(monitor=\"val_acc\",patience=2,min_delta=0.01)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plot_model(model,show_shapes=True,show_layer_names=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#fitting our model using fit_generator \n#our model history is stored in model_history\n#so that we can see how our model accuracy and loss changed over the concurrent epochs\nmodel_history=model.fit_generator(train_generator,epochs=25,verbose=1,validation_data=validation_generator,callbacks=[cs])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sns.set()\nplt.figure(figsize=(10,7))\nplt.plot(model_history.history[\"accuracy\"],label=\"MODEL_ACCURACY\")\nplt.plot(model_history.history[\"val_accuracy\"],label=\"VALIdATION_ACCURACY\")\nplt.xlabel(\"No. of Epochs\",size=20)\nplt.ylabel(\"Accuracy\",size=20)\nplt.title(\"ACCURACY vs VALIDATION_ACCURACY\",size=20,color='b')\nplt.legend()\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sns.set()\nplt.figure(figsize=(10,7))\nplt.plot(model_history.history[\"loss\"],label=\"LOSS\")\nplt.plot(model_history.history[\"val_loss\"],label=\"VALIDATION_LOSS\")\nplt.xlabel(\"No. of Epochs\",size=20)\nplt.ylabel(\"Loss\",size=20)\nplt.title(\"LOSS vs VALIDATIAON_LOSS\",size=20,color='b')\nplt.legend()\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#THERE IS NO NEED FOR US TO DO SEPARATE TRAINING AND TESTING SINCE WE SPLITTED VALIDATION DATA WHICH IS \n#COMPLETELY DIFFERENT FROM TRAINING DATA\n#or else we can use our validation generator as test ","execution_count":null,"outputs":[]}],"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":4,"nbformat_minor":4}