{"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":"2023-01-21T16:46:55.359613Z","iopub.execute_input":"2023-01-21T16:46:55.360283Z","iopub.status.idle":"2023-01-21T16:49:37.019774Z","shell.execute_reply.started":"2023-01-21T16:46:55.360188Z","shell.execute_reply":"2023-01-21T16:49:37.018616Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.preprocessing import image\nimport tensorflow as tf\nfrom tensorflow.keras import datasets ,layers,models\nimport matplotlib.pyplot as plt\nfrom keras.applications.vgg19 import preprocess_input\nfrom tensorflow.keras.applications import *\nimport dlib\nfrom tensorflow.keras.utils import to_categorical\nimport numpy as np \nimport os \nimport cv2\nfrom keras.applications.vgg16 import VGG16\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten\nfrom keras.layers import Conv2D, MaxPooling2D, BatchNormalization\nfrom tensorflow.keras.utils import Sequence\nfrom keras.utils import data_utils\nimport matplotlib.image as mpimg\nfrom keras.layers.core import Activation\nfrom keras.layers import Conv2D, MaxPooling2D, BatchNormalization\nfrom keras.callbacks import ReduceLROnPlateau\nfrom tensorflow.keras.layers import Input, Add, Dense, Activation, ZeroPadding2D,GlobalAveragePooling2D\n\n\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\n","metadata":{"execution":{"iopub.status.busy":"2023-01-21T16:49:37.022697Z","iopub.execute_input":"2023-01-21T16:49:37.023048Z","iopub.status.idle":"2023-01-21T16:49:43.659888Z","shell.execute_reply.started":"2023-01-21T16:49:37.023014Z","shell.execute_reply":"2023-01-21T16:49:43.658938Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Paths","metadata":{}},{"cell_type":"code","source":"os.getcwd()","metadata":{"execution":{"iopub.status.busy":"2023-01-21T16:49:43.661171Z","iopub.execute_input":"2023-01-21T16:49:43.661943Z","iopub.status.idle":"2023-01-21T16:49:43.675277Z","shell.execute_reply.started":"2023-01-21T16:49:43.661901Z","shell.execute_reply":"2023-01-21T16:49:43.673909Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"DATA_DIR = \"../input/state-farm-distracted-driver-detection/imgs\"\nTEST_DIR = os.path.join(DATA_DIR,\"test\")\nTRAIN_DIR = os.path.join(DATA_DIR,\"train\")\nMODEL_PATH = os.path.join(os.getcwd(),\"model\",\"self_trained\")\nPICKLE_DIR = os.path.join(os.getcwd(),\"pickle_files\")\nCSV_DIR = os.path.join(os.getcwd(),\"csv_files\")","metadata":{"execution":{"iopub.status.busy":"2023-01-21T16:49:43.677061Z","iopub.execute_input":"2023-01-21T16:49:43.677678Z","iopub.status.idle":"2023-01-21T16:49:43.702409Z","shell.execute_reply.started":"2023-01-21T16:49:43.677634Z","shell.execute_reply":"2023-01-21T16:49:43.701502Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"The purpose of this notebook is to identify the driver's physical state, such as safe driving, texting on a phone, drinking, or operating the radio, in order to alert the self-driving system to the fact that the driver's attention may not be fully on the task of driving.","metadata":{}},{"cell_type":"markdown","source":"**Loading Datasets**","metadata":{}},{"cell_type":"code","source":"\ndf= pd.read_csv(\"/kaggle/input/state-farm-distracted-driver-detection/driver_imgs_list.csv\")\ndf.head() \n","metadata":{"execution":{"iopub.status.busy":"2023-01-21T16:49:43.704985Z","iopub.execute_input":"2023-01-21T16:49:43.705918Z","iopub.status.idle":"2023-01-21T16:49:43.765550Z","shell.execute_reply.started":"2023-01-21T16:49:43.705883Z","shell.execute_reply":"2023-01-21T16:49:43.764485Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.shape","metadata":{"execution":{"iopub.status.busy":"2023-01-21T16:49:43.766704Z","iopub.execute_input":"2023-01-21T16:49:43.767000Z","iopub.status.idle":"2023-01-21T16:49:43.772200Z","shell.execute_reply.started":"2023-01-21T16:49:43.766972Z","shell.execute_reply":"2023-01-21T16:49:43.771479Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Exploratory Data Analysis**","metadata":{}},{"cell_type":"code","source":"plt.figure(figsize=(15,12))\nsns.histplot(x=\"classname\", data=df, hue=\"classname\")\n\nplt.show();","metadata":{"execution":{"iopub.status.busy":"2023-01-21T16:49:43.773356Z","iopub.execute_input":"2023-01-21T16:49:43.773852Z","iopub.status.idle":"2023-01-21T16:49:44.435680Z","shell.execute_reply.started":"2023-01-21T16:49:43.773788Z","shell.execute_reply":"2023-01-21T16:49:44.434510Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"activity_map = {'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\n\n\nplt.figure(figsize=(15,12))\ncount=1\npath= '../input/state-farm-distracted-driver-detection/imgs/train/'\nso = os.listdir(\"../input/state-farm-distracted-driver-detection/imgs/train/\")\nfor dirr in so:\n    for i, file in enumerate(os.listdir(path+dirr)):\n        if i==1:\n            break\n        else:\n            fig = plt.subplot(3,4,count)\n            count +=1\n            img= plt.imread(path+ dirr + '/' +file)\n            plt.imshow(img)\n            plt.title(activity_map[dirr])\n","metadata":{"execution":{"iopub.status.busy":"2023-01-21T16:49:44.436925Z","iopub.execute_input":"2023-01-21T16:49:44.437767Z","iopub.status.idle":"2023-01-21T16:49:46.383504Z","shell.execute_reply.started":"2023-01-21T16:49:44.437735Z","shell.execute_reply":"2023-01-21T16:49:46.382481Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Data Preparation**\n\nWe will create a csv file that lists the location and class (if applicable) of the training and test images for easy traceability.","metadata":{}},{"cell_type":"code","source":"def create_csv(DATA_DIR, filename):\n    class_names= os.listdir(DATA_DIR)\n    data = list()\n    if (os.path.isdir(os.path.join(DATA_DIR,class_names[0]))):\n        for class_name in class_names:\n            file_names= os.listdir(os.path.join(DATA_DIR,class_name))\n            for file in file_names:\n                data.append({\"Filename\": os.path.join(DATA_DIR,class_name,file),\"Classname\":class_name})\n    \n    else:\n        class_name= \"test\"\n        file_names= os.listdir(DATA_DIR)\n        for file in file_names:\n            data.append({\"Filename\": os.path.join(DATA_DIR,file),\"Classname\":class_name})\n            \n    data= pd.DataFrame(data)\n    data.to_csv(os.path.join(os.getcwd(), filename),index=False)\n        \n    return data\n        \n        \n            \n    \n    ","metadata":{"execution":{"iopub.status.busy":"2023-01-21T16:49:46.385355Z","iopub.execute_input":"2023-01-21T16:49:46.386215Z","iopub.status.idle":"2023-01-21T16:49:46.396500Z","shell.execute_reply.started":"2023-01-21T16:49:46.386171Z","shell.execute_reply":"2023-01-21T16:49:46.395602Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data_train=create_csv(TRAIN_DIR,\"train.csv\")\ndata_test= create_csv(TEST_DIR, \"test.csv\")","metadata":{"execution":{"iopub.status.busy":"2023-01-21T16:49:46.397937Z","iopub.execute_input":"2023-01-21T16:49:46.398822Z","iopub.status.idle":"2023-01-21T16:49:47.036839Z","shell.execute_reply.started":"2023-01-21T16:49:46.398782Z","shell.execute_reply":"2023-01-21T16:49:47.035894Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"labels_list = list(set(data_train['Classname'].values.tolist()))\nlabels_id = {label_name:int(id) for id,label_name in enumerate(labels_list)}\nprint(labels_id)\ndata_train['Classname'].replace(labels_id,inplace=True)","metadata":{"execution":{"iopub.status.busy":"2023-01-21T16:49:47.038056Z","iopub.execute_input":"2023-01-21T16:49:47.038482Z","iopub.status.idle":"2023-01-21T16:49:47.060976Z","shell.execute_reply.started":"2023-01-21T16:49:47.038452Z","shell.execute_reply":"2023-01-21T16:49:47.060198Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data_train[\"Filename\"].head()","metadata":{"execution":{"iopub.status.busy":"2023-01-21T16:49:47.061913Z","iopub.execute_input":"2023-01-21T16:49:47.062701Z","iopub.status.idle":"2023-01-21T16:49:47.070131Z","shell.execute_reply.started":"2023-01-21T16:49:47.062670Z","shell.execute_reply":"2023-01-21T16:49:47.069065Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data_train = data_train.sample(frac=1)\nsize = data_train.shape[0]\ndf_1 = data_train.copy()\ndf_train = data_train.iloc[:size - int(0.2*size)]\ndf_test = data_train.iloc[size - int(0.2*size):]","metadata":{"execution":{"iopub.status.busy":"2023-01-21T16:49:47.071426Z","iopub.execute_input":"2023-01-21T16:49:47.071767Z","iopub.status.idle":"2023-01-21T16:49:47.082397Z","shell.execute_reply.started":"2023-01-21T16:49:47.071714Z","shell.execute_reply":"2023-01-21T16:49:47.081654Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"size","metadata":{"execution":{"iopub.status.busy":"2023-01-21T16:49:47.086090Z","iopub.execute_input":"2023-01-21T16:49:47.086451Z","iopub.status.idle":"2023-01-21T16:49:47.093044Z","shell.execute_reply.started":"2023-01-21T16:49:47.086411Z","shell.execute_reply":"2023-01-21T16:49:47.092023Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train","metadata":{"execution":{"iopub.status.busy":"2023-01-21T16:49:47.094561Z","iopub.execute_input":"2023-01-21T16:49:47.095082Z","iopub.status.idle":"2023-01-21T16:49:47.109231Z","shell.execute_reply.started":"2023-01-21T16:49:47.095044Z","shell.execute_reply":"2023-01-21T16:49:47.108197Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test","metadata":{"execution":{"iopub.status.busy":"2023-01-21T16:49:47.110667Z","iopub.execute_input":"2023-01-21T16:49:47.110936Z","iopub.status.idle":"2023-01-21T16:49:47.125899Z","shell.execute_reply.started":"2023-01-21T16:49:47.110910Z","shell.execute_reply":"2023-01-21T16:49:47.124833Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data_train['Classname'] = data_train['Classname'].astype('int')","metadata":{"execution":{"iopub.status.busy":"2023-01-21T16:49:47.126804Z","iopub.execute_input":"2023-01-21T16:49:47.127229Z","iopub.status.idle":"2023-01-21T16:49:47.137373Z","shell.execute_reply.started":"2023-01-21T16:49:47.127189Z","shell.execute_reply":"2023-01-21T16:49:47.135912Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_datagen = ImageDataGenerator(rescale=1/255 ,rotation_range = 5, shear_range = 0.02,zoom_range = 0.02,\n                                         samplewise_center=True, samplewise_std_normalization= True)\n    ","metadata":{"execution":{"iopub.status.busy":"2023-01-21T16:49:47.138482Z","iopub.execute_input":"2023-01-21T16:49:47.140992Z","iopub.status.idle":"2023-01-21T16:49:47.152226Z","shell.execute_reply.started":"2023-01-21T16:49:47.140946Z","shell.execute_reply":"2023-01-21T16:49:47.150983Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_generator = train_datagen.flow_from_dataframe(\n    df_train, \n    x_col='Filename',\n    y_col='Classname',\n    directory=None,\n    target_size=(256,256),\n    batch_size=64,\n    class_mode='raw' or 'sparse',\n    shuffle=True\n)\n","metadata":{"execution":{"iopub.status.busy":"2023-01-21T16:49:47.154398Z","iopub.execute_input":"2023-01-21T16:49:47.154922Z","iopub.status.idle":"2023-01-21T16:49:57.645478Z","shell.execute_reply.started":"2023-01-21T16:49:47.154870Z","shell.execute_reply":"2023-01-21T16:49:57.644351Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"valid_generator = train_datagen.flow_from_dataframe(\n    df_test, \n    x_col='Filename',\n    y_col='Classname',\n    directory=None,\n    target_size=(256,256),\n    batch_size=64,\n    class_mode='raw' or 'sparse',\n    shuffle=True\n)\n","metadata":{"execution":{"iopub.status.busy":"2023-01-21T16:49:57.648756Z","iopub.execute_input":"2023-01-21T16:49:57.649291Z","iopub.status.idle":"2023-01-21T16:50:00.643630Z","shell.execute_reply.started":"2023-01-21T16:49:57.649258Z","shell.execute_reply":"2023-01-21T16:50:00.642760Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Model**","metadata":{}},{"cell_type":"code","source":"DIM = 256\nNB_CHANNELS = 3\nNB_CLASSES = 10","metadata":{"execution":{"iopub.status.busy":"2023-01-21T16:50:00.644725Z","iopub.execute_input":"2023-01-21T16:50:00.645535Z","iopub.status.idle":"2023-01-21T16:50:00.650150Z","shell.execute_reply.started":"2023-01-21T16:50:00.645497Z","shell.execute_reply":"2023-01-21T16:50:00.649161Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"base_model = Sequential()\nbase_model.add(Conv2D(32, (3, 3), padding=\"same\",input_shape = (DIM , DIM , NB_CHANNELS)))\nbase_model.add(Activation(\"relu\"))\nbase_model.add(BatchNormalization(axis=1))\nbase_model.add(MaxPooling2D(pool_size=(3, 3)))\nbase_model.add(Conv2D(64, (3, 3), padding=\"same\"))\nbase_model.add(Activation(\"relu\"))\nbase_model.add(BatchNormalization(axis=1))\nbase_model.add(Conv2D(64, (3, 3), padding=\"same\"))\nbase_model.add(Activation(\"relu\"))\nbase_model.add(BatchNormalization(axis=1))\nbase_model.add(MaxPooling2D(pool_size=(2, 2)))\nbase_model.add(Conv2D(128, (3, 3), padding=\"same\"))\nbase_model.add(Activation(\"relu\"))\nbase_model.add(BatchNormalization(axis=1))\nbase_model.add(Conv2D(128, (3, 3), padding=\"same\"))\nbase_model.add(Activation(\"relu\"))\nbase_model.add(BatchNormalization(axis=1))\nbase_model.add(MaxPooling2D(pool_size=(2, 2)))\nbase_model.add(Flatten())\nbase_model.add(Dense(1024))\nbase_model.add(Activation(\"relu\"))\nbase_model.add(BatchNormalization())\nbase_model.add(Dense(10))\nbase_model.add(Activation(\"softmax\"))\nbase_model.build((0,256,256,3))\nbase_model.summary()","metadata":{"execution":{"iopub.status.busy":"2023-01-21T16:50:00.651233Z","iopub.execute_input":"2023-01-21T16:50:00.651527Z","iopub.status.idle":"2023-01-21T16:50:01.421333Z","shell.execute_reply.started":"2023-01-21T16:50:00.651500Z","shell.execute_reply":"2023-01-21T16:50:01.418985Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"learning_rate_reduction = ReduceLROnPlateau(monitor='accuracy',\n                                            patience = 2,\n                                            verbose=1,\n                                            factor=0.1,\n                                            min_lr=0.000001)\n\nopt = tf.keras.optimizers.Adam(learning_rate=0.0001)\n\n\nbase_model.compile(optimizer = opt, loss='sparse_categorical_crossentropy', metrics=['accuracy'])\nhistory = base_model.fit(train_generator,validation_data = valid_generator, epochs = 3,callbacks=[learning_rate_reduction])","metadata":{"execution":{"iopub.status.busy":"2023-01-21T16:50:01.422865Z","iopub.execute_input":"2023-01-21T16:50:01.423278Z","iopub.status.idle":"2023-01-21T18:12:42.843633Z","shell.execute_reply.started":"2023-01-21T16:50:01.423238Z","shell.execute_reply":"2023-01-21T18:12:42.842695Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport numpy as np\n\nepochs=np.arange(3)\nplt.plot(epochs, history.history[\"loss\"], label=\"Test\" )\nplt.plot(epochs, history.history [\"val_loss\"], label=\"Validation\")\nplt.legend()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-01-21T18:45:28.370727Z","iopub.execute_input":"2023-01-21T18:45:28.371788Z","iopub.status.idle":"2023-01-21T18:45:28.780779Z","shell.execute_reply.started":"2023-01-21T18:45:28.371739Z","shell.execute_reply":"2023-01-21T18:45:28.779846Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"epochs=np.arange(3)\nplt.plot(epochs, history.history[\"accuracy\"], label=\"Test\" )\nplt.plot(epochs, history.history [\"val_accuracy\"], label=\"Validation\")\nplt.legend()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-01-21T18:45:59.827173Z","iopub.execute_input":"2023-01-21T18:45:59.827786Z","iopub.status.idle":"2023-01-21T18:46:00.054742Z","shell.execute_reply.started":"2023-01-21T18:45:59.827750Z","shell.execute_reply":"2023-01-21T18:46:00.053697Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"image = plt.imread(\"../input/state-farm-distracted-driver-detection/imgs/train/c0/img_101175.jpg\")\nplt.imshow(image)\n","metadata":{"execution":{"iopub.status.busy":"2023-01-21T18:46:35.777639Z","iopub.execute_input":"2023-01-21T18:46:35.778016Z","iopub.status.idle":"2023-01-21T18:46:36.083248Z","shell.execute_reply.started":"2023-01-21T18:46:35.777988Z","shell.execute_reply":"2023-01-21T18:46:36.082234Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"img = cv2.resize(image, (256, 256)) \nimg = img.reshape(1,256,256,3)\nimg.shape","metadata":{"execution":{"iopub.status.busy":"2023-01-21T18:46:59.212524Z","iopub.execute_input":"2023-01-21T18:46:59.212947Z","iopub.status.idle":"2023-01-21T18:46:59.220784Z","shell.execute_reply.started":"2023-01-21T18:46:59.212912Z","shell.execute_reply":"2023-01-21T18:46:59.219684Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ypred = base_model.predict(img/255)\nprint(ypred)\n","metadata":{"execution":{"iopub.status.busy":"2023-01-21T18:47:23.401822Z","iopub.execute_input":"2023-01-21T18:47:23.402823Z","iopub.status.idle":"2023-01-21T18:47:23.708282Z","shell.execute_reply.started":"2023-01-21T18:47:23.402787Z","shell.execute_reply":"2023-01-21T18:47:23.707521Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ypred_class = np.argmax(ypred,axis=1)\nypred_class","metadata":{"execution":{"iopub.status.busy":"2023-01-21T18:47:26.134464Z","iopub.execute_input":"2023-01-21T18:47:26.135477Z","iopub.status.idle":"2023-01-21T18:47:26.142569Z","shell.execute_reply.started":"2023-01-21T18:47:26.135410Z","shell.execute_reply":"2023-01-21T18:47:26.141880Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}