{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.7.9","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":5048,"databundleVersionId":868335,"sourceType":"competition"},{"sourceId":10030171,"sourceType":"datasetVersion","datasetId":6177376},{"sourceId":10123614,"sourceType":"datasetVersion","datasetId":6247065}],"dockerImageVersionId":30066,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# IMPORTING THE LIBRARIES","metadata":{}},{"cell_type":"code","source":"import os\nimport pandas as pd\nimport pickle\nimport numpy as np\nimport seaborn as sns\nfrom sklearn.datasets import load_files\nfrom keras.utils import np_utils\nimport matplotlib.pyplot as plt\nfrom keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D\nfrom keras.layers import Dropout, Flatten, Dense\nfrom keras.models import Sequential\nfrom keras.utils.vis_utils import plot_model\nfrom keras.callbacks import ModelCheckpoint\nfrom keras.utils import to_categorical\nfrom sklearn.metrics import confusion_matrix\nfrom keras.preprocessing import image                  \nfrom tqdm import tqdm\n\nimport seaborn as sns\nfrom sklearn.metrics import accuracy_score,precision_score,recall_score,f1_score","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T07:40:15.502500Z","iopub.execute_input":"2024-12-07T07:40:15.502888Z","iopub.status.idle":"2024-12-07T07:40:23.134804Z","shell.execute_reply.started":"2024-12-07T07:40:15.502806Z","shell.execute_reply":"2024-12-07T07:40:23.133805Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Pretty display for notebooks\n%matplotlib inline","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T07:40:23.136512Z","iopub.execute_input":"2024-12-07T07:40:23.136988Z","iopub.status.idle":"2024-12-07T07:40:23.143876Z","shell.execute_reply.started":"2024-12-07T07:40:23.136944Z","shell.execute_reply":"2024-12-07T07:40:23.142884Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!ls","metadata":{"scrolled":true,"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T07:40:25.445912Z","iopub.execute_input":"2024-12-07T07:40:25.446273Z","iopub.status.idle":"2024-12-07T07:40:26.636914Z","shell.execute_reply.started":"2024-12-07T07:40:25.446244Z","shell.execute_reply":"2024-12-07T07:40:26.635568Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Defining the train,test and model directories\n\nWe will create the directories for train,test and model training paths if not present","metadata":{}},{"cell_type":"code","source":"DATA_DIR = \"/kaggle/input/mergeddriver/MergedDriver\"\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":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T07:40:28.788387Z","iopub.execute_input":"2024-12-07T07:40:28.788834Z","iopub.status.idle":"2024-12-07T07:40:28.795133Z","shell.execute_reply.started":"2024-12-07T07:40:28.788795Z","shell.execute_reply":"2024-12-07T07:40:28.794049Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"if not os.path.exists(TEST_DIR):\n    print(\"Testing data does not exists\")\nif not os.path.exists(TRAIN_DIR):\n    print(\"Training data does not exists\")\nif not os.path.exists(MODEL_PATH):\n    print(\"Model path does not exists\")\n    os.makedirs(MODEL_PATH)\n    print(\"Model path created\")\nif not os.path.exists(PICKLE_DIR):\n    os.makedirs(PICKLE_DIR)\nif not os.path.exists(CSV_DIR):\n    os.makedirs(CSV_DIR)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T07:40:31.497996Z","iopub.execute_input":"2024-12-07T07:40:31.498377Z","iopub.status.idle":"2024-12-07T07:40:31.511291Z","shell.execute_reply.started":"2024-12-07T07:40:31.498348Z","shell.execute_reply":"2024-12-07T07:40:31.510152Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Data Preparation","metadata":{}},{"cell_type":"markdown","source":"We will create a csv file having the location of the files present for training and test images and their associated class if present so that it is easily traceable.","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({\n                    \"Filename\":os.path.join(DATA_DIR,class_name,file),\n                    \"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(({\n                \"FileName\":os.path.join(DATA_DIR,file),\n                \"ClassName\":class_name\n            }))\n    data = pd.DataFrame(data)\n    data.to_csv(os.path.join(os.getcwd(),\"csv_files\",filename),index=False)\n\ncreate_csv(TRAIN_DIR,\"train.csv\")\ncreate_csv(TEST_DIR,\"test.csv\")\ndata_train = pd.read_csv(os.path.join(os.getcwd(),\"csv_files\",\"train.csv\"))\ndata_test = pd.read_csv(os.path.join(os.getcwd(),\"csv_files\",\"test.csv\"))\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T07:40:36.004084Z","iopub.execute_input":"2024-12-07T07:40:36.004388Z","iopub.status.idle":"2024-12-07T07:40:36.932801Z","shell.execute_reply.started":"2024-12-07T07:40:36.004363Z","shell.execute_reply":"2024-12-07T07:40:36.931905Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"data_train.info()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T07:40:37.723169Z","iopub.execute_input":"2024-12-07T07:40:37.723456Z","iopub.status.idle":"2024-12-07T07:40:37.753463Z","shell.execute_reply.started":"2024-12-07T07:40:37.723432Z","shell.execute_reply":"2024-12-07T07:40:37.752394Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"data_train['ClassName'].value_counts()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T07:40:39.751327Z","iopub.execute_input":"2024-12-07T07:40:39.751636Z","iopub.status.idle":"2024-12-07T07:40:39.767216Z","shell.execute_reply.started":"2024-12-07T07:40:39.751611Z","shell.execute_reply":"2024-12-07T07:40:39.766150Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"data_train.describe()","metadata":{"scrolled":true,"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T07:40:48.231016Z","iopub.execute_input":"2024-12-07T07:40:48.231347Z","iopub.status.idle":"2024-12-07T07:40:48.340861Z","shell.execute_reply.started":"2024-12-07T07:40:48.231320Z","shell.execute_reply":"2024-12-07T07:40:48.339780Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\n\nnf = data_train['ClassName'].value_counts(sort=False)\nlabels = data_train['ClassName'].value_counts(sort=False).index.tolist()\ny = np.array(nf)\nwidth = 1/1.5\nN = len(y)\nx = range(N)\n\nfig = plt.figure(figsize=(20,15))\nay = fig.add_subplot(211)\n\nplt.xticks(x, labels, size=15)\nplt.yticks(size=15)\n\nay.bar(x, y, width, color=\"blue\")\n\nplt.title('Bar Chart',size=25)\nplt.xlabel('classname',size=15)\nplt.ylabel('Count',size=15)\n\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T07:40:58.105551Z","iopub.execute_input":"2024-12-07T07:40:58.105960Z","iopub.status.idle":"2024-12-07T07:40:58.330023Z","shell.execute_reply.started":"2024-12-07T07:40:58.105931Z","shell.execute_reply":"2024-12-07T07:40:58.328951Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"data_test.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T07:41:03.504144Z","iopub.execute_input":"2024-12-07T07:41:03.504501Z","iopub.status.idle":"2024-12-07T07:41:03.515179Z","shell.execute_reply.started":"2024-12-07T07:41:03.504476Z","shell.execute_reply":"2024-12-07T07:41:03.513598Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"data_test.shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T07:41:06.124314Z","iopub.execute_input":"2024-12-07T07:41:06.124610Z","iopub.status.idle":"2024-12-07T07:41:06.130837Z","shell.execute_reply.started":"2024-12-07T07:41:06.124584Z","shell.execute_reply":"2024-12-07T07:41:06.129902Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Observation:\n1. There are total 22424 training samples\n2. There are total 79726 testing samples\n3. The training dataset is equally balanced to a great extent and hence we need not do any downsampling of the data","metadata":{}},{"cell_type":"markdown","source":"## Converting into numerical values","metadata":{}},{"cell_type":"code","source":"labels_list = list(set(data_train['ClassName'].values.tolist()))\nlabels_id = {label_name:id for id,label_name in enumerate(labels_list)}\nprint(labels_id)\ndata_train['ClassName'].replace(labels_id,inplace=True)\ndata_test['ClassName'].replace(labels_id,inplace=True)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T07:41:38.929190Z","iopub.execute_input":"2024-12-07T07:41:38.929504Z","iopub.status.idle":"2024-12-07T07:41:38.986005Z","shell.execute_reply.started":"2024-12-07T07:41:38.929480Z","shell.execute_reply":"2024-12-07T07:41:38.984546Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"with open(os.path.join(os.getcwd(),\"pickle_files\",\"labels_list.pkl\"),\"wb\") as handle:\n    pickle.dump(labels_id,handle)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T07:41:49.055847Z","iopub.execute_input":"2024-12-07T07:41:49.056165Z","iopub.status.idle":"2024-12-07T07:41:49.062632Z","shell.execute_reply.started":"2024-12-07T07:41:49.056139Z","shell.execute_reply":"2024-12-07T07:41:49.060813Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"labels = to_categorical(data_train['ClassName'])\nprint(labels.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T07:41:54.878579Z","iopub.execute_input":"2024-12-07T07:41:54.878936Z","iopub.status.idle":"2024-12-07T07:41:54.887752Z","shell.execute_reply.started":"2024-12-07T07:41:54.878907Z","shell.execute_reply":"2024-12-07T07:41:54.886743Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"labels_test = to_categorical(data_test['ClassName'])\nprint(labels_test.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T07:42:19.828389Z","iopub.execute_input":"2024-12-07T07:42:19.828743Z","iopub.status.idle":"2024-12-07T07:42:19.834725Z","shell.execute_reply.started":"2024-12-07T07:42:19.828714Z","shell.execute_reply":"2024-12-07T07:42:19.833427Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Splitting into Train and Test sets","metadata":{}},{"cell_type":"code","source":"xtrain = data_train['Filename']  # Paths to training images\nytrain = labels                  # One-hot encoded labels for training\n\nxtest = data_test['Filename']    # Paths to testing images\nytest = labels_test              # One-hot encoded labels for testing\n\n# Verify the shapes\nprint(\"xtrain shape:\", xtrain.shape)\nprint(\"ytrain shape:\", ytrain.shape)\nprint(\"xtest shape:\", xtest.shape)\nprint(\"ytest shape:\", ytest.shape)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T08:01:09.210491Z","iopub.execute_input":"2024-12-07T08:01:09.210874Z","iopub.status.idle":"2024-12-07T08:01:09.217845Z","shell.execute_reply.started":"2024-12-07T08:01:09.210840Z","shell.execute_reply":"2024-12-07T08:01:09.216296Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### Converting into 64*64 images \nYou can substitute 64,64 to 224,224 for better results only if ram is >32gb","metadata":{}},{"cell_type":"code","source":"\ndef path_to_tensor(img_path):\n    # loads RGB image as PIL.Image.Image type\n    img = image.load_img(img_path, target_size=(64, 64))\n    # convert PIL.Image.Image type to 3D tensor with shape (64, 64, 3)\n    x = image.img_to_array(img)\n    # convert 3D tensor to 4D tensor with shape (1, 64,64, 3) and return 4D tensor\n    return np.expand_dims(x, axis=0)\n\ndef paths_to_tensor(img_paths):\n    list_of_tensors = [path_to_tensor(img_path) for img_path in tqdm(img_paths)]\n    return np.vstack(list_of_tensors)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T08:02:23.046426Z","iopub.execute_input":"2024-12-07T08:02:23.046810Z","iopub.status.idle":"2024-12-07T08:02:23.053210Z","shell.execute_reply.started":"2024-12-07T08:02:23.046777Z","shell.execute_reply":"2024-12-07T08:02:23.051515Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\nfrom PIL import ImageFile                            \nImageFile.LOAD_TRUNCATED_IMAGES = True                 \n\n# pre-process the data for Keras\ntrain_tensors = paths_to_tensor(xtrain).astype('float32')/255 - 0.5\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T08:02:25.896266Z","iopub.execute_input":"2024-12-07T08:02:25.896618Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Defining the Model","metadata":{}},{"cell_type":"code","source":"##takes too much ram \n## run this if your ram is greater than 16gb \ntest_tensors = paths_to_tensor(data_test.iloc[:,0]).astype('float32')/255 - 0.5 ","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model = Sequential()\n\nmodel.add(Conv2D(filters=64, kernel_size=2, padding='same', activation='relu', input_shape=(64,64,3), kernel_initializer='glorot_normal'))\nmodel.add(MaxPooling2D(pool_size=2))\nmodel.add(Conv2D(filters=128, kernel_size=2, padding='same', activation='relu', kernel_initializer='glorot_normal'))\nmodel.add(MaxPooling2D(pool_size=2))\nmodel.add(Conv2D(filters=256, kernel_size=2, padding='same', activation='relu', kernel_initializer='glorot_normal'))\nmodel.add(MaxPooling2D(pool_size=2))\nmodel.add(Conv2D(filters=512, kernel_size=2, padding='same', activation='relu', kernel_initializer='glorot_normal'))\nmodel.add(MaxPooling2D(pool_size=2))\nmodel.add(Dropout(0.5))\nmodel.add(Flatten())\nmodel.add(Dense(500, activation='relu', kernel_initializer='glorot_normal'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(10, activation='softmax', kernel_initializer='glorot_normal'))\n\n\nmodel.summary()","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plot_model(model,to_file=os.path.join(MODEL_PATH,\"model_distracted_driver.png\"),show_shapes=True,show_layer_names=True)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T08:54:46.160876Z","iopub.status.idle":"2024-12-07T08:54:46.161321Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T08:54:46.162341Z","iopub.status.idle":"2024-12-07T08:54:46.162774Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"filepath = os.path.join(MODEL_PATH,\"distracted-{epoch:02d}-{val_accuracy:.2f}.hdf5\")\ncheckpoint = ModelCheckpoint(filepath, monitor='val_accuracy', verbose=1, save_best_only=True, mode='max',period=1)\ncallbacks_list = [checkpoint]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T08:54:46.163905Z","iopub.status.idle":"2024-12-07T08:54:46.164301Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model_history = model.fit(train_tensors,ytrain,validation_data = (test_tensors, ytest),epochs=25, batch_size=40, shuffle=True,callbacks=callbacks_list)","metadata":{"scrolled":true,"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T08:55:02.831678Z","iopub.execute_input":"2024-12-07T08:55:02.832200Z","iopub.status.idle":"2024-12-07T14:31:50.510378Z","shell.execute_reply.started":"2024-12-07T08:55:02.832146Z","shell.execute_reply":"2024-12-07T14:31:50.506934Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 12))\nax1.plot(model_history.history['loss'], color='b', label=\"Training loss\")\nax1.plot(model_history.history['val_loss'], color='r', label=\"Validation loss\")\nax1.set_xticks(np.arange(1, 25, 1))\nax1.set_yticks(np.arange(0, 1, 0.1))\n\nax2.plot(model_history.history['accuracy'], color='b', label=\"Training accuracy\")\nax2.plot(model_history.history['val_accuracy'], color='r',label=\"Validation accuracy\")\nax2.set_xticks(np.arange(1, 25, 1))\n\nlegend = plt.legend(loc='best', shadow=True)\nplt.tight_layout()\nplt.show()","metadata":{"scrolled":true,"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T14:31:50.516910Z","iopub.execute_input":"2024-12-07T14:31:50.517353Z","iopub.status.idle":"2024-12-07T14:31:50.992208Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Model Analysis\n\nFinding the Confusion matrix,Precision,Recall and F1 score to analyse the model thus created ","metadata":{}},{"cell_type":"code","source":"\ndef print_confusion_matrix(confusion_matrix, class_names, figsize = (10,7), fontsize=14):\n    df_cm = pd.DataFrame(\n        confusion_matrix, index=class_names, columns=class_names, \n    )\n    fig = plt.figure(figsize=figsize)\n    try:\n        heatmap = sns.heatmap(df_cm, annot=True, fmt=\"d\")\n    except ValueError:\n        raise ValueError(\"Confusion matrix values must be integers.\")\n    heatmap.yaxis.set_ticklabels(heatmap.yaxis.get_ticklabels(), rotation=0, ha='right', fontsize=fontsize)\n    heatmap.xaxis.set_ticklabels(heatmap.xaxis.get_ticklabels(), rotation=45, ha='right', fontsize=fontsize)\n    plt.ylabel('True label')\n    plt.xlabel('Predicted label')\n    fig.savefig(os.path.join(MODEL_PATH,\"confusion_matrix.png\"))\n    return fig\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T14:31:51.011381Z","iopub.execute_input":"2024-12-07T14:31:51.011656Z","iopub.status.idle":"2024-12-07T14:31:51.019178Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def print_heatmap(n_labels, n_predictions, class_names):\n    labels = n_labels #sess.run(tf.argmax(n_labels, 1))\n    predictions = n_predictions #sess.run(tf.argmax(n_predictions, 1))\n\n#     confusion_matrix = sess.run(tf.contrib.metrics.confusion_matrix(labels, predictions))\n    matrix = confusion_matrix(labels.argmax(axis=1),predictions.argmax(axis=1))\n    row_sum = np.sum(matrix, axis = 1)\n    w, h = matrix.shape\n\n    c_m = np.zeros((w, h))\n\n    for i in range(h):\n        c_m[i] = matrix[i] * 100 / row_sum[i]\n\n    c = c_m.astype(dtype = np.uint8)\n\n    \n    heatmap = print_confusion_matrix(c, class_names, figsize=(18,10), fontsize=20)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T14:31:51.021054Z","iopub.execute_input":"2024-12-07T14:31:51.021532Z","iopub.status.idle":"2024-12-07T14:31:51.032551Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class_names = list()\nfor name,idx in labels_id.items():\n    class_names.append(name)\nypred = model.predict(test_tensors)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T14:31:51.034448Z","iopub.execute_input":"2024-12-07T14:31:51.034954Z","iopub.status.idle":"2024-12-07T14:32:33.403092Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print_heatmap(ytest,ypred,class_names)","metadata":{"scrolled":true,"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T14:32:33.405441Z","iopub.execute_input":"2024-12-07T14:32:33.405964Z","iopub.status.idle":"2024-12-07T14:32:34.368819Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Precision Recall F1 Score","metadata":{}},{"cell_type":"code","source":"ypred_class = np.argmax(ypred,axis=1)\n# print(ypred_class[:10])\nytest = np.argmax(ytest,axis=1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T14:32:34.370432Z","iopub.execute_input":"2024-12-07T14:32:34.370920Z","iopub.status.idle":"2024-12-07T14:32:34.377328Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"accuracy = accuracy_score(ytest,ypred_class)\nprint('Accuracy: %f' % accuracy)\n# precision tp / (tp + fp)\nprecision = precision_score(ytest, ypred_class,average='weighted')\nprint('Precision: %f' % precision)\n# recall: tp / (tp + fn)\nrecall = recall_score(ytest,ypred_class,average='weighted')\nprint('Recall: %f' % recall)\n# f1: 2 tp / (2 tp + fp + fn)\nf1 = f1_score(ytest,ypred_class,average='weighted')\nprint('F1 score: %f' % f1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T14:32:34.379377Z","iopub.execute_input":"2024-12-07T14:32:34.379894Z","iopub.status.idle":"2024-12-07T14:32:34.410175Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nfrom tensorflow.keras.preprocessing.image import img_to_array, load_img\nimport tensorflow as tf\n\n# Preprocessing function similar to paths_to_tensor\ndef preprocess_image(image_path):\n    img = load_img(image_path, target_size=(64, 64))  # Replace with your model's input size\n    img_array = img_to_array(img).astype('float32') / 255.0 - 0.5  # Normalize and center\n    img_array = np.expand_dims(img_array, axis=0)  # Add batch dimension\n    return img_array\n\n# Testing function\ndef test_image(image_path, model, labels_list):\n    img_tensor = preprocess_image(image_path)\n\n    # Predict\n    predictions = model.predict(img_tensor)\n    predicted_class = np.argmax(predictions, axis=1)[0]\n    predicted_label = labels_list[predicted_class]\n\n    return predicted_label\n\n\nimage_path = \"/kaggle/input/driver-detection/Driver/v2_cam1_cam2_ split_by_driver/Camera 2/test/c0/13310.jpg\"\n\n\n# Predict\npredicted_label = test_image(image_path, model, labels_list)\nprint(f\"The predicted label for the image is: {predicted_label}\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T14:32:34.411214Z","iopub.execute_input":"2024-12-07T14:32:34.411454Z","iopub.status.idle":"2024-12-07T14:32:34.545555Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Assuming `model` is your trained Keras model\nmodel.save('model.h5')  # Saves the model in HDF5 format\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T14:40:47.659085Z","iopub.execute_input":"2024-12-07T14:40:47.659564Z","iopub.status.idle":"2024-12-07T14:40:47.744622Z","shell.execute_reply.started":"2024-12-07T14:40:47.659523Z","shell.execute_reply":"2024-12-07T14:40:47.743533Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Assuming `model` is your trained Keras model\nmodel.save('/kaggle/working/saved_model_directory')  # Saves the model in SavedModel format\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T14:43:47.066504Z","iopub.execute_input":"2024-12-07T14:43:47.066918Z","iopub.status.idle":"2024-12-07T14:43:49.728739Z","shell.execute_reply.started":"2024-12-07T14:43:47.066890Z","shell.execute_reply":"2024-12-07T14:43:49.727504Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import tensorflow as tf\n\n# Load the trained model\nmodel = tf.keras.models.load_model('/kaggle/working/model.h5')  # Adjust the path and format as needed\n\n# Convert the model to TensorFlow Lite format\nconverter = tf.lite.TFLiteConverter.from_keras_model(model)\ntflite_model = converter.convert()\n\n# Save the .tflite model\nwith open('model.tflite', 'wb') as f:\n    f.write(tflite_model)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T14:45:00.566365Z","iopub.execute_input":"2024-12-07T14:45:00.566887Z","iopub.status.idle":"2024-12-07T14:45:03.072256Z","shell.execute_reply.started":"2024-12-07T14:45:00.566851Z","shell.execute_reply":"2024-12-07T14:45:03.070669Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"converter.optimizations = [tf.lite.Optimize.DEFAULT]\ntflite_model = converter.convert()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T14:45:56.126161Z","iopub.execute_input":"2024-12-07T14:45:56.126564Z","iopub.status.idle":"2024-12-07T14:45:57.975867Z","shell.execute_reply.started":"2024-12-07T14:45:56.126534Z","shell.execute_reply":"2024-12-07T14:45:57.974833Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Your class names\nclass_names = ['c0', 'c1', 'c9', 'c4', 'c5', 'c3', 'c6', 'c2', 'c7', 'c8']\n\n# Write to labelmap.txt\nwith open(\"labelmap.txt\", \"w\") as file:\n    for class_name in class_names:\n        file.write(f\"{class_name}\\n\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-07T15:04:03.555512Z","iopub.execute_input":"2024-12-07T15:04:03.555932Z","iopub.status.idle":"2024-12-07T15:04:03.562870Z","shell.execute_reply.started":"2024-12-07T15:04:03.555900Z","shell.execute_reply":"2024-12-07T15:04:03.561519Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}