{"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":"markdown","source":"# <div style=\"text-align: center; background-color: #595964; font-family:Times New Roman; color: white; padding: 14px; line-height: 1;border-radius:20px\">Dog vs Cat clssification</div>","metadata":{}},{"cell_type":"markdown","source":"<a id=\"1\"></a>\n# <div style=\"text-align: center; background-color: #00BFFF; font-family:Times New Roman; color: white; padding: 14px; line-height: 1;border-radius:20px\">1. Import Necessary Libraries</div>","metadata":{}},{"cell_type":"code","source":"!pip install visualkeras","metadata":{"execution":{"iopub.status.busy":"2023-09-14T02:47:46.657772Z","iopub.execute_input":"2023-09-14T02:47:46.658162Z","iopub.status.idle":"2023-09-14T02:48:01.225297Z","shell.execute_reply.started":"2023-09-14T02:47:46.658135Z","shell.execute_reply":"2023-09-14T02:48:01.224030Z"},"_kg_hide-output":true,"collapsed":true,"jupyter":{"outputs_hidden":true},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport plotly.graph_objs as go \nimport itertools\nimport plotly.express as px\nimport cv2\nimport tensorflow as tf\nimport random\nimport zipfile\nimport os\nfrom PIL import Image\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import classification_report\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nimport visualkeras","metadata":{"execution":{"iopub.status.busy":"2023-09-14T02:48:15.302211Z","iopub.execute_input":"2023-09-14T02:48:15.303545Z","iopub.status.idle":"2023-09-14T02:48:15.337695Z","shell.execute_reply.started":"2023-09-14T02:48:15.303498Z","shell.execute_reply":"2023-09-14T02:48:15.336549Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a id=\"1\"></a>\n# <div style=\"text-align: center; background-color: #6495ED; font-family:Times New Roman; color: white; padding: 14px; line-height: 1;border-radius:20px\">2. Unzip and extract data </div>","metadata":{}},{"cell_type":"code","source":"with zipfile.ZipFile('/kaggle/input/dogs-vs-cats/train.zip', 'r') as train_zip:\n    train_zip.extractall('.')  \nimage_dir = \"../working/train/\"\nfilenames = os.listdir(image_dir)\nlabels = [x.split(\".\")[0] for x in filenames]\ndf = pd.DataFrame({\"filename\": filenames, \"label\": labels})\ndf.head()","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-09-14T02:25:20.477275Z","iopub.execute_input":"2023-09-14T02:25:20.477643Z","iopub.status.idle":"2023-09-14T02:25:28.008069Z","shell.execute_reply.started":"2023-09-14T02:25:20.477613Z","shell.execute_reply":"2023-09-14T02:25:28.006935Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a id=\"1\"></a>\n# <div style=\"text-align: center; background-color: #6495ED; font-family:Times New Roman; color: white; padding: 14px; line-height: 1;border-radius:20px\">3. Check for data imabalance and number of categories </div>","metadata":{}},{"cell_type":"code","source":"count = df['label'].value_counts()\n\ncount \n","metadata":{"execution":{"iopub.status.busy":"2023-09-14T02:33:31.136363Z","iopub.execute_input":"2023-09-14T02:33:31.137312Z","iopub.status.idle":"2023-09-14T02:33:31.150890Z","shell.execute_reply.started":"2023-09-14T02:33:31.137279Z","shell.execute_reply":"2023-09-14T02:33:31.149696Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig = go.Figure(go.Bar(\n            x= count.values,\n            y=count.index,\n            orientation='h'))\n\nfig.update_layout(title='Data Distribution in Bars',font_size=15,title_x=0.45)\n\n\nfig.show()\n\nfig=px.pie(count.head(10),values= 'count', names=df['label'].unique(),hole=0.425)\nfig.update_layout(title='Data Distribution of Data',font_size=15,title_x=0.45,annotations=[dict(text='Cat vs Dog',font_size=18, showarrow=False,height=800,width=700)])\nfig.update_traces(textfont_size=15,textinfo='percent')\nfig.show()","metadata":{"execution":{"iopub.status.busy":"2023-09-14T02:33:10.423675Z","iopub.execute_input":"2023-09-14T02:33:10.424026Z","iopub.status.idle":"2023-09-14T02:33:11.721942Z","shell.execute_reply.started":"2023-09-14T02:33:10.423999Z","shell.execute_reply":"2023-09-14T02:33:11.721018Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a id=\"1\"></a>\n# <div style=\"text-align: center; background-color: #6495ED; font-family:Times New Roman; color: white; padding: 14px; line-height: 1;border-radius:20px\">4. Visualize the data for each category </div>","metadata":{}},{"cell_type":"code","source":"grouped_data = df.groupby(\"label\")\n\nnum_images_per_category = 5\n\nfig, axes = plt.subplots(len(grouped_data), num_images_per_category, figsize=(20, 20))\n\nfor i, (category, group) in enumerate(grouped_data):\n  \n    random_indices = random.sample(range(len(group)), num_images_per_category)\n\n    for j, index in enumerate(random_indices):\n        filename = group.iloc[index][\"filename\"]\n        label = group.iloc[index][\"label\"]\n        image_path = os.path.join(image_dir, filename)\n        image = Image.open(image_path)\n\n        axes[i, j].imshow(image)\n        axes[i, j].set_title(\"Label: \" + label, fontsize = 30)\n        \n\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-09-14T02:34:20.091879Z","iopub.execute_input":"2023-09-14T02:34:20.092386Z","iopub.status.idle":"2023-09-14T02:34:25.131517Z","shell.execute_reply.started":"2023-09-14T02:34:20.092357Z","shell.execute_reply":"2023-09-14T02:34:25.130345Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a id=\"1\"></a>\n# <div style=\"text-align: center; background-color: #6495ED; font-family:Times New Roman; color: white; padding: 14px; line-height: 1;border-radius:20px\">5. Create train, validation and test datasets </div>","metadata":{}},{"cell_type":"code","source":"labels = df['label']\nX_train, X_temp = train_test_split(df, test_size=0.2, stratify=labels, random_state = 23)\n\nlabel_test_val = X_temp['label']\nX_test, X_val = train_test_split(X_temp, test_size=0.5, stratify=label_test_val, random_state = 23)\n\nprint ('X_train:', X_train['label'].value_counts())\n\nprint ('X_val:', X_val['label'].value_counts())\n\nprint ('X_test:', X_test['label'].value_counts())","metadata":{"execution":{"iopub.status.busy":"2023-09-14T02:36:02.008888Z","iopub.execute_input":"2023-09-14T02:36:02.009270Z","iopub.status.idle":"2023-09-14T02:36:02.079659Z","shell.execute_reply.started":"2023-09-14T02:36:02.009240Z","shell.execute_reply":"2023-09-14T02:36:02.078608Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a id=\"1\"></a>\n# <div style=\"text-align: center; background-color: #6495ED; font-family:Times New Roman; color: white; padding: 14px; line-height: 1;border-radius:20px\">6. Create image data generator</div>","metadata":{}},{"cell_type":"code","source":"batch_size = 64\nsize = (370, 370)\nidg = tf.keras.preprocessing.image.ImageDataGenerator(preprocessing_function = tf.keras.applications.vgg16.preprocess_input)","metadata":{"execution":{"iopub.status.busy":"2023-09-14T02:42:16.715095Z","iopub.execute_input":"2023-09-14T02:42:16.715518Z","iopub.status.idle":"2023-09-14T02:42:16.721822Z","shell.execute_reply.started":"2023-09-14T02:42:16.715462Z","shell.execute_reply":"2023-09-14T02:42:16.720550Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_idg = ImageDataGenerator(rescale=1/255)\ntrain_idg = idg.flow_from_dataframe(X_train, \"train/\", x_col= \"filename\", y_col= \"label\",\n                                    batch_size = batch_size,\n                                    target_size=size)","metadata":{"execution":{"iopub.status.busy":"2023-09-14T02:42:17.204993Z","iopub.execute_input":"2023-09-14T02:42:17.205355Z","iopub.status.idle":"2023-09-14T02:42:17.463732Z","shell.execute_reply.started":"2023-09-14T02:42:17.205326Z","shell.execute_reply":"2023-09-14T02:42:17.462624Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"val_idg = ImageDataGenerator(rescale=1/255)\nval_idg = idg.flow_from_dataframe(X_val, \"train/\", x_col=\"filename\", y_col=\"label\",\n                                  batch_size = batch_size,\n                                  target_size = size, shuffle = False)","metadata":{"execution":{"iopub.status.busy":"2023-09-14T02:42:17.811429Z","iopub.execute_input":"2023-09-14T02:42:17.812366Z","iopub.status.idle":"2023-09-14T02:42:17.854588Z","shell.execute_reply.started":"2023-09-14T02:42:17.812323Z","shell.execute_reply":"2023-09-14T02:42:17.853469Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_idg = ImageDataGenerator(rescale=1/255)\ntest_idg = idg.flow_from_dataframe(X_test, \"train/\", x_col= \"filename\", y_col= \"label\",\n                                    batch_size = batch_size,\n                                    target_size=size, shuffle = False)","metadata":{"execution":{"iopub.status.busy":"2023-09-14T02:42:18.039060Z","iopub.execute_input":"2023-09-14T02:42:18.039426Z","iopub.status.idle":"2023-09-14T02:42:18.082067Z","shell.execute_reply.started":"2023-09-14T02:42:18.039399Z","shell.execute_reply":"2023-09-14T02:42:18.081142Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a id=\"1\"></a>\n# <div style=\"text-align: center; background-color: #6495ED; font-family:Times New Roman; color: white; padding: 14px; line-height: 1;border-radius:20px\">7. Download vgg16 model and Building the Model </div>","metadata":{}},{"cell_type":"code","source":"vgg16_model = tf.keras.applications.vgg16.VGG16(include_top=False, input_shape=(370, 370, 3))","metadata":{"execution":{"iopub.status.busy":"2023-09-14T02:43:09.817461Z","iopub.execute_input":"2023-09-14T02:43:09.818068Z","iopub.status.idle":"2023-09-14T02:43:14.065064Z","shell.execute_reply.started":"2023-09-14T02:43:09.818000Z","shell.execute_reply":"2023-09-14T02:43:14.064039Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"vgg16_model.summary()","metadata":{"execution":{"iopub.status.busy":"2023-09-14T02:43:23.459532Z","iopub.execute_input":"2023-09-14T02:43:23.460139Z","iopub.status.idle":"2023-09-14T02:43:23.522091Z","shell.execute_reply.started":"2023-09-14T02:43:23.460095Z","shell.execute_reply":"2023-09-14T02:43:23.521275Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for layer in vgg16_model.layers:\n    layer.trainable = False","metadata":{"execution":{"iopub.status.busy":"2023-09-14T02:44:00.020699Z","iopub.execute_input":"2023-09-14T02:44:00.021105Z","iopub.status.idle":"2023-09-14T02:44:00.027305Z","shell.execute_reply.started":"2023-09-14T02:44:00.021075Z","shell.execute_reply":"2023-09-14T02:44:00.026082Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"flat = tf.keras.layers.Flatten() (vgg16_model.output)\ndropout1 = tf.keras.layers.Dropout(0.2, name=\"Dropout1\") (flat)\ndense1 = tf.keras.layers.Dense(128, activation=\"relu\") (dropout1)\ndropout2 = tf.keras.layers.Dropout(0.2, name=\"Dropout2\")(dense1)\noutput = tf.keras.layers.Dense(2, activation=\"softmax\") (dropout2)\n\nfinal_model = tf.keras.models.Model(inputs=[vgg16_model.input], outputs=[output])","metadata":{"execution":{"iopub.status.busy":"2023-09-14T02:45:00.492714Z","iopub.execute_input":"2023-09-14T02:45:00.493113Z","iopub.status.idle":"2023-09-14T02:45:00.546846Z","shell.execute_reply.started":"2023-09-14T02:45:00.493082Z","shell.execute_reply":"2023-09-14T02:45:00.545841Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tf.keras.utils.plot_model(final_model, show_shapes = True, show_layer_names=True)\n","metadata":{"execution":{"iopub.status.busy":"2023-09-14T02:45:34.315606Z","iopub.execute_input":"2023-09-14T02:45:34.316026Z","iopub.status.idle":"2023-09-14T02:45:34.691340Z","shell.execute_reply.started":"2023-09-14T02:45:34.315996Z","shell.execute_reply":"2023-09-14T02:45:34.690369Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"visualkeras.layered_view(final_model, legend=True)","metadata":{"execution":{"iopub.status.busy":"2023-09-14T02:48:28.839357Z","iopub.execute_input":"2023-09-14T02:48:28.839770Z","iopub.status.idle":"2023-09-14T02:48:29.255575Z","shell.execute_reply.started":"2023-09-14T02:48:28.839738Z","shell.execute_reply":"2023-09-14T02:48:29.254530Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"'''model = tf.keras.models.Sequential([\n    # Note the input shape is the desired size of the image 300x300 with 3 bytes color\n    # This is the first convolution\n    tf.keras.layers.Conv2D(16, (3,3), activation='relu', input_shape=(370, 370, 3)),\n    tf.keras.layers.MaxPooling2D(2, 2),\n    # The second convolution\n    tf.keras.layers.Conv2D(32, (3,3), activation='relu'),\n    tf.keras.layers.MaxPooling2D(2,2),\n    # The third convolution\n    tf.keras.layers.Conv2D(64, (3,3), activation='relu'),\n    tf.keras.layers.MaxPooling2D(2,2),\n    # The fourth convolution\n    tf.keras.layers.Conv2D(64, (3,3), activation='relu'),\n    tf.keras.layers.MaxPooling2D(2,2),\n    # The fifth convolution\n    tf.keras.layers.Conv2D(64, (3,3), activation='relu'),\n    tf.keras.layers.MaxPooling2D(2,2),\n    # Flatten the results to feed into a DNN\n    tf.keras.layers.Flatten(),\n    # 512 neuron hidden layer\n    tf.keras.layers.Dense(512, activation='relu'),\n    # Only 1 output neuron. It will contain a value from 0-1 where 0 for 1 class ('horses') and 1 for the other ('humans')\n    tf.keras.layers.Dense(2, activation='sigmoid')\n])'''","metadata":{"execution":{"iopub.status.busy":"2023-09-14T03:11:43.994297Z","iopub.execute_input":"2023-09-14T03:11:43.994746Z","iopub.status.idle":"2023-09-14T03:11:44.004221Z","shell.execute_reply.started":"2023-09-14T03:11:43.994712Z","shell.execute_reply":"2023-09-14T03:11:44.003116Z"},"_kg_hide-output":true,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a id=\"1\"></a>\n# <div style=\"text-align: center; background-color: #6495ED; font-family:Times New Roman; color: white; padding: 14px; line-height: 1;border-radius:20px\">8. Compile the model</div>","metadata":{}},{"cell_type":"code","source":"final_model.compile(optimizer='adam',\n                    loss=tf.keras.losses.categorical_crossentropy,\n                    metrics = [\"acc\"])","metadata":{"execution":{"iopub.status.busy":"2023-09-14T02:45:42.630039Z","iopub.execute_input":"2023-09-14T02:45:42.630430Z","iopub.status.idle":"2023-09-14T02:45:42.651927Z","shell.execute_reply.started":"2023-09-14T02:45:42.630401Z","shell.execute_reply":"2023-09-14T02:45:42.650893Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a id=\"1\"></a>\n# <div style=\"text-align: center; background-color: #6495ED; font-family:Times New Roman; color: white; padding: 14px; line-height: 1;border-radius:20px\">9. Create a Callback</div>","metadata":{}},{"cell_type":"code","source":"model_ckpt = tf.keras.callbacks.ModelCheckpoint(\"DogCat\",\n                                                monitor=\"val_loss\",\n                                                save_best_only=True)","metadata":{"execution":{"iopub.status.busy":"2023-09-14T02:45:49.327272Z","iopub.execute_input":"2023-09-14T02:45:49.327672Z","iopub.status.idle":"2023-09-14T02:45:49.333571Z","shell.execute_reply.started":"2023-09-14T02:45:49.327642Z","shell.execute_reply":"2023-09-14T02:45:49.332034Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a id=\"1\"></a>\n# <div style=\"text-align: center; background-color: #6495ED; font-family:Times New Roman; color: white; padding: 14px; line-height: 1;border-radius:20px\">10. Train the model </div>","metadata":{}},{"cell_type":"code","source":"history = final_model.fit(train_idg, batch_size=batch_size, validation_data=val_idg, epochs = 4, callbacks=[model_ckpt])","metadata":{"execution":{"iopub.status.busy":"2023-09-14T02:48:51.282975Z","iopub.execute_input":"2023-09-14T02:48:51.283351Z","iopub.status.idle":"2023-09-14T03:02:37.382453Z","shell.execute_reply.started":"2023-09-14T02:48:51.283319Z","shell.execute_reply":"2023-09-14T03:02:37.381279Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a id=\"1\"></a>\n# <div style=\"text-align: center; background-color: #6495ED; font-family:Times New Roman; color: white; padding: 14px; line-height: 1;border-radius:20px\">11. Evaluate accuracy and loss for the model\n </div>","metadata":{}},{"cell_type":"code","source":"acc = history.history['acc']\nval_acc = history.history['val_acc']\n\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs_range = range(4)\n\nplt.figure(figsize=(15, 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-14T03:06:07.088378Z","iopub.execute_input":"2023-09-14T03:06:07.088830Z","iopub.status.idle":"2023-09-14T03:06:07.755244Z","shell.execute_reply.started":"2023-09-14T03:06:07.088799Z","shell.execute_reply":"2023-09-14T03:06:07.754242Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a id=\"1\"></a>\n# <div style=\"text-align: center; background-color: #6495ED; font-family:Times New Roman; color: white; padding: 14px; line-height: 1;border-radius:20px\">12. Check the accuracy of the model on test subset</div>","metadata":{}},{"cell_type":"code","source":"cat_dog_model = tf.keras.models.load_model(\"DogCat\")\n\nresult = cat_dog_model.predict(test_idg)\n\nresult_argmax = np.argmax(result, axis=1)\n\ny_true = test_idg.labels\n\ny_pred = result_argmax\n\naccuracy = (y_pred == y_true).mean()\n\nprint(\"Test Accuracy:\", accuracy)","metadata":{"execution":{"iopub.status.busy":"2023-09-14T03:06:16.294042Z","iopub.execute_input":"2023-09-14T03:06:16.294521Z","iopub.status.idle":"2023-09-14T03:06:39.401649Z","shell.execute_reply.started":"2023-09-14T03:06:16.294464Z","shell.execute_reply":"2023-09-14T03:06:39.400320Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Evaluate the model\nreport = classification_report(y_true, y_pred)\n\n# Split the classification report into lines\nreport_lines = report.split('\\n')\n\n# Create header row\nheader_row = report_lines[0].split()\n\n# Create rows for each class\ntable_rows = [row.split() for row in report_lines[2:-5]]\n\n# Create the table using Plotly\ntable = go.Figure(data=[go.Table(header=dict(values=header_row),\n                 cells=dict(values=list(zip(*table_rows))))\n                 ])\n\n# Show the table\ntable.show()","metadata":{"execution":{"iopub.status.busy":"2023-09-14T03:07:26.588497Z","iopub.execute_input":"2023-09-14T03:07:26.589014Z","iopub.status.idle":"2023-09-14T03:07:26.634126Z","shell.execute_reply.started":"2023-09-14T03:07:26.588967Z","shell.execute_reply":"2023-09-14T03:07:26.632891Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a id=\"1\"></a>\n# <div style=\"text-align: center; background-color: #6495ED; font-family:Times New Roman; color: white; padding: 14px; line-height: 1;border-radius:20px\">13. Make predictions on kaggle test data for submission</div>","metadata":{}},{"cell_type":"code","source":"with zipfile.ZipFile('/kaggle/input/dogs-vs-cats/test1.zip', 'r') as test1_zip:\n    test1_zip.extractall('.')  \ntest_dir = \"../working/test1/\"\nfilenames = os.listdir(test_dir)\ntest_data = pd.DataFrame({\"filename\": filenames})\ntest_data['label'] = 'unknown'\ntest_data.head()","metadata":{"execution":{"iopub.status.busy":"2023-09-14T03:07:31.541445Z","iopub.execute_input":"2023-09-14T03:07:31.541910Z","iopub.status.idle":"2023-09-14T03:07:38.467609Z","shell.execute_reply.started":"2023-09-14T03:07:31.541873Z","shell.execute_reply":"2023-09-14T03:07:38.466465Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test1_idg =  idg.flow_from_dataframe(test_data, \"test1/\", x_col= \"filename\",y_col = 'label',\n                                    batch_size = batch_size,\n                                    target_size=size, shuffle = False)","metadata":{"execution":{"iopub.status.busy":"2023-09-14T03:07:38.472108Z","iopub.execute_input":"2023-09-14T03:07:38.472448Z","iopub.status.idle":"2023-09-14T03:07:38.639435Z","shell.execute_reply.started":"2023-09-14T03:07:38.472419Z","shell.execute_reply":"2023-09-14T03:07:38.638356Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test1_predict = cat_dog_model.predict(test1_idg)\n\ntest1_predict_argmax = np.argmax(test1_predict, axis=1)\n\ny_test_pred = test1_predict_argmax\n\ntest_data['label'] = y_test_pred\n\ntest_data.head()","metadata":{"execution":{"iopub.status.busy":"2023-09-14T03:07:38.641302Z","iopub.execute_input":"2023-09-14T03:07:38.641716Z","iopub.status.idle":"2023-09-14T03:09:32.510946Z","shell.execute_reply.started":"2023-09-14T03:07:38.641679Z","shell.execute_reply":"2023-09-14T03:09:32.508465Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"label_mapping = {0: 'cat', 1: 'dog'}\ntest_data['label'] = test_data['label'].map(label_mapping)\ntest_data.head()","metadata":{"execution":{"iopub.status.busy":"2023-09-14T03:09:32.513879Z","iopub.execute_input":"2023-09-14T03:09:32.514327Z","iopub.status.idle":"2023-09-14T03:09:32.531399Z","shell.execute_reply.started":"2023-09-14T03:09:32.514287Z","shell.execute_reply":"2023-09-14T03:09:32.530144Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a id=\"1\"></a>\n# <div style=\"text-align: center; background-color: #6495ED; font-family:Times New Roman; color: white; padding: 14px; line-height: 1;border-radius:20px\">14. Visualize the predicted results</div>","metadata":{}},{"cell_type":"code","source":"fig, axes = plt.subplots(1, 10, figsize=(20, 10))\nfor idx in range(10):\n    image_path = os.path.join(test_dir, test_data.iloc[idx]['filename'])\n    image = Image.open(image_path)\n    axes[idx].imshow(image)\n    axes[idx].set_title(\"Label: \" + test_data.iloc[idx]['label'])\n    axes[idx].axis('off')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-09-14T03:11:18.422894Z","iopub.execute_input":"2023-09-14T03:11:18.423308Z","iopub.status.idle":"2023-09-14T03:11:19.578292Z","shell.execute_reply.started":"2023-09-14T03:11:18.423276Z","shell.execute_reply":"2023-09-14T03:11:19.577160Z"},"trusted":true},"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"}}