{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.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":31089,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import numpy as np #linear algebra\nimport pandas as pd # data processing\nimport cv2  # opencv Library\nimport glob\nimport matplotlib.pyplot as plt # plotting library\nimport matplotlib.image as mpimg\nfrom sklearn.model_selection import train_test_split\nimport tensorflow\nimport random\nfrom keras.callbacks import EarlyStopping\nfrom PIL import Image\nimport h5py\nimport os\n\n# look at what's inside Kaggle input folder\nprint(os.listdir(\"/kaggle/input\"))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-20T04:01:41.715939Z","iopub.execute_input":"2025-09-20T04:01:41.716480Z","iopub.status.idle":"2025-09-20T04:01:41.721521Z","shell.execute_reply.started":"2025-09-20T04:01:41.716456Z","shell.execute_reply":"2025-09-20T04:01:41.720761Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":" # Setting Directoy Paths","metadata":{}},{"cell_type":"code","source":"directory='/kaggle/input/state-farm-distracted-driver-detection/imgs/train'\ntest_directory='/kaggle/input/state-farm-distracted-driver-detection/imgs/test/'\nrandom_test = '/kaggle/input/driver/'\n\n\nclasses=['c0','c1','c2','c3','c4','c5','c6','c7','c8','c9']\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-20T04:01:45.532457Z","iopub.execute_input":"2025-09-20T04:01:45.532946Z","iopub.status.idle":"2025-09-20T04:01:45.537071Z","shell.execute_reply.started":"2025-09-20T04:01:45.532923Z","shell.execute_reply":"2025-09-20T04:01:45.536261Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Creating training and testing data","metadata":{}},{"cell_type":"code","source":"training_data = []\ntesting_data = []","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-20T04:01:52.074031Z","iopub.execute_input":"2025-09-20T04:01:52.074312Z","iopub.status.idle":"2025-09-20T04:01:52.078021Z","shell.execute_reply.started":"2025-09-20T04:01:52.074292Z","shell.execute_reply":"2025-09-20T04:01:52.077308Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def create_training_data():\n    for category in classes:\n        path = os.path.join(directory,category)\n        class_num = classes.index(category)\n\n        for img in os.listdir(path):\n            img_array=cv2.imread(os.path.join(path,img),cv2.IMREAD_GRAYSCALE)\n            new_img=cv2.resize(img_array,(240,240))\n            training_data.append([new_img,class_num])\n    ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-20T04:01:53.973066Z","iopub.execute_input":"2025-09-20T04:01:53.973691Z","iopub.status.idle":"2025-09-20T04:01:53.979959Z","shell.execute_reply.started":"2025-09-20T04:01:53.973661Z","shell.execute_reply":"2025-09-20T04:01:53.979127Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def create_testing_data():\n    for img in os.listdir(test_directory):\n        img_array = cv2.imread(os.path.join(test_directory,img),cv2.IMREAD_GRAYSCALE)\n        new_img = cv2.resize(img_array,(240,240))\n        testing_data.append([img,new_img])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-20T04:01:59.233037Z","iopub.execute_input":"2025-09-20T04:01:59.233741Z","iopub.status.idle":"2025-09-20T04:01:59.237744Z","shell.execute_reply.started":"2025-09-20T04:01:59.233719Z","shell.execute_reply":"2025-09-20T04:01:59.236893Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for i in classes:\n    path = os.path.join(directory,i)\n    for img in os.listdir(path):\n        img_array = cv2.imread(os.path.join(path,img),cv2.IMREAD_GRAYSCALE)\n        plt.imshow(img_array,cmap='gray')\n        plt.show()\n        break\n    break\n        ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-20T04:02:02.653022Z","iopub.execute_input":"2025-09-20T04:02:02.653745Z","iopub.status.idle":"2025-09-20T04:02:03.018964Z","shell.execute_reply.started":"2025-09-20T04:02:02.653720Z","shell.execute_reply":"2025-09-20T04:02:03.018291Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"create_training_data()\ncreate_testing_data()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-20T04:02:06.293040Z","iopub.execute_input":"2025-09-20T04:02:06.293581Z","iopub.status.idle":"2025-09-20T04:12:48.943954Z","shell.execute_reply.started":"2025-09-20T04:02:06.293557Z","shell.execute_reply":"2025-09-20T04:12:48.943260Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Shuffling Data","metadata":{}},{"cell_type":"code","source":"random.shuffle(training_data)\nx=[]\ny=[]\nfor features,label in training_data:\n    x.append(features)\n    y.append(label)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-20T04:14:26.055114Z","iopub.execute_input":"2025-09-20T04:14:26.055930Z","iopub.status.idle":"2025-09-20T04:14:26.074567Z","shell.execute_reply.started":"2025-09-20T04:14:26.055903Z","shell.execute_reply":"2025-09-20T04:14:26.073766Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"x[0].shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-20T04:14:32.596228Z","iopub.execute_input":"2025-09-20T04:14:32.596723Z","iopub.status.idle":"2025-09-20T04:14:32.601256Z","shell.execute_reply.started":"2025-09-20T04:14:32.596700Z","shell.execute_reply":"2025-09-20T04:14:32.600528Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"y[0:20]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-20T04:14:35.475483Z","iopub.execute_input":"2025-09-20T04:14:35.476181Z","iopub.status.idle":"2025-09-20T04:14:35.480871Z","shell.execute_reply.started":"2025-09-20T04:14:35.476157Z","shell.execute_reply":"2025-09-20T04:14:35.480083Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Creating Dummies for Target","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras.utils import to_categorical\ny_cat=to_categorical(y,num_classes=10)\ny_cat[0:10]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-20T04:14:37.895224Z","iopub.execute_input":"2025-09-20T04:14:37.895784Z","iopub.status.idle":"2025-09-20T04:14:37.961551Z","shell.execute_reply.started":"2025-09-20T04:14:37.895759Z","shell.execute_reply":"2025-09-20T04:14:37.960930Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Resahping the image to fit the batch size(batch,count,h,w,c)","metadata":{}},{"cell_type":"code","source":"x=np.array(x).reshape(-1,240,240,1)\nx[0].shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-20T04:14:41.655028Z","iopub.execute_input":"2025-09-20T04:14:41.655526Z","iopub.status.idle":"2025-09-20T04:14:42.063460Z","shell.execute_reply.started":"2025-09-20T04:14:41.655505Z","shell.execute_reply":"2025-09-20T04:14:42.062693Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"x.shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-20T04:14:44.655396Z","iopub.execute_input":"2025-09-20T04:14:44.655926Z","iopub.status.idle":"2025-09-20T04:14:44.660816Z","shell.execute_reply.started":"2025-09-20T04:14:44.655901Z","shell.execute_reply":"2025-09-20T04:14:44.660035Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Split into Train and Test","metadata":{}},{"cell_type":"code","source":"x_train,x_test,y_train,y_test=train_test_split(x,y_cat,test_size=0.3,random_state=50)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-20T04:14:49.060139Z","iopub.execute_input":"2025-09-20T04:14:49.060817Z","iopub.status.idle":"2025-09-20T04:14:49.440318Z","shell.execute_reply.started":"2025-09-20T04:14:49.060793Z","shell.execute_reply":"2025-09-20T04:14:49.439514Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(\"Shape of train image is:\",x_train.shape)\nprint(\"Shape of validation images is:\",x_test.shape)\nprint(\"Shape of label is:\",y_train.shape)\nprint(\"Shape of label is:\",y_test.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-20T04:14:51.055489Z","iopub.execute_input":"2025-09-20T04:14:51.056284Z","iopub.status.idle":"2025-09-20T04:14:51.060402Z","shell.execute_reply.started":"2025-09-20T04:14:51.056252Z","shell.execute_reply":"2025-09-20T04:14:51.059638Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Creating model architecture","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras import layers\nfrom tensorflow.keras import models\nfrom tensorflow.keras import optimizers\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.preprocessing.image import img_to_array,load_img\nfrom tensorflow.keras.layers import Conv2D,MaxPooling2D,Flatten,Dense,Dropout,BatchNormalization\nbatch_size=128","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-20T04:14:56.500420Z","iopub.execute_input":"2025-09-20T04:14:56.500721Z","iopub.status.idle":"2025-09-20T04:14:56.506528Z","shell.execute_reply.started":"2025-09-20T04:14:56.500700Z","shell.execute_reply":"2025-09-20T04:14:56.505973Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model = models.Sequential()\n\n# CNN1\nmodel.add(Conv2D(32,(3,3),activation='relu',input_shape=(240,240,1)))\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(32,(3,3),activation='relu',padding='same'))\nmodel.add(BatchNormalization(axis=3))\nmodel.add(MaxPooling2D(pool_size=(2,2),padding='same')) \nmodel.add(Dropout(0.2))\n\n# CNN2\nmodel.add(Conv2D(64,(3,3),activation='relu',padding='same'))\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(64,(3,3),activation='relu',padding='same')) \nmodel.add(BatchNormalization(axis=3))\nmodel.add(MaxPooling2D(pool_size=(2,2),padding='same'))\nmodel.add(Dropout(0.3))\n\n# CNN3\nmodel.add(Conv2D(128,(3,3),activation='relu',padding='same'))\nmodel.add(BatchNormalization()) \nmodel.add(Conv2D(128,(3,3),activation='relu',padding='same')) \nmodel.add(BatchNormalization(axis=3))\nmodel.add(MaxPooling2D(pool_size=(2,2),padding='same'))\nmodel.add(Dropout(0.5)) \n\n#Dense and output\nmodel.add(Flatten())\nmodel.add(Dense(units=512,activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.5))\nmodel.add(Dense(units=128,activation='relu'))                 \nmodel.add(Dropout(0.5))\nmodel.add(Dense(10,activation='softmax'))\n\n\n                 ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-20T04:15:09.516661Z","iopub.execute_input":"2025-09-20T04:15:09.517199Z","iopub.status.idle":"2025-09-20T04:15:09.777727Z","shell.execute_reply.started":"2025-09-20T04:15:09.517177Z","shell.execute_reply":"2025-09-20T04:15:09.777127Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-20T04:15:14.175350Z","iopub.execute_input":"2025-09-20T04:15:14.175682Z","iopub.status.idle":"2025-09-20T04:15:14.203398Z","shell.execute_reply.started":"2025-09-20T04:15:14.175660Z","shell.execute_reply":"2025-09-20T04:15:14.202864Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Compile and fit model","metadata":{}},{"cell_type":"code","source":"model.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['accuracy'])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-20T04:15:20.296391Z","iopub.execute_input":"2025-09-20T04:15:20.296703Z","iopub.status.idle":"2025-09-20T04:15:20.309999Z","shell.execute_reply.started":"2025-09-20T04:15:20.296682Z","shell.execute_reply":"2025-09-20T04:15:20.309365Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.callbacks import EarlyStopping\ncallbacks = [EarlyStopping(monitor='val_accuracy',patience=5)]\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-20T04:15:26.095158Z","iopub.execute_input":"2025-09-20T04:15:26.095772Z","iopub.status.idle":"2025-09-20T04:15:26.101233Z","shell.execute_reply.started":"2025-09-20T04:15:26.095749Z","shell.execute_reply":"2025-09-20T04:15:26.100639Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"results=model.fit(x_train,y_train,batch_size=batch_size,epochs=12,verbose=1,validation_data=(x_test,y_test),callbacks=callbacks)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-20T04:21:41.556006Z","iopub.execute_input":"2025-09-20T04:21:41.556855Z","iopub.status.idle":"2025-09-20T04:26:48.353576Z","shell.execute_reply.started":"2025-09-20T04:21:41.556826Z","shell.execute_reply":"2025-09-20T04:26:48.352954Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(results.history['accuracy'])\nprint(results.history['val_accuracy'])\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-20T04:30:08.921829Z","iopub.execute_input":"2025-09-20T04:30:08.922123Z","iopub.status.idle":"2025-09-20T04:30:08.926625Z","shell.execute_reply.started":"2025-09-20T04:30:08.922103Z","shell.execute_reply":"2025-09-20T04:30:08.925739Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\nplt.plot(results.history['accuracy'], label='Train Accuracy')\nplt.plot(results.history['val_accuracy'], label='Val Accuracy')\nplt.xlabel('Epoch')\nplt.ylabel('Accuracy')\nplt.legend()\nplt.show()\n\nplt.plot(results.history['loss'], label='Train Loss')\nplt.plot(results.history['val_loss'], label='Val Loss')\nplt.xlabel('Epoch')\nplt.ylabel('Loss')\nplt.legend()\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-20T04:30:28.950950Z","iopub.execute_input":"2025-09-20T04:30:28.951188Z","iopub.status.idle":"2025-09-20T04:30:29.257747Z","shell.execute_reply.started":"2025-09-20T04:30:28.951172Z","shell.execute_reply":"2025-09-20T04:30:29.257013Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}