{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":5048,"databundleVersionId":868335,"sourceType":"competition"}],"dockerImageVersionId":30698,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"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\n# for 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":"2024-05-25T10:15:42.778640Z","iopub.execute_input":"2024-05-25T10:15:42.779499Z","iopub.status.idle":"2024-05-25T10:15:42.784884Z","shell.execute_reply.started":"2024-05-25T10:15:42.779462Z","shell.execute_reply":"2024-05-25T10:15:42.783778Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Import Necessary Libraries","metadata":{}},{"cell_type":"code","source":"import os\nimport pandas as pd\nimport cv2\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras import Sequential\nfrom tensorflow.keras.layers import Conv2D\nfrom tensorflow.keras.layers import MaxPool2D\nfrom tensorflow.keras.layers import Dropout\nfrom tensorflow.keras.layers import Flatten\nfrom tensorflow.keras.layers import Dense\nfrom tensorflow.keras.layers import InputLayer\nfrom tensorflow.keras.callbacks import ModelCheckpoint\nfrom tensorflow.keras.callbacks import EarlyStopping","metadata":{"execution":{"iopub.status.busy":"2024-05-25T10:15:42.791792Z","iopub.execute_input":"2024-05-25T10:15:42.792655Z","iopub.status.idle":"2024-05-25T10:15:42.799217Z","shell.execute_reply.started":"2024-05-25T10:15:42.792627Z","shell.execute_reply":"2024-05-25T10:15:42.798024Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Explore the Dataset","metadata":{}},{"cell_type":"code","source":"next(os.walk('/kaggle/input/state-farm-distracted-driver-detection'))","metadata":{"execution":{"iopub.status.busy":"2024-05-25T10:15:42.806850Z","iopub.execute_input":"2024-05-25T10:15:42.807512Z","iopub.status.idle":"2024-05-25T10:15:42.815217Z","shell.execute_reply.started":"2024-05-25T10:15:42.807487Z","shell.execute_reply":"2024-05-25T10:15:42.814229Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"path='/kaggle/input/state-farm-distracted-driver-detection/driver_imgs_list.csv'\ndf=pd.read_csv(path)\ndf.head()","metadata":{"execution":{"iopub.status.busy":"2024-05-25T10:15:43.307810Z","iopub.execute_input":"2024-05-25T10:15:43.308757Z","iopub.status.idle":"2024-05-25T10:15:43.358767Z","shell.execute_reply.started":"2024-05-25T10:15:43.308712Z","shell.execute_reply":"2024-05-25T10:15:43.357701Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"len(df.subject.value_counts().keys())","metadata":{"execution":{"iopub.status.busy":"2024-05-25T10:15:43.452583Z","iopub.execute_input":"2024-05-25T10:15:43.453465Z","iopub.status.idle":"2024-05-25T10:15:43.471012Z","shell.execute_reply.started":"2024-05-25T10:15:43.453428Z","shell.execute_reply":"2024-05-25T10:15:43.469770Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Hence, number of unique drivers is 26","metadata":{}},{"cell_type":"markdown","source":"## Display the Class Paths","metadata":{}},{"cell_type":"code","source":"next(os.walk('/kaggle/input/state-farm-distracted-driver-detection/imgs'))","metadata":{"execution":{"iopub.status.busy":"2024-05-25T10:15:43.473438Z","iopub.execute_input":"2024-05-25T10:15:43.474130Z","iopub.status.idle":"2024-05-25T10:15:43.483118Z","shell.execute_reply.started":"2024-05-25T10:15:43.474094Z","shell.execute_reply":"2024-05-25T10:15:43.482025Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"next(os.walk('/kaggle/input/state-farm-distracted-driver-detection/imgs/train'))","metadata":{"execution":{"iopub.status.busy":"2024-05-25T10:15:43.484181Z","iopub.execute_input":"2024-05-25T10:15:43.484435Z","iopub.status.idle":"2024-05-25T10:15:43.493255Z","shell.execute_reply.started":"2024-05-25T10:15:43.484412Z","shell.execute_reply":"2024-05-25T10:15:43.492230Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class_paths=[]\nfor dirname, _, filenames in os.walk('/kaggle/input/state-farm-distracted-driver-detection/imgs/train'):\n    for a in _:\n        cls_path=os.path.join(dirname, a)\n        print(cls_path)\n        class_paths.append(cls_path)","metadata":{"execution":{"iopub.status.busy":"2024-05-25T10:15:43.496880Z","iopub.execute_input":"2024-05-25T10:15:43.497174Z","iopub.status.idle":"2024-05-25T10:15:50.542364Z","shell.execute_reply.started":"2024-05-25T10:15:43.497150Z","shell.execute_reply":"2024-05-25T10:15:50.541488Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"a,b,c=next(os.walk(class_paths[0]))\na,b,c[:10]","metadata":{"execution":{"iopub.status.busy":"2024-05-25T10:15:50.544152Z","iopub.execute_input":"2024-05-25T10:15:50.544450Z","iopub.status.idle":"2024-05-25T10:15:50.946042Z","shell.execute_reply.started":"2024-05-25T10:15:50.544425Z","shell.execute_reply":"2024-05-25T10:15:50.945096Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Display Sample Image","metadata":{}},{"cell_type":"code","source":"image1=cv2.cvtColor(cv2.imread('/kaggle/input/state-farm-distracted-driver-detection/imgs/train/c5/img_68208.jpg'), cv2.COLOR_BGR2RGB)\nplt.imshow(image1)\nplt.show()\nimage1.shape","metadata":{"execution":{"iopub.status.busy":"2024-05-25T10:15:50.947332Z","iopub.execute_input":"2024-05-25T10:15:50.947633Z","iopub.status.idle":"2024-05-25T10:15:51.376254Z","shell.execute_reply.started":"2024-05-25T10:15:50.947609Z","shell.execute_reply":"2024-05-25T10:15:51.375359Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Prepare Training Data","metadata":{}},{"cell_type":"code","source":"train1=[]\nlabels=[]\nfor class_path in class_paths:\n    a_,b_,c_=next(os.walk(class_path))\n#     print(a_,b_,c_)\n    for c__ in c_:\n        img_path=os.path.join(a_, c__)\n#         print(a_[-1:], img_path)\n        img=cv2.imread(img_path, cv2.IMREAD_COLOR)\n        img=cv2.resize(img, (96,96))\n        train1.append(img)\n        labels.append(int(a_[-1:]))\n#         break","metadata":{"execution":{"iopub.status.busy":"2024-05-25T10:15:51.378733Z","iopub.execute_input":"2024-05-25T10:15:51.379507Z","iopub.status.idle":"2024-05-25T10:18:56.713140Z","shell.execute_reply.started":"2024-05-25T10:15:51.379468Z","shell.execute_reply":"2024-05-25T10:18:56.712162Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.imshow(cv2.cvtColor(train1[0], cv2.COLOR_BGR2RGB))\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-05-25T10:18:56.714409Z","iopub.execute_input":"2024-05-25T10:18:56.714695Z","iopub.status.idle":"2024-05-25T10:18:56.873686Z","shell.execute_reply.started":"2024-05-25T10:18:56.714672Z","shell.execute_reply":"2024-05-25T10:18:56.872345Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(np.array(labels).shape)\nprint(labels[:10])","metadata":{"execution":{"iopub.status.busy":"2024-05-25T10:18:56.876133Z","iopub.execute_input":"2024-05-25T10:18:56.876659Z","iopub.status.idle":"2024-05-25T10:18:56.888475Z","shell.execute_reply.started":"2024-05-25T10:18:56.876611Z","shell.execute_reply":"2024-05-25T10:18:56.887109Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## One-Hot Encoding","metadata":{}},{"cell_type":"code","source":"y = tf.keras.utils.to_categorical(labels, 10)\nprint(type(y))\ny[:10]","metadata":{"execution":{"iopub.status.busy":"2024-05-25T10:18:56.889622Z","iopub.execute_input":"2024-05-25T10:18:56.889910Z","iopub.status.idle":"2024-05-25T10:18:56.908234Z","shell.execute_reply.started":"2024-05-25T10:18:56.889870Z","shell.execute_reply":"2024-05-25T10:18:56.907200Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Normalize Data","metadata":{}},{"cell_type":"code","source":"# train=np.array(train, dtype=np.uint8).reshape(-1, 160, 160, 3)\ntrain=np.array(train1, dtype=np.float32).reshape(-1, 96, 96, 3)\nprint(np.max(train))\ntrain=train/255\nprint(np.max(train))","metadata":{"execution":{"iopub.status.busy":"2024-05-25T10:19:30.004211Z","iopub.execute_input":"2024-05-25T10:19:30.005027Z","iopub.status.idle":"2024-05-25T10:19:31.781967Z","shell.execute_reply.started":"2024-05-25T10:19:30.004994Z","shell.execute_reply":"2024-05-25T10:19:31.781046Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.imshow(cv2.cvtColor(train[0], cv2.COLOR_BGR2RGB))\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-05-25T10:19:37.628907Z","iopub.execute_input":"2024-05-25T10:19:37.629779Z","iopub.status.idle":"2024-05-25T10:19:37.852918Z","shell.execute_reply.started":"2024-05-25T10:19:37.629745Z","shell.execute_reply":"2024-05-25T10:19:37.851273Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"type(train)","metadata":{"execution":{"iopub.status.busy":"2024-05-25T10:19:50.757898Z","iopub.execute_input":"2024-05-25T10:19:50.758663Z","iopub.status.idle":"2024-05-25T10:19:50.764862Z","shell.execute_reply.started":"2024-05-25T10:19:50.758626Z","shell.execute_reply":"2024-05-25T10:19:50.763776Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"set(labels)","metadata":{"execution":{"iopub.status.busy":"2024-05-25T10:19:52.073223Z","iopub.execute_input":"2024-05-25T10:19:52.074149Z","iopub.status.idle":"2024-05-25T10:19:52.081326Z","shell.execute_reply.started":"2024-05-25T10:19:52.074106Z","shell.execute_reply":"2024-05-25T10:19:52.080221Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Split Data into Train and Test Sets","metadata":{}},{"cell_type":"code","source":"X_train, X_test, y_train, y_test=train_test_split(train, y, test_size=0.2, random_state=0, stratify=labels)\nprint(\"Train label distribution:\", np.sum(y_train, axis=0))\nprint(\"Test label distribution:\", np.sum(y_test, axis=0))","metadata":{"execution":{"iopub.status.busy":"2024-05-25T10:19:53.308190Z","iopub.execute_input":"2024-05-25T10:19:53.308878Z","iopub.status.idle":"2024-05-25T10:19:54.041451Z","shell.execute_reply.started":"2024-05-25T10:19:53.308842Z","shell.execute_reply":"2024-05-25T10:19:54.040425Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Build CNN Model","metadata":{}},{"cell_type":"code","source":"model=Sequential()\nmodel.add(InputLayer(shape=(96,96,3)))\n\nmodel.add(Conv2D(128, kernel_size=3, padding='same', activation='relu'))\nmodel.add(MaxPool2D(pool_size=(2, 2)))\n\nmodel.add(Conv2D(128, kernel_size=3, padding='same', activation='relu'))\nmodel.add(MaxPool2D(pool_size=(2, 2)))\n\nmodel.add(Conv2D(256, kernel_size=3, padding='same', activation='relu'))\nmodel.add(MaxPool2D(pool_size=(2, 2)))\n\nmodel.add(Conv2D(512, kernel_size=3, padding='same', activation='relu'))\nmodel.add(MaxPool2D(pool_size=(2, 2)))\n\nmodel.add(Dropout(0.5))\nmodel.add(Flatten())\n\nmodel.add(Dense(500,activation='relu'))\nmodel.add(Dropout(0.5))\n\nmodel.add(Dense(10, activation='softmax'))\n\n","metadata":{"execution":{"iopub.status.busy":"2024-05-25T10:19:55.488270Z","iopub.execute_input":"2024-05-25T10:19:55.488965Z","iopub.status.idle":"2024-05-25T10:19:55.613496Z","shell.execute_reply.started":"2024-05-25T10:19:55.488927Z","shell.execute_reply":"2024-05-25T10:19:55.612637Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"execution":{"iopub.status.busy":"2024-05-25T10:19:59.858115Z","iopub.execute_input":"2024-05-25T10:19:59.859039Z","iopub.status.idle":"2024-05-25T10:19:59.886505Z","shell.execute_reply.started":"2024-05-25T10:19:59.859005Z","shell.execute_reply":"2024-05-25T10:19:59.885486Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Compile the Model","metadata":{}},{"cell_type":"code","source":"model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2024-05-25T10:20:44.189077Z","iopub.execute_input":"2024-05-25T10:20:44.189474Z","iopub.status.idle":"2024-05-25T10:20:44.204706Z","shell.execute_reply.started":"2024-05-25T10:20:44.189446Z","shell.execute_reply":"2024-05-25T10:20:44.203738Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Set Up Callbacks","metadata":{}},{"cell_type":"code","source":"checkpointer=ModelCheckpoint(\n    'saved_models/weights_best_vanilla.keras',\n#     monitor='val_loss',\n    monitor='val_loss',\n    verbose=1,\n    save_best_only=True,\n    mode='auto',\n)","metadata":{"execution":{"iopub.status.busy":"2024-05-25T10:21:18.953758Z","iopub.execute_input":"2024-05-25T10:21:18.954771Z","iopub.status.idle":"2024-05-25T10:21:18.959504Z","shell.execute_reply.started":"2024-05-25T10:21:18.954730Z","shell.execute_reply":"2024-05-25T10:21:18.958436Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"es=EarlyStopping(monitor='val_loss',mode='auto',verbose=1,patience=2,restore_best_weights=True)","metadata":{"execution":{"iopub.status.busy":"2024-05-25T10:24:39.192418Z","iopub.execute_input":"2024-05-25T10:24:39.193201Z","iopub.status.idle":"2024-05-25T10:24:39.198018Z","shell.execute_reply.started":"2024-05-25T10:24:39.193164Z","shell.execute_reply":"2024-05-25T10:24:39.196894Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_train.shape","metadata":{"execution":{"iopub.status.busy":"2024-05-25T10:24:39.742256Z","iopub.execute_input":"2024-05-25T10:24:39.743245Z","iopub.status.idle":"2024-05-25T10:24:39.749684Z","shell.execute_reply.started":"2024-05-25T10:24:39.743212Z","shell.execute_reply":"2024-05-25T10:24:39.748633Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Train the Model","metadata":{}},{"cell_type":"code","source":"# model.fit(\n#     x=X_train,\n#     y=y_train,\n#     batch_size=40,\n#     epochs=10,\n#     verbose=1,\n#     callbacks=[checkpointer, es],\n# #     callbacks=[ checkpointer],\n#     validation_data=(X_test, y_test),\n# #     shuffle=True,\n# )\nmodel.fit(\n    x=X_train,\n    y=y_train,\n    batch_size=40,\n    epochs=10,\n    verbose='auto',\n    callbacks=[checkpointer, es],\n    validation_split=0.1,\n#     validation_data=None,\n    shuffle=True,\n#     class_weight=None,\n#     sample_weight=None,\n#     initial_epoch=0,\n#     steps_per_epoch=None,\n#     validation_steps=None,\n#     validation_batch_size=None,\n#     validation_freq=1\n)","metadata":{"execution":{"iopub.status.busy":"2024-05-25T10:24:40.284209Z","iopub.execute_input":"2024-05-25T10:24:40.284886Z","iopub.status.idle":"2024-05-25T10:25:23.304174Z","shell.execute_reply.started":"2024-05-25T10:24:40.284821Z","shell.execute_reply":"2024-05-25T10:25:23.303180Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Evaluate the Model","metadata":{}},{"cell_type":"code","source":"model.evaluate(X_test, y_test)","metadata":{"execution":{"iopub.status.busy":"2024-05-25T10:27:04.858054Z","iopub.execute_input":"2024-05-25T10:27:04.858829Z","iopub.status.idle":"2024-05-25T10:27:07.030434Z","shell.execute_reply.started":"2024-05-25T10:27:04.858794Z","shell.execute_reply":"2024-05-25T10:27:07.029317Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}