{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# importing all libraries \nimport numpy as np    \nimport pandas as pd\nimport os \nimport cv2 as cv\nfrom tqdm.notebook import tqdm\nimport tensorflow as tf\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.utils import image_dataset_from_directory\nfrom tensorflow.keras.layers import Conv2D,MaxPooling2D,Dense,Flatten,Rescaling,Dropout\nfrom tensorflow.keras.callbacks import EarlyStopping","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-09-05T05:07:14.398725Z","iopub.execute_input":"2023-09-05T05:07:14.399194Z","iopub.status.idle":"2023-09-05T05:07:14.407574Z","shell.execute_reply.started":"2023-09-05T05:07:14.399163Z","shell.execute_reply":"2023-09-05T05:07:14.406418Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# converting data into train data from image generator\ntrain_data = tf.keras.utils.image_dataset_from_directory(\n  '/kaggle/input/state-farm-distracted-driver-detection/imgs/train',\n  validation_split=0.2,\n  subset=\"training\",\n  seed=123,\n  image_size=(100, 100),\n  batch_size=128,label_mode='categorical',)\n","metadata":{"execution":{"iopub.status.busy":"2023-09-05T05:07:14.412755Z","iopub.execute_input":"2023-09-05T05:07:14.414156Z","iopub.status.idle":"2023-09-05T05:07:19.870547Z","shell.execute_reply.started":"2023-09-05T05:07:14.414112Z","shell.execute_reply":"2023-09-05T05:07:19.869183Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# converting data into validation data from image generator\nval_data = tf.keras.utils.image_dataset_from_directory(\n  '/kaggle/input/state-farm-distracted-driver-detection/imgs/train',\n  validation_split=0.2,\n  subset=\"validation\",\n  seed=123,\n  image_size=(100, 100),\n  batch_size=128,label_mode='categorical',)","metadata":{"execution":{"iopub.status.busy":"2023-09-05T05:07:19.873033Z","iopub.execute_input":"2023-09-05T05:07:19.873402Z","iopub.status.idle":"2023-09-05T05:07:21.594586Z","shell.execute_reply.started":"2023-09-05T05:07:19.873374Z","shell.execute_reply":"2023-09-05T05:07:21.593170Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# showing some of the images\nclasses = train_data.class_names\nimport matplotlib.pyplot as plt\nplt.figure(figsize=(10,10))\nfor images,labels in train_data.take(1):\n    labels = labels.numpy()\n    for i in range(25):\n        ax = plt.subplot(5, 5, i + 1)\n        plt.imshow(images[i].numpy().astype(\"uint8\"))\n        plt.title(classes[labels[i].argmax()])\n        plt.axis(\"off\")","metadata":{"execution":{"iopub.status.busy":"2023-09-05T05:07:21.596420Z","iopub.execute_input":"2023-09-05T05:07:21.596896Z","iopub.status.idle":"2023-09-05T05:07:26.069257Z","shell.execute_reply.started":"2023-09-05T05:07:21.596859Z","shell.execute_reply":"2023-09-05T05:07:26.067757Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# creating our model\nmodel = tf.keras.models.Sequential([\n    Rescaling(scale = 1/255,input_shape=(100,100,3)),\n    Conv2D(32,(3,3),activation='relu'),\n    MaxPooling2D((2,2)),\n    Dropout(0.1),\n    Conv2D(64,(3,3),activation='relu'),\n    MaxPooling2D((2,2)),\n    Conv2D(32,(3,3),activation='relu'),\n    MaxPooling2D((2,2)),\n    Dropout(0.1),\n    Flatten(),\n    Dense(1024,activation='relu'),\n    Dropout(0.1),\n    Dense(512,activation='relu'),\n    \n    Dense(256,activation='relu'),\n    Dropout(0.1),\n    Dense(10,activation='softmax'),\n])\n\n# compiling our model\nmodel.compile(optimizer = Adam(lr=0.01),loss = 'categorical_crossentropy',metrics=['acc'])\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2023-09-05T05:07:26.072807Z","iopub.execute_input":"2023-09-05T05:07:26.073227Z","iopub.status.idle":"2023-09-05T05:07:26.339879Z","shell.execute_reply.started":"2023-09-05T05:07:26.073192Z","shell.execute_reply":"2023-09-05T05:07:26.336912Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# early stopping to stop overfitting\nes = EarlyStopping(monitor='val_acc',min_delta=0.01,patience=2)\n","metadata":{"execution":{"iopub.status.busy":"2023-09-05T05:07:26.342524Z","iopub.execute_input":"2023-09-05T05:07:26.343060Z","iopub.status.idle":"2023-09-05T05:07:26.349179Z","shell.execute_reply.started":"2023-09-05T05:07:26.343015Z","shell.execute_reply":"2023-09-05T05:07:26.347728Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# fitting the model\nhistory = model.fit(train_data,epochs=10,validation_data=val_data,callbacks=[es])","metadata":{"execution":{"iopub.status.busy":"2023-09-05T05:07:26.350572Z","iopub.execute_input":"2023-09-05T05:07:26.350989Z","iopub.status.idle":"2023-09-05T05:28:51.023652Z","shell.execute_reply.started":"2023-09-05T05:07:26.350958Z","shell.execute_reply":"2023-09-05T05:28:51.021841Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# visualizing accuracy and losses\nacc = history.history['acc']\nval_acc = history.history['val_acc']\n\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs_range = history.epoch\n\nplt.figure(figsize=(10,10))\nplt.subplot(1, 2, 1)\nplt.plot(epochs_range, acc, label='Training Accuracy')\nplt.plot(epochs_range, val_acc, label='Validation Accuracy')\nplt.legend(loc='lower right')\nplt.title('Training and Validation Accuracy')\n\nplt.subplot(1, 2, 2)\nplt.plot(epochs_range, loss, label='Training Loss')\nplt.plot(epochs_range, val_loss, label='Validation Loss')\nplt.legend(loc='upper right')\nplt.title('Training and Validation Loss')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-09-05T05:28:51.025163Z","iopub.execute_input":"2023-09-05T05:28:51.025982Z","iopub.status.idle":"2023-09-05T05:28:51.559517Z","shell.execute_reply.started":"2023-09-05T05:28:51.025943Z","shell.execute_reply":"2023-09-05T05:28:51.558219Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# converting training data from image generator for prediction\ntest_data = image_dataset_from_directory(\n    '/kaggle/input/state-farm-distracted-driver-detection/imgs/test',\n    batch_size = 128,\n    image_size=(100,100),\n    labels = None,\n    label_mode=None,\n    shuffle = False\n)","metadata":{"execution":{"iopub.status.busy":"2023-09-05T05:28:51.560948Z","iopub.execute_input":"2023-09-05T05:28:51.561401Z","iopub.status.idle":"2023-09-05T05:33:41.013545Z","shell.execute_reply.started":"2023-09-05T05:28:51.561360Z","shell.execute_reply":"2023-09-05T05:33:41.012224Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# function for predicting images\ndef predict_image(path):\n    img = tf.keras.utils.load_img(path).resize((100,100))\n    img = np.array(img).reshape((1,100,100,3))\n    y = model.predict(img,verbose=False)\n    return y\n    ","metadata":{"execution":{"iopub.status.busy":"2023-09-05T05:33:41.015100Z","iopub.execute_input":"2023-09-05T05:33:41.015453Z","iopub.status.idle":"2023-09-05T05:33:41.023100Z","shell.execute_reply.started":"2023-09-05T05:33:41.015424Z","shell.execute_reply":"2023-09-05T05:33:41.021822Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# predicting some test images\ntest_path = '/kaggle/input/state-farm-distracted-driver-detection/imgs/test'\nplt.figure(figsize=(10,10))\ni=1\nfor img_path in os.listdir(test_path)[:25]:\n    img_path = os.path.join(test_path,img_path)\n    img = tf.keras.utils.load_img(img_path)\n    ax = plt.subplot(5, 5, i)\n    plt.imshow(img)\n    plt.title('c'+str(predict_image(img_path).argmax()))\n    plt.axis(\"off\")\n    i += 1","metadata":{"execution":{"iopub.status.busy":"2023-09-05T05:33:41.026453Z","iopub.execute_input":"2023-09-05T05:33:41.026876Z","iopub.status.idle":"2023-09-05T05:33:47.150144Z","shell.execute_reply.started":"2023-09-05T05:33:41.026837Z","shell.execute_reply":"2023-09-05T05:33:47.149176Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# also use for predicting test data takes more time\n# y = np.zeros((79726,10))\n# test_dir = '/kaggle/input/state-farm-distracted-driver-detection/imgs/test'\n# count = 0\n# for i in tqdm(os.listdir(test_dir)):\n#     path = os.path.join(test_dir,i)\n#     y[count] = predict_image(path)\n#     count += 1","metadata":{"execution":{"iopub.status.busy":"2023-09-05T05:33:47.151473Z","iopub.execute_input":"2023-09-05T05:33:47.152388Z","iopub.status.idle":"2023-09-05T05:33:47.157230Z","shell.execute_reply.started":"2023-09-05T05:33:47.152353Z","shell.execute_reply":"2023-09-05T05:33:47.156260Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#predicting test data given\ny = model.predict(test_data)","metadata":{"execution":{"iopub.status.busy":"2023-09-05T05:33:47.158893Z","iopub.execute_input":"2023-09-05T05:33:47.160245Z","iopub.status.idle":"2023-09-05T05:38:31.682638Z","shell.execute_reply.started":"2023-09-05T05:33:47.160205Z","shell.execute_reply":"2023-09-05T05:38:31.681286Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y.shape","metadata":{"execution":{"iopub.status.busy":"2023-09-05T05:38:31.684432Z","iopub.execute_input":"2023-09-05T05:38:31.684824Z","iopub.status.idle":"2023-09-05T05:38:31.692512Z","shell.execute_reply.started":"2023-09-05T05:38:31.684791Z","shell.execute_reply":"2023-09-05T05:38:31.691313Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# exporting data as given\ndf = pd.DataFrame(y)\ndf.columns = ['c0','c1','c2','c3','c4','c5','c6','c7','c8','c9']\nfilepath = [i.split('/')[-1] for i in test_data.file_paths]\ndf1 = pd.DataFrame(filepath)\ndf1.columns = ['img']\ndf = df1.join(df)\ndf.to_csv('/kaggle/working/output.csv',index=False)","metadata":{"execution":{"iopub.status.busy":"2023-09-05T05:38:31.694056Z","iopub.execute_input":"2023-09-05T05:38:31.694486Z","iopub.status.idle":"2023-09-05T05:38:33.246557Z","shell.execute_reply.started":"2023-09-05T05:38:31.694444Z","shell.execute_reply":"2023-09-05T05:38:33.245457Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.head()","metadata":{"execution":{"iopub.status.busy":"2023-09-05T05:38:33.248596Z","iopub.execute_input":"2023-09-05T05:38:33.249080Z","iopub.status.idle":"2023-09-05T05:38:33.283335Z","shell.execute_reply.started":"2023-09-05T05:38:33.249047Z","shell.execute_reply":"2023-09-05T05:38:33.281782Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}],"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"}}