{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.7.12","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"},{"sourceId":9684893,"sourceType":"datasetVersion","datasetId":5920246}],"dockerImageVersionId":30162,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"<center><h1 style=\"color:#1a1a1a;\n                    font-size:3em\">\n        Distracted Driver Detection\n        </h1> \n        <h2 style=\"color:#1a1a1a;\n                    font-size:2em\">\n        Can computer vision spot distracted drivers?\n        </h2>\n</center>","metadata":{}},{"cell_type":"markdown","source":"## Realised by:\n * ### Mohammed JAWHAR\n * ### Amine SNOUSSI \n","metadata":{}},{"cell_type":"markdown","source":"<p style=\"font-size:1.5em\">📜 Table of Contents:</p>\n<div style=\"font-size:1.3em\">    \n    <ul>\n       <li><a href=\"#Intro-section\">Part 1: Loading Dataset 📖</a></li>   \n       <li>\n          <a href=\"#Analysis-section\">Part 2: EDA 🔎</a>\n       </li>\n       <li>\n          <a href=\"#Forcasting-section\">Part 3: CNN Model 🧿</a>\n        </li>\n        <li>\n          <a href=\"#Forcasting-section\">Part 4 : Data Augmentation 🖼️</a>\n        </li>\n        \n    ","metadata":{}},{"cell_type":"markdown","source":"<div id=\"overview\">\n        <h1 style=\"color:#1a1a1a\">\n         ⮞  Part 1 : Loading Dataset \n        </h1>\n</div>","metadata":{}},{"cell_type":"code","source":"!pip install numpy pandas opencv-python tqdm glob2 keras scikit-learn matplotlib","metadata":{"execution":{"iopub.status.busy":"2024-10-23T12:28:17.883585Z","iopub.execute_input":"2024-10-23T12:28:17.883954Z","iopub.status.idle":"2024-10-23T12:28:31.287226Z","shell.execute_reply.started":"2024-10-23T12:28:17.883859Z","shell.execute_reply":"2024-10-23T12:28:31.286490Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport cv2\nimport os\nfrom tqdm import tqdm\nfrom glob import glob\nfrom keras.utils import np_utils\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\n\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Sequential, Model\nfrom keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout, BatchNormalization, GlobalAveragePooling2D\n\n","metadata":{"execution":{"iopub.status.busy":"2024-10-23T12:28:31.289392Z","iopub.execute_input":"2024-10-23T12:28:31.289707Z","iopub.status.idle":"2024-10-23T12:28:41.844813Z","shell.execute_reply.started":"2024-10-23T12:28:31.289664Z","shell.execute_reply":"2024-10-23T12:28:41.843963Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df = pd.read_csv('../input/state-farm-distracted-driver-detection/driver_imgs_list.csv')\ndf.head(5)","metadata":{"execution":{"iopub.status.busy":"2024-10-23T12:28:41.845866Z","iopub.execute_input":"2024-10-23T12:28:41.846093Z","iopub.status.idle":"2024-10-23T12:28:41.907792Z","shell.execute_reply.started":"2024-10-23T12:28:41.846062Z","shell.execute_reply":"2024-10-23T12:28:41.907031Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Groupby subjects\nby_drivers = df.groupby('subject') \n#Group unique drivers\nunique_drivers = by_drivers.groups.keys() # drivers id\n\nprint('There are : ',len(unique_drivers), ' unique drivers')\nprint('There is a mean of ',round(df.groupby('subject').count()['classname'].mean()), ' images by driver.')","metadata":{"execution":{"iopub.status.busy":"2024-10-23T12:28:41.909375Z","iopub.execute_input":"2024-10-23T12:28:41.909596Z","iopub.status.idle":"2024-10-23T12:28:41.940035Z","shell.execute_reply.started":"2024-10-23T12:28:41.909568Z","shell.execute_reply":"2024-10-23T12:28:41.939401Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"num_classes = 10","metadata":{"execution":{"iopub.status.busy":"2024-10-23T12:28:41.940879Z","iopub.execute_input":"2024-10-23T12:28:41.941057Z","iopub.status.idle":"2024-10-23T12:28:41.944706Z","shell.execute_reply.started":"2024-10-23T12:28:41.941033Z","shell.execute_reply":"2024-10-23T12:28:41.943853Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Read with opencv\ndef get_image(path, img_rows, img_cols, color_type=3):\n    \n    if color_type == 1:\n        img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)\n    elif color_type == 3:\n        img = cv2.imread(path, cv2.IMREAD_COLOR)\n    img = cv2.resize(img, (img_rows, img_cols)) # Reduce size\n    return img\n\n#Loading training dataset\ndef train_data_load(img_rows=64, img_cols=64, color_type=3):\n    train_images=[]\n    train_labels=[]\n    \n    #Loop over the training folder\n    for classes in tqdm(range(num_classes)):\n        print('Loading directory c{}'.format(classes))\n        files = glob(os.path.join('../input/state-farm-distracted-driver-detection/imgs/train/c' + str(classes), '*.jpg'))\n        for file in files:\n            img = get_image(file, img_rows, img_cols, color_type)\n            train_images.append(img)\n            train_labels.append(classes)\n    return train_images, train_labels\n\ndef read_and_normalize_train_data(img_rows, img_cols, color_type):\n    X, labels = train_data_load(img_rows, img_cols, color_type)\n    y = np_utils.to_categorical(labels, 10)\n    x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n    x_train = np.array(x_train, dtype=np.uint8).reshape(-1,img_rows,img_cols,color_type)\n    x_test = np.array(x_test, dtype=np.uint8).reshape(-1,img_rows,img_cols,color_type)\n    \n    return x_train, x_test, y_train, y_test\n\n#Loading validation dataset\ndef load_test(size=200000, img_rows=64, img_cols=64, color_type=3):\n    \"\"\"\n    Same as above but for validation dataset\n    \"\"\"\n    path = os.path.join('../input/state-farm-distracted-driver-detection/imgs/test', '*.jpg')\n    files = sorted(glob(path))\n    X_test, X_test_id = [], []\n    total = 0\n    files_size = len(files)\n    for file in tqdm(files):\n        if total >= size or total >= files_size:\n            break\n        file_base = os.path.basename(file)\n        img = get_image(file, img_rows, img_cols, color_type)\n        X_test.append(img)\n        X_test_id.append(file_base)\n        total += 1\n    return X_test, X_test_id\n\ndef read_and_normalize_sampled_test_data(size, img_rows, img_cols, color_type=3):\n    test_data, test_ids = load_test(size, img_rows, img_cols, color_type)   \n    test_data = np.array(test_data, dtype=np.uint8)\n    test_data = test_data.reshape(-1,img_rows,img_cols,color_type)\n    return test_data, test_ids\n    ","metadata":{"execution":{"iopub.status.busy":"2024-10-23T12:28:41.945950Z","iopub.execute_input":"2024-10-23T12:28:41.946162Z","iopub.status.idle":"2024-10-23T12:28:41.963455Z","shell.execute_reply.started":"2024-10-23T12:28:41.946136Z","shell.execute_reply":"2024-10-23T12:28:41.962752Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pip install np_utils\n","metadata":{"execution":{"iopub.status.busy":"2024-10-23T12:28:41.964933Z","iopub.execute_input":"2024-10-23T12:28:41.965213Z","iopub.status.idle":"2024-10-23T12:28:52.829880Z","shell.execute_reply.started":"2024-10-23T12:28:41.965161Z","shell.execute_reply":"2024-10-23T12:28:52.828975Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"img_rows = 64\nimg_cols = 64\ncolor_type = 1\nnb_test_samples = 200\n\n#Loading train images \nx_train, x_test, y_train, y_test = read_and_normalize_train_data(img_rows, img_cols, color_type)\n\n#Loading validation images \ntest_files, test_targets = read_and_normalize_sampled_test_data(nb_test_samples, img_rows, img_cols, color_type)","metadata":{"execution":{"iopub.status.busy":"2024-10-23T12:28:52.831405Z","iopub.execute_input":"2024-10-23T12:28:52.831665Z","iopub.status.idle":"2024-10-23T12:33:59.140104Z","shell.execute_reply.started":"2024-10-23T12:28:52.831624Z","shell.execute_reply":"2024-10-23T12:33:59.139278Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<div id=\"overview\">\n        <h1 style=\"color:#1a1a1a\">\n         ⮞  Part 2 : EDA \n        </h1>\n</div>","metadata":{}},{"cell_type":"markdown","source":"### Data visualisation\n ","metadata":{}},{"cell_type":"code","source":"import plotly.express as px\npx.histogram(df, x=\"classname\", color=\"classname\", title=\"Number of images by categories \")\n","metadata":{"execution":{"iopub.status.busy":"2024-10-23T12:33:59.141206Z","iopub.execute_input":"2024-10-23T12:33:59.141462Z","iopub.status.idle":"2024-10-23T12:34:05.148738Z","shell.execute_reply.started":"2024-10-23T12:33:59.141432Z","shell.execute_reply":"2024-10-23T12:34:05.148007Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Find the frequency of images per driver\ndrivers_id = pd.DataFrame((df['subject'].value_counts()).reset_index())\ndrivers_id.columns = ['driver_id', 'Counts']\npx.histogram(drivers_id, x=\"driver_id\",y=\"Counts\" ,color=\"driver_id\", title=\"Number of images by subjects \")","metadata":{"execution":{"iopub.status.busy":"2024-10-23T12:34:05.151345Z","iopub.execute_input":"2024-10-23T12:34:05.151577Z","iopub.status.idle":"2024-10-23T12:34:05.340942Z","shell.execute_reply.started":"2024-10-23T12:34:05.151547Z","shell.execute_reply":"2024-10-23T12:34:05.340162Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Images overview\n","metadata":{}},{"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\nplt.figure(figsize = (12, 20))\nimage_count = 1\nBASE_URL = '../input/state-farm-distracted-driver-detection/imgs/train/'\nfor directory in os.listdir(BASE_URL):\n    if directory[0] != '.':\n        for i, file in enumerate(os.listdir(BASE_URL + directory)):\n            if i == 1:\n                break\n            else:\n                fig = plt.subplot(5, 2, image_count)\n                image_count += 1\n                image = mpimg.imread(BASE_URL + directory + '/' + file)\n                plt.imshow(image)\n                plt.title(activity_map[directory])","metadata":{"execution":{"iopub.status.busy":"2024-10-23T12:34:05.342219Z","iopub.execute_input":"2024-10-23T12:34:05.342767Z","iopub.status.idle":"2024-10-23T12:34:07.616262Z","shell.execute_reply.started":"2024-10-23T12:34:05.342724Z","shell.execute_reply":"2024-10-23T12:34:07.615492Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<div id=\"overview\">\n        <h1 style=\"color:#1a1a1a\">\n         ⮞  Part 3 : CNN Model \n        </h1>\n</div>","metadata":{}},{"cell_type":"markdown","source":"### Architecture :\n\n* 3 Convolutionnal layers (with Relu, Maxpooling and dropout)\n* A flatten layer\n* 2 Dense layers with Relu and Dropouts\n* 1 Dense layer with softmax for the classification","metadata":{}},{"cell_type":"code","source":"batch_size = 50\nn_epochs = 100","metadata":{"execution":{"iopub.status.busy":"2024-10-23T12:34:07.617453Z","iopub.execute_input":"2024-10-23T12:34:07.617706Z","iopub.status.idle":"2024-10-23T12:34:07.621460Z","shell.execute_reply.started":"2024-10-23T12:34:07.617676Z","shell.execute_reply":"2024-10-23T12:34:07.620806Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def create_model():\n    \n    model = Sequential()\n    \n    #CNN1\n    model.add(Conv2D(32, (3,3), activation='relu', input_shape=(img_rows, img_cols, color_type)))\n    model.add(BatchNormalization())\n    model.add(Conv2D(32,(3,3), activation='relu', padding='same'))\n    model.add(BatchNormalization(axis=3))\n    model.add(MaxPooling2D(pool_size=(2,2), padding='same'))\n    model.add(Dropout(0.3))\n    \n    #CNN2\n    model.add(Conv2D(64, (3,3), activation='relu', input_shape=(img_rows, img_cols, color_type)))\n    model.add(BatchNormalization())\n    model.add(Conv2D(64,(3,3), activation='relu', padding='same'))\n    model.add(BatchNormalization(axis=3))\n    model.add(MaxPooling2D(pool_size=(2,2), padding='same'))\n    model.add(Dropout(0.3))\n    \n    #CNN3\n    model.add(Conv2D(128, (3,3), activation='relu', input_shape=(img_rows, img_cols, color_type)))\n    model.add(BatchNormalization())\n    model.add(Conv2D(128,(3,3), activation='relu', padding='same'))\n    model.add(BatchNormalization(axis=3))\n    model.add(MaxPooling2D(pool_size=(2,2), padding='same'))\n    model.add(Dropout(0.3))\n    \n    \n    #Output\n    model.add(Flatten())\n    model.add(Dense(512, activation='relu'))\n    model.add(BatchNormalization())\n    model.add(Dropout(0.5))\n    model.add(Dense(128, activation='relu'))\n    model.add(BatchNormalization())\n    model.add(Dropout(0.25))\n    model.add(Dense(10,activation='softmax'))\n    \n    \n    return model","metadata":{"execution":{"iopub.status.busy":"2024-10-23T12:34:07.622535Z","iopub.execute_input":"2024-10-23T12:34:07.622744Z","iopub.status.idle":"2024-10-23T12:34:07.636633Z","shell.execute_reply.started":"2024-10-23T12:34:07.622718Z","shell.execute_reply":"2024-10-23T12:34:07.636010Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = create_model()\n\n#Details about the model\nmodel.summary()\n\nmodel.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])\n","metadata":{"execution":{"iopub.status.busy":"2024-10-23T12:34:07.637582Z","iopub.execute_input":"2024-10-23T12:34:07.637762Z","iopub.status.idle":"2024-10-23T12:34:11.957047Z","shell.execute_reply.started":"2024-10-23T12:34:07.637738Z","shell.execute_reply":"2024-10-23T12:34:11.956285Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### Training model","metadata":{}},{"cell_type":"code","source":"history = model.fit(x_train, y_train,\n                   validation_data=(x_test, y_test),\n                   epochs=n_epochs, batch_size=batch_size, verbose=1)\n\nprint('History of the training',history.history)\n","metadata":{"execution":{"iopub.status.busy":"2024-10-23T12:34:11.958286Z","iopub.execute_input":"2024-10-23T12:34:11.958980Z","iopub.status.idle":"2024-10-23T12:43:45.989782Z","shell.execute_reply.started":"2024-10-23T12:34:11.958931Z","shell.execute_reply":"2024-10-23T12:43:45.988910Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def plot_train_history(history):\n    \"\"\"\n    Plot the validation accuracy and validation loss over epochs\n    \"\"\"\n    # Summarize history for accuracy\n    plt.plot(history.history['accuracy'])\n    plt.plot(history.history['val_accuracy'])\n    plt.title('Model accuracy')\n    plt.ylabel('accuracy')\n    plt.xlabel('epoch')\n    plt.legend(['train', 'test'], loc='upper left')\n    plt.show()\n\n    # Summarize history for loss\n    plt.plot(history.history['loss'])\n    plt.plot(history.history['val_loss'])\n    plt.title('Model loss')\n    plt.ylabel('loss')\n    plt.xlabel('epoch')\n    plt.legend(['train', 'test'], loc='upper left')\n    plt.show()\n    \nplot_train_history(history)","metadata":{"execution":{"iopub.status.busy":"2024-10-23T12:43:45.991057Z","iopub.execute_input":"2024-10-23T12:43:45.991324Z","iopub.status.idle":"2024-10-23T12:43:46.414864Z","shell.execute_reply.started":"2024-10-23T12:43:45.991287Z","shell.execute_reply":"2024-10-23T12:43:46.414146Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Prediction on test set","metadata":{}},{"cell_type":"code","source":"def plot_test_class(model, test_files, image_number, color_type=1):\n    \"\"\"\n    Function that tests or model on test images and show the results\n    \"\"\"\n    img_brute = test_files[image_number]\n    img_brute = cv2.resize(img_brute,(img_rows,img_cols))\n    plt.imshow(img_brute, cmap='gray')\n\n    new_img = img_brute.reshape(-1,img_rows,img_cols,color_type)\n\n    y_prediction = model.predict(new_img, batch_size=batch_size, verbose=1)\n    print('Y prediction: {}'.format(y_prediction))\n    print('Predicted: {}'.format(activity_map.get('c{}'.format(np.argmax(y_prediction)))))\n    \n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2024-10-23T12:43:46.415933Z","iopub.execute_input":"2024-10-23T12:43:46.416148Z","iopub.status.idle":"2024-10-23T12:43:46.422687Z","shell.execute_reply.started":"2024-10-23T12:43:46.416119Z","shell.execute_reply":"2024-10-23T12:43:46.421983Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"score1 = model.evaluate(x_test, y_test, verbose=1)\n","metadata":{"execution":{"iopub.status.busy":"2024-10-23T12:43:46.423633Z","iopub.execute_input":"2024-10-23T12:43:46.423814Z","iopub.status.idle":"2024-10-23T12:43:47.171539Z","shell.execute_reply.started":"2024-10-23T12:43:46.423790Z","shell.execute_reply":"2024-10-23T12:43:47.170793Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print('Loss: ', score1[0])\nprint('Accuracy: ', score1[1]*100, ' %')","metadata":{"execution":{"iopub.status.busy":"2024-10-23T12:43:47.172693Z","iopub.execute_input":"2024-10-23T12:43:47.172924Z","iopub.status.idle":"2024-10-23T12:43:47.178345Z","shell.execute_reply.started":"2024-10-23T12:43:47.172895Z","shell.execute_reply":"2024-10-23T12:43:47.177539Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for i in range(20):\n    plot_test_class(model, test_files, i)","metadata":{"execution":{"iopub.status.busy":"2024-10-23T12:43:47.179438Z","iopub.execute_input":"2024-10-23T12:43:47.179656Z","iopub.status.idle":"2024-10-23T12:43:51.489031Z","shell.execute_reply.started":"2024-10-23T12:43:47.179628Z","shell.execute_reply":"2024-10-23T12:43:51.488447Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<div id=\"overview\">\n        <h1 style=\"color:#1a1a1a\">\n         ⮞  Part 4 : Data Augmentation\n        </h1>\n</div>","metadata":{}},{"cell_type":"code","source":"# Using ImageDataGenerator from keras\ntrain_datagen = ImageDataGenerator(rescale = 1.0/255, \n                                   shear_range = 0.2, \n                                   zoom_range = 0.2, \n                                   horizontal_flip = True, \n                                   validation_split = 0.2)\n\ntest_datagen = ImageDataGenerator(rescale=1.0/ 255, validation_split = 0.2)","metadata":{"execution":{"iopub.status.busy":"2024-10-23T12:43:51.490383Z","iopub.execute_input":"2024-10-23T12:43:51.490623Z","iopub.status.idle":"2024-10-23T12:43:51.495733Z","shell.execute_reply.started":"2024-10-23T12:43:51.490591Z","shell.execute_reply":"2024-10-23T12:43:51.495006Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"nb_train_samples = x_train.shape[0]\nnb_validation_samples = x_test.shape[0]\ntraining_generator = train_datagen.flow(x_train, y_train, batch_size=batch_size)\nvalidation_generator = test_datagen.flow(x_test, y_test, batch_size=batch_size)","metadata":{"execution":{"iopub.status.busy":"2024-10-23T12:43:51.496821Z","iopub.execute_input":"2024-10-23T12:43:51.497029Z","iopub.status.idle":"2024-10-23T12:43:52.399881Z","shell.execute_reply.started":"2024-10-23T12:43:51.497001Z","shell.execute_reply":"2024-10-23T12:43:52.398984Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Training with data augmentation","metadata":{}},{"cell_type":"code","source":"history_v2 = model.fit_generator(training_generator,\n                         steps_per_epoch = nb_train_samples // batch_size,\n                         epochs = n_epochs, \n                         verbose = 1,\n                         validation_data = validation_generator,\n                         validation_steps = nb_validation_samples // batch_size)","metadata":{"execution":{"iopub.status.busy":"2024-10-23T12:43:52.401013Z","iopub.execute_input":"2024-10-23T12:43:52.401230Z","iopub.status.idle":"2024-10-23T12:59:09.725519Z","shell.execute_reply.started":"2024-10-23T12:43:52.401203Z","shell.execute_reply":"2024-10-23T12:59:09.724734Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n# Lưu mô hình\nmodel.save('/kaggle/working/my_model.h5')","metadata":{"execution":{"iopub.status.busy":"2024-10-23T12:59:09.727019Z","iopub.execute_input":"2024-10-23T12:59:09.727286Z","iopub.status.idle":"2024-10-23T12:59:09.859350Z","shell.execute_reply.started":"2024-10-23T12:59:09.727232Z","shell.execute_reply":"2024-10-23T12:59:09.858680Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.models import load_model\nloaded_model = load_model('my_model.h5')\n\n# In ra thông tin mô hình\nloaded_model.summary()\n","metadata":{"execution":{"iopub.status.busy":"2024-10-23T12:59:09.860400Z","iopub.execute_input":"2024-10-23T12:59:09.860622Z","iopub.status.idle":"2024-10-23T12:59:10.177959Z","shell.execute_reply.started":"2024-10-23T12:59:09.860595Z","shell.execute_reply":"2024-10-23T12:59:10.177154Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import cv2\nimport numpy as np\nfrom tensorflow.keras.models import load_model\nfrom tensorflow.keras.preprocessing import image\nimport matplotlib.pyplot as plt\n\n# Đường dẫn đến mô hình đã lưu\nmodel_path = 'my_model.h5'\n\n# Load mô hình\nloaded_model = load_model(model_path)\n\n# Đường dẫn đến ảnh cần kiểm tra\nimage_path = '/kaggle/input/dsadasd/truck-driver.jpg'\n\n# Kích thước ảnh đầu vào của mô hình\nimg_width, img_height = 64, 64\n\n# Hàm tiền xử lý ảnh\n\ndef preprocess_image(img_path):\n    img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE) # Đọc ảnh grayscale\n    img = cv2.resize(img, (img_width, img_height), interpolation=cv2.INTER_AREA) # Thay đổi kích thước\n    x = image.img_to_array(img)\n    x = np.expand_dims(x, axis=0)\n    x = x / 255.0\n    return x\n\n# Tiền xử lý ảnh\nimg = preprocess_image(image_path)\n\n# Dự đoán\npredictions = loaded_model.predict(img)\n\n# Lấy lớp dự đoán\npredicted_class = np.argmax(predictions)\n\n# Tên các lớp (dictionary)\nclass_names = {\n    '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# Lấy tên lớp dự đoán\npredicted_class_name = class_names[f\"c{predicted_class}\"]\n\n# In kết quả\nprint(f\"Ảnh: {image_path}\")\nprint(f\"Dự đoán: {predicted_class_name}\")\nprint(f\"Xác suất: {predictions[0][predicted_class]}\")\n\n# Hiển thị ảnh và kết quả bằng matplotlib\noriginal_img = cv2.imread(image_path)\nplt.imshow(cv2.cvtColor(original_img, cv2.COLOR_BGR2RGB))  # Chuyển đổi màu\nplt.title(f\"Prediction: {predicted_class_name}\")\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-10-23T13:23:10.852579Z","iopub.execute_input":"2024-10-23T13:23:10.852883Z","iopub.status.idle":"2024-10-23T13:23:12.093109Z","shell.execute_reply.started":"2024-10-23T13:23:10.852850Z","shell.execute_reply":"2024-10-23T13:23:12.092359Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plot_train_history(history_v2)\n","metadata":{"execution":{"iopub.status.busy":"2024-10-23T12:59:11.009531Z","iopub.execute_input":"2024-10-23T12:59:11.009751Z","iopub.status.idle":"2024-10-23T12:59:11.409525Z","shell.execute_reply.started":"2024-10-23T12:59:11.009723Z","shell.execute_reply":"2024-10-23T12:59:11.408835Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Evaluate and compare the performance of the new model\nscore2 = model.evaluate_generator(validation_generator, nb_validation_samples // batch_size)\nprint(\"Loss for model 1\",score1[0])\nprint(\"Loss for model 2 (data augmentation):\", score2[0])\n\nprint(\"Test accuracy for model 1\",score1[1])\nprint(\"Test accuracy for model 2 (data augmentation):\", score2[1])","metadata":{"execution":{"iopub.status.busy":"2024-10-23T12:59:11.413552Z","iopub.execute_input":"2024-10-23T12:59:11.414129Z","iopub.status.idle":"2024-10-23T12:59:11.904338Z","shell.execute_reply.started":"2024-10-23T12:59:11.414098Z","shell.execute_reply":"2024-10-23T12:59:11.903595Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Conclusion for Data Augmentation\n### Data augmentation makes our model more robust.","metadata":{}}]}