{"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"}],"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","metadata":{}},{"cell_type":"markdown","source":"Part 1: Loading Dataset\nPart 2: EDA\nPart 3: CNN Model\nPart 4 : Data Augmentation","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":"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-04-25T11:39:45.783698Z","iopub.execute_input":"2024-04-25T11:39:45.784450Z","iopub.status.idle":"2024-04-25T11:39:45.790554Z","shell.execute_reply.started":"2024-04-25T11:39:45.784416Z","shell.execute_reply":"2024-04-25T11:39:45.789789Z"},"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-04-25T11:39:46.795720Z","iopub.execute_input":"2024-04-25T11:39:46.796476Z","iopub.status.idle":"2024-04-25T11:39:46.833512Z","shell.execute_reply.started":"2024-04-25T11:39:46.796439Z","shell.execute_reply":"2024-04-25T11:39:46.832823Z"},"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-04-25T11:39:52.257842Z","iopub.execute_input":"2024-04-25T11:39:52.258136Z","iopub.status.idle":"2024-04-25T11:39:52.282022Z","shell.execute_reply.started":"2024-04-25T11:39:52.258102Z","shell.execute_reply":"2024-04-25T11:39:52.281309Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"num_classes = 10","metadata":{"execution":{"iopub.status.busy":"2024-04-25T11:39:53.776482Z","iopub.execute_input":"2024-04-25T11:39:53.776792Z","iopub.status.idle":"2024-04-25T11:39:53.782435Z","shell.execute_reply.started":"2024-04-25T11:39:53.776734Z","shell.execute_reply":"2024-04-25T11:39:53.781675Z"},"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-04-25T11:39:55.411277Z","iopub.execute_input":"2024-04-25T11:39:55.411875Z","iopub.status.idle":"2024-04-25T11:39:55.429763Z","shell.execute_reply.started":"2024-04-25T11:39:55.411839Z","shell.execute_reply":"2024-04-25T11:39:55.428853Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pip install np_utils\n","metadata":{"execution":{"iopub.status.busy":"2024-04-25T11:39:56.944957Z","iopub.execute_input":"2024-04-25T11:39:56.945231Z","iopub.status.idle":"2024-04-25T11:40:05.986888Z","shell.execute_reply.started":"2024-04-25T11:39:56.945199Z","shell.execute_reply":"2024-04-25T11:40:05.985922Z"},"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-04-25T11:40:05.988893Z","iopub.execute_input":"2024-04-25T11:40:05.989140Z","iopub.status.idle":"2024-04-25T11:41:28.352447Z","shell.execute_reply.started":"2024-04-25T11:40:05.989109Z","shell.execute_reply":"2024-04-25T11:41:28.351672Z"},"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-04-25T11:41:28.353671Z","iopub.execute_input":"2024-04-25T11:41:28.354047Z","iopub.status.idle":"2024-04-25T11:41:28.651298Z","shell.execute_reply.started":"2024-04-25T11:41:28.354007Z","shell.execute_reply":"2024-04-25T11:41:28.650622Z"},"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-04-25T11:41:28.652832Z","iopub.execute_input":"2024-04-25T11:41:28.653048Z","iopub.status.idle":"2024-04-25T11:41:28.835319Z","shell.execute_reply.started":"2024-04-25T11:41:28.653021Z","shell.execute_reply":"2024-04-25T11:41:28.834610Z"},"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-04-25T11:41:28.836320Z","iopub.execute_input":"2024-04-25T11:41:28.836528Z","iopub.status.idle":"2024-04-25T11:41:31.316639Z","shell.execute_reply.started":"2024-04-25T11:41:28.836501Z","shell.execute_reply":"2024-04-25T11:41:31.315695Z"},"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 = 40\nn_epochs = 75","metadata":{"execution":{"iopub.status.busy":"2024-04-25T11:43:56.401401Z","iopub.execute_input":"2024-04-25T11:43:56.401687Z","iopub.status.idle":"2024-04-25T11:43:56.405422Z","shell.execute_reply.started":"2024-04-25T11:43:56.401654Z","shell.execute_reply":"2024-04-25T11:43:56.404643Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.models import Model\nfrom keras.layers import Input, Conv2D, BatchNormalization, MaxPooling2D, Dropout, Dense, Flatten, add\n\ndef create_model():\n    inputs = Input(shape=(img_rows, img_cols, color_type))\n    \n    # Initial Convolutional Block\n    x = Conv2D(32, (3, 3), activation='relu', padding='same')(inputs)\n    x = BatchNormalization()(x)\n    x = Conv2D(32, (3, 3), activation='relu', padding='same')(x)\n    x = BatchNormalization()(x)\n    x = MaxPooling2D(pool_size=(2, 2))(x)\n    x = Dropout(0.2)(x)\n    \n    # Adding more blocks with skip connections\n    for filters in [64, 128, 256]:\n        # Convolutional Block\n        y = Conv2D(filters, (3, 3), activation='relu', padding='same')(x)\n        y = BatchNormalization()(y)\n        y = Conv2D(filters, (3, 3), activation='relu', padding='same')(y)\n        y = BatchNormalization()(y)\n        y = MaxPooling2D(pool_size=(2, 2))(y)\n        y = Dropout(0.3)(y)\n        \n        # Skip Connection\n        x = Conv2D(filters, (1, 1), strides=(2, 2), padding='same')(x) # Matching the dimension of x to y\n        x = add([x, y])  # Adding skip connection\n\n    # Final layers\n    x = Flatten()(x)\n    x = Dense(512, activation='relu')(x)\n    x = BatchNormalization()(x)\n    x = Dropout(0.5)(x)  \n    x = Dense(128, activation='relu')(x)\n    x = BatchNormalization()(x)\n    x = Dropout(0.5)(x) \n    outputs = Dense(10, activation='softmax')(x)\n    \n    model = Model(inputs=inputs, outputs=outputs)\n    \n    return model","metadata":{"execution":{"iopub.status.busy":"2024-04-25T11:41:31.323080Z","iopub.execute_input":"2024-04-25T11:41:31.323304Z","iopub.status.idle":"2024-04-25T11:41:31.339505Z","shell.execute_reply.started":"2024-04-25T11:41:31.323275Z","shell.execute_reply":"2024-04-25T11:41:31.338794Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = create_model()\n\n#Details about the model\nmodel.summary()\n","metadata":{"execution":{"iopub.status.busy":"2024-04-25T11:43:10.216258Z","iopub.execute_input":"2024-04-25T11:43:10.216555Z","iopub.status.idle":"2024-04-25T11:43:10.479100Z","shell.execute_reply.started":"2024-04-25T11:43:10.216521Z","shell.execute_reply":"2024-04-25T11:43:10.478331Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### Training model","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras.optimizers import Adam","metadata":{"execution":{"iopub.status.busy":"2024-04-25T11:44:02.565586Z","iopub.execute_input":"2024-04-25T11:44:02.566343Z","iopub.status.idle":"2024-04-25T11:44:02.570176Z","shell.execute_reply.started":"2024-04-25T11:44:02.566305Z","shell.execute_reply":"2024-04-25T11:44:02.569360Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"custom_lr = 0.00004\noptimizer = Adam(learning_rate=custom_lr)\n\nmodel.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy'])\n\nhistory = 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-04-25T11:44:05.164312Z","iopub.execute_input":"2024-04-25T11:44:05.164584Z","iopub.status.idle":"2024-04-25T11:53:12.631504Z","shell.execute_reply.started":"2024-04-25T11:44:05.164552Z","shell.execute_reply":"2024-04-25T11:53:12.630716Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# from tensorflow.keras.optimizers import RMSprop","metadata":{"execution":{"iopub.status.busy":"2024-04-25T11:39:42.691405Z","iopub.status.idle":"2024-04-25T11:39:42.691826Z","shell.execute_reply.started":"2024-04-25T11:39:42.691588Z","shell.execute_reply":"2024-04-25T11:39:42.691610Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# custom_lr = 0.00004\n# optimizer = RMSprop(learning_rate=custom_lr)\n# model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy'])\n\n# n_epochs = 75\n\n# 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\n# print('History of the training',history.history)","metadata":{"execution":{"iopub.status.busy":"2024-04-25T11:39:42.693146Z","iopub.status.idle":"2024-04-25T11:39:42.693551Z","shell.execute_reply.started":"2024-04-25T11:39:42.693331Z","shell.execute_reply":"2024-04-25T11:39:42.693353Z"},"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-04-25T11:56:34.863093Z","iopub.execute_input":"2024-04-25T11:56:34.863428Z","iopub.status.idle":"2024-04-25T11:56:35.311551Z","shell.execute_reply.started":"2024-04-25T11:56:34.863391Z","shell.execute_reply":"2024-04-25T11:56:35.310869Z"},"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-04-25T11:58:58.961931Z","iopub.execute_input":"2024-04-25T11:58:58.962229Z","iopub.status.idle":"2024-04-25T11:58:58.969594Z","shell.execute_reply.started":"2024-04-25T11:58:58.962194Z","shell.execute_reply":"2024-04-25T11:58:58.968805Z"},"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-04-25T11:59:01.600556Z","iopub.execute_input":"2024-04-25T11:59:01.600858Z","iopub.status.idle":"2024-04-25T11:59:02.922651Z","shell.execute_reply.started":"2024-04-25T11:59:01.600825Z","shell.execute_reply":"2024-04-25T11:59:02.922004Z"},"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-04-25T12:00:00.252219Z","iopub.execute_input":"2024-04-25T12:00:00.252921Z","iopub.status.idle":"2024-04-25T12:00:00.258433Z","shell.execute_reply.started":"2024-04-25T12:00:00.252888Z","shell.execute_reply":"2024-04-25T12:00:00.257593Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for i in range(10):\n    plot_test_class(model, test_files, i)","metadata":{"execution":{"iopub.status.busy":"2024-04-25T12:00:22.821008Z","iopub.execute_input":"2024-04-25T12:00:22.821768Z","iopub.status.idle":"2024-04-25T12:00:25.219418Z","shell.execute_reply.started":"2024-04-25T12:00:22.821715Z","shell.execute_reply":"2024-04-25T12:00:25.218705Z"},"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-04-25T12:00:29.570368Z","iopub.execute_input":"2024-04-25T12:00:29.571032Z","iopub.status.idle":"2024-04-25T12:00:29.576067Z","shell.execute_reply.started":"2024-04-25T12:00:29.570986Z","shell.execute_reply":"2024-04-25T12:00:29.575294Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Training with data augmentation","metadata":{}},{"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-04-25T12:00:32.918711Z","iopub.execute_input":"2024-04-25T12:00:32.918997Z","iopub.status.idle":"2024-04-25T12:00:33.012227Z","shell.execute_reply.started":"2024-04-25T12:00:32.918967Z","shell.execute_reply":"2024-04-25T12:00:33.011584Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"n_epochs = 75\nhistory_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-04-25T12:00:56.672699Z","iopub.execute_input":"2024-04-25T12:00:56.672992Z","iopub.status.idle":"2024-04-25T12:13:15.323420Z","shell.execute_reply.started":"2024-04-25T12:00:56.672960Z","shell.execute_reply":"2024-04-25T12:13:15.322734Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plot_train_history(history_v2)\n","metadata":{"execution":{"iopub.status.busy":"2024-04-25T12:13:15.325298Z","iopub.execute_input":"2024-04-25T12:13:15.326038Z","iopub.status.idle":"2024-04-25T12:13:15.741405Z","shell.execute_reply.started":"2024-04-25T12:13:15.325995Z","shell.execute_reply":"2024-04-25T12:13:15.740623Z"},"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-04-25T12:52:26.618136Z","iopub.execute_input":"2024-04-25T12:52:26.618427Z","iopub.status.idle":"2024-04-25T12:52:27.278020Z","shell.execute_reply.started":"2024-04-25T12:52:26.618397Z","shell.execute_reply":"2024-04-25T12:52:27.277214Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Conclusion for Data Augmentation\n### Data augmentation makes our model more robust.","metadata":{}}]}