{"metadata":{"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"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-07-03T12:39:04.483445Z","iopub.execute_input":"2022-07-03T12:39:04.483881Z","iopub.status.idle":"2022-07-03T12:39:04.497826Z","shell.execute_reply.started":"2022-07-03T12:39:04.483797Z","shell.execute_reply":"2022-07-03T12:39:04.496356Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# # Table of Contents\n\n\n1. [Importing Libraies](#1)\n \n2.  [Extracting Files](#2)\n\n     2.1 [ Setting Path](#2.1)\n     \n3.  [Making Data Frame](#3)\n\n4.  [Data Distribution](#4)\n\n      4.1 [Displaying Images of Cat](#4.1)\n      \n      4.2  [Displaying Images of Dog](#4.2)\n      \n5. [Siplitting The Data](#5)\n\n    5.1  [Image Data Generator](#5.1)\n    \n6. [Making CNN Model](#6)\n\n    6.1  [Displaying the model](#6.1)\n\n\n7 [Training of Model Model](#7)\n\n\n\n\n     ","metadata":{}},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"markdown","source":"\n# **Classification Basic CNN.**\n\nPlease Vote Up if you like this Note Book\n\nIn this notebook, we will learn how to classify images of dog and cat by building a simple Neural Network.\n\nWhat we will learn:\n\n* Load the images.\n\n* Visulaise the Data distribution of all data.\n\n* Visualizing some of the images\n \n* Making The CNN Network\n\n* Use Image Data Generator\n\n* Graph the training loss and validation loss\n\n* Predict the results\n\n* Confusion Matrix","metadata":{}},{"cell_type":"markdown","source":"<a id=\"1\"></a> <br>\n# 1. Importing Libraries","metadata":{}},{"cell_type":"markdown","source":"We are Importing Libraries.\n\n* Libraries which need for\n\n* Image Processing\n\n* Data visualization\n\n*  Making Model Architecture.\n\n","metadata":{}},{"cell_type":"markdown","source":"\n\n","metadata":{}},{"cell_type":"code","source":"''' importing library''' \n\nimport numpy as np\nimport sys\nimport tensorflow as tf\nimport os\nimport sys\nimport pandas as pd\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.layers import Dense, BatchNormalization\n\n\n%matplotlib inline\nimport matplotlib.image as img\nimport matplotlib.pyplot as plt","metadata":{"execution":{"iopub.status.busy":"2022-07-03T12:39:10.417814Z","iopub.execute_input":"2022-07-03T12:39:10.418229Z","iopub.status.idle":"2022-07-03T12:39:12.408081Z","shell.execute_reply.started":"2022-07-03T12:39:10.418195Z","shell.execute_reply":"2022-07-03T12:39:12.407063Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Setting Seed**","metadata":{}},{"cell_type":"code","source":"'''setting seed'''\nseed = 0\nnp.random.seed(seed)\ntf.random.set_seed(3)","metadata":{"execution":{"iopub.status.busy":"2022-07-03T12:39:12.410089Z","iopub.execute_input":"2022-07-03T12:39:12.410799Z","iopub.status.idle":"2022-07-03T12:39:12.416631Z","shell.execute_reply.started":"2022-07-03T12:39:12.410759Z","shell.execute_reply":"2022-07-03T12:39:12.415701Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a id=\"2\"></a> <br>\n# 2. Extarcting Files","metadata":{}},{"cell_type":"code","source":"import zipfile\n\nzip_files = ['test1', 'train']\n\nfor zip_file in zip_files:\n    with zipfile.ZipFile(\"../input/dogs-vs-cats/{}.zip\".format(zip_file),\"r\") as z:\n        z.extractall(\".\")\n        print(\"{} unzipped\".format(zip_file))","metadata":{"execution":{"iopub.status.busy":"2022-07-03T12:39:14.364490Z","iopub.execute_input":"2022-07-03T12:39:14.365158Z","iopub.status.idle":"2022-07-03T12:39:27.727236Z","shell.execute_reply.started":"2022-07-03T12:39:14.365120Z","shell.execute_reply":"2022-07-03T12:39:27.726315Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"'''test1, train Data is in current working folder'''\nprint(os.listdir('../working'))","metadata":{"execution":{"iopub.status.busy":"2022-07-03T12:39:27.729193Z","iopub.execute_input":"2022-07-03T12:39:27.729678Z","iopub.status.idle":"2022-07-03T12:39:27.735124Z","shell.execute_reply.started":"2022-07-03T12:39:27.729604Z","shell.execute_reply":"2022-07-03T12:39:27.734326Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a id=\"2.1\"></a> <br>\n# 2.1 Setting Path\n\n* Setting the path and Image size ","metadata":{}},{"cell_type":"code","source":"IMAGE_FOLDER_PATH = \"../working/train\"\nFILE_NAMES = os.listdir(IMAGE_FOLDER_PATH)\nWIDTH = 150\nHEIGHT = 150","metadata":{"execution":{"iopub.status.busy":"2022-07-03T12:39:27.736428Z","iopub.execute_input":"2022-07-03T12:39:27.737016Z","iopub.status.idle":"2022-07-03T12:39:27.759455Z","shell.execute_reply.started":"2022-07-03T12:39:27.736979Z","shell.execute_reply":"2022-07-03T12:39:27.758693Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"FILE_NAMES[0:5]","metadata":{"execution":{"iopub.status.busy":"2022-07-03T12:39:30.189966Z","iopub.execute_input":"2022-07-03T12:39:30.190691Z","iopub.status.idle":"2022-07-03T12:39:30.197987Z","shell.execute_reply.started":"2022-07-03T12:39:30.190634Z","shell.execute_reply":"2022-07-03T12:39:30.197000Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"labels = []\nfor i in os.listdir(IMAGE_FOLDER_PATH):\n    labels+=[i]","metadata":{"execution":{"iopub.status.busy":"2022-07-03T12:39:31.154802Z","iopub.execute_input":"2022-07-03T12:39:31.155573Z","iopub.status.idle":"2022-07-03T12:39:31.180422Z","shell.execute_reply.started":"2022-07-03T12:39:31.155535Z","shell.execute_reply":"2022-07-03T12:39:31.179542Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a id=\"3\"></a> <br>\n# 3 Making Data Frame","metadata":{}},{"cell_type":"code","source":"# empty list\ntargets = list()\nfull_paths = list()\ntrain_cats_dir = list()\ntrain_dogs_dir = list()\n\n# finding each file's target\nfor file_name in FILE_NAMES:\n    target = file_name.split(\".\")[0] # target name\n    full_path = os.path.join(IMAGE_FOLDER_PATH, file_name)\n    \n    if(target == \"dog\"):\n        train_dogs_dir.append(full_path)\n    if(target == \"cat\"):\n        train_cats_dir.append(full_path)\n    \n    full_paths.append(full_path)\n    targets.append(target)\n\ndataset = pd.DataFrame() # make dataframe\ndataset['image_path'] = full_paths # file path\ndataset['target'] = targets # file's target","metadata":{"execution":{"iopub.status.busy":"2022-07-03T12:39:32.972931Z","iopub.execute_input":"2022-07-03T12:39:32.973289Z","iopub.status.idle":"2022-07-03T12:39:33.058370Z","shell.execute_reply.started":"2022-07-03T12:39:32.973258Z","shell.execute_reply":"2022-07-03T12:39:33.057667Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dataset.head(10)","metadata":{"execution":{"iopub.status.busy":"2022-07-03T12:39:33.721012Z","iopub.execute_input":"2022-07-03T12:39:33.721316Z","iopub.status.idle":"2022-07-03T12:39:33.733221Z","shell.execute_reply.started":"2022-07-03T12:39:33.721290Z","shell.execute_reply":"2022-07-03T12:39:33.732360Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"total data counts:\", dataset['target'].count())\ncounts = dataset['target'].value_counts()\nprint(counts)","metadata":{"execution":{"iopub.status.busy":"2022-07-03T12:39:34.355624Z","iopub.execute_input":"2022-07-03T12:39:34.356283Z","iopub.status.idle":"2022-07-03T12:39:34.370029Z","shell.execute_reply.started":"2022-07-03T12:39:34.356253Z","shell.execute_reply":"2022-07-03T12:39:34.368145Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a id=\"4\"></a> <br>\n# 4 Data Distributation","metadata":{}},{"cell_type":"code","source":"label_count=dataset['target'].value_counts()\nexplode = (0.01,0.01)  \n\nfig1, ax1 = plt.subplots(figsize=(5,5))\nax1.pie(label_count.values, explode=explode, labels=label_count.index, autopct='%1.1f%%',\n        shadow=True, startangle=90)\nax1.axis('equal') \nplt.title('Target Distribution')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-07-03T12:39:36.077365Z","iopub.execute_input":"2022-07-03T12:39:36.077984Z","iopub.status.idle":"2022-07-03T12:39:36.195589Z","shell.execute_reply.started":"2022-07-03T12:39:36.077947Z","shell.execute_reply":"2022-07-03T12:39:36.194606Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a id=\"4.1\"></a> <br>\n# 4.1 Displaying Images of Cat","metadata":{}},{"cell_type":"code","source":"rows = 4\ncols = 4\naxes = []\nfig=plt.figure(figsize=(10,10))\ni = 0\n\nfor a in range(rows*cols):\n    b = img.imread(train_cats_dir[i])\n    axes.append(fig.add_subplot(rows,cols,a+1))\n    plt.imshow(b)\n    i+=1\nfig.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-07-03T12:39:37.561286Z","iopub.execute_input":"2022-07-03T12:39:37.562116Z","iopub.status.idle":"2022-07-03T12:39:39.470265Z","shell.execute_reply.started":"2022-07-03T12:39:37.562066Z","shell.execute_reply":"2022-07-03T12:39:39.469483Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a id=\"4.2\"></a> <br>\n# 4.2 Displaying Images of Dog","metadata":{}},{"cell_type":"code","source":"rows = 4\ncols = 4\naxes = []\nfig=plt.figure(figsize=(10,10))\ni = 0\n\nfor a in range(rows*cols):\n    b = img.imread(train_dogs_dir[i])\n    axes.append(fig.add_subplot(rows,cols,a+1))\n    plt.imshow(b)\n    i+=1\nfig.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-07-03T12:39:39.471490Z","iopub.execute_input":"2022-07-03T12:39:39.471832Z","iopub.status.idle":"2022-07-03T12:39:41.514091Z","shell.execute_reply.started":"2022-07-03T12:39:39.471801Z","shell.execute_reply":"2022-07-03T12:39:41.513060Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a id=\"5\"></a> <br>\n# 5 Splitting The data","metadata":{}},{"cell_type":"code","source":"dataset_train, dataset_test = train_test_split(dataset, test_size=0.2, random_state=seed)","metadata":{"execution":{"iopub.status.busy":"2022-07-03T12:39:41.515874Z","iopub.execute_input":"2022-07-03T12:39:41.516290Z","iopub.status.idle":"2022-07-03T12:39:41.527925Z","shell.execute_reply.started":"2022-07-03T12:39:41.516255Z","shell.execute_reply":"2022-07-03T12:39:41.526790Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# **Data Distributaion Visulatization**","metadata":{}},{"cell_type":"code","source":"class_id_distributionTrain = dataset_train['target'].value_counts()\nclass_id_distributionTrain.head(10)","metadata":{"execution":{"iopub.status.busy":"2022-07-03T12:39:43.451151Z","iopub.execute_input":"2022-07-03T12:39:43.451793Z","iopub.status.idle":"2022-07-03T12:39:43.462312Z","shell.execute_reply.started":"2022-07-03T12:39:43.451759Z","shell.execute_reply":"2022-07-03T12:39:43.461516Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(13,5))\nplt.xticks(np.arange(43))\nplt.bar(class_id_distributionTrain.index, class_id_distributionTrain.values)","metadata":{"execution":{"iopub.status.busy":"2022-07-03T12:39:44.494938Z","iopub.execute_input":"2022-07-03T12:39:44.495543Z","iopub.status.idle":"2022-07-03T12:39:44.696981Z","shell.execute_reply.started":"2022-07-03T12:39:44.495509Z","shell.execute_reply":"2022-07-03T12:39:44.696067Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"label_count=dataset_train['target'].value_counts()\nexplode = (0.01,0.01)  \n\nfig1, ax1 = plt.subplots(figsize=(5,5))\nax1.pie(label_count.values, explode=explode, labels=label_count.index, autopct='%1.1f%%',\n        shadow=True, startangle=90)\nax1.axis('equal') \nplt.title('Target Distribution')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-07-03T12:39:45.497015Z","iopub.execute_input":"2022-07-03T12:39:45.497322Z","iopub.status.idle":"2022-07-03T12:39:45.610509Z","shell.execute_reply.started":"2022-07-03T12:39:45.497296Z","shell.execute_reply":"2022-07-03T12:39:45.609633Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class_id_distributionTest = dataset_test['target'].value_counts()\nclass_id_distributionTest.head(10)","metadata":{"execution":{"iopub.status.busy":"2022-07-03T12:39:46.553058Z","iopub.execute_input":"2022-07-03T12:39:46.553410Z","iopub.status.idle":"2022-07-03T12:39:46.563496Z","shell.execute_reply.started":"2022-07-03T12:39:46.553376Z","shell.execute_reply":"2022-07-03T12:39:46.562681Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"label_count=dataset_test['target'].value_counts()\nexplode = (0.01,0.01)  \n\nfig1, ax1 = plt.subplots(figsize=(5,5))\nax1.pie(label_count.values, explode=explode, labels=label_count.index, autopct='%1.1f%%',\n        shadow=True, startangle=90)\nax1.axis('equal') \nplt.title('Target Distribution')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-07-03T12:39:47.853127Z","iopub.execute_input":"2022-07-03T12:39:47.853504Z","iopub.status.idle":"2022-07-03T12:39:47.967599Z","shell.execute_reply.started":"2022-07-03T12:39:47.853473Z","shell.execute_reply":"2022-07-03T12:39:47.966676Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a id=\"5.1\"></a> <br>\n# 5.1 Image DataGenerator\n\nWhen there is little data to train, we have to use ImageDataGenerator to increase the number of data.\nIt is recommended to use only scaling for test data.\n\n1. rescale = 1./255 : change the value between 0 and 1\n\n2. rotation_range = 15 : Random rotation within 15 degrees\n\n3. shear_range = 0.1 : shear range 10%\n\n4. zoom_range = 0.2 : zoom range 20%\n\n5. horizontal_flip = True : Randomly flip horizontally.\n\n6. width_shift_range = 0.1 : Randomly move the original image horizontally within 10% of the width\n\n7. height_shift_range=0.1 : Randomly move the original image vertically within 10% of the width\n","metadata":{}},{"cell_type":"code","source":"train_datagen=ImageDataGenerator(\nrotation_range=15,\nrescale=1./255,\nshear_range=0.1,\nzoom_range=0.2,\nhorizontal_flip=True,\nwidth_shift_range=0.1,\nheight_shift_range=0.1)\n\ntrain_datagenerator=train_datagen.flow_from_dataframe(dataframe=dataset_train,\n                                                     x_col=\"image_path\",\n                                                     y_col=\"target\",\n                                                     target_size=(WIDTH, HEIGHT),\n                                                     class_mode=\"binary\",\n                                                     batch_size=150)","metadata":{"execution":{"iopub.status.busy":"2022-07-03T12:39:49.934385Z","iopub.execute_input":"2022-07-03T12:39:49.934771Z","iopub.status.idle":"2022-07-03T12:39:50.130340Z","shell.execute_reply.started":"2022-07-03T12:39:49.934740Z","shell.execute_reply":"2022-07-03T12:39:50.129592Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_datagen = ImageDataGenerator(rescale=1./255)\ntest_datagenerator=test_datagen.flow_from_dataframe(dataframe=dataset_test,\n                                                   x_col=\"image_path\",\n                                                   y_col=\"target\",\n                                                   target_size=(WIDTH, HEIGHT),\n                                                   class_mode=\"binary\",\n                                                   batch_size=150)","metadata":{"execution":{"iopub.status.busy":"2022-07-03T12:39:51.179130Z","iopub.execute_input":"2022-07-03T12:39:51.179776Z","iopub.status.idle":"2022-07-03T12:39:51.238887Z","shell.execute_reply.started":"2022-07-03T12:39:51.179740Z","shell.execute_reply":"2022-07-03T12:39:51.238031Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a id=\"6\"></a> <br>\n# 6 Making CNN Model","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras.layers import Dense, BatchNormalization\nmodel = Sequential() # implement model layer \nmodel.add(Conv2D(32, kernel_size=(3,3), input_shape=(WIDTH, HEIGHT, 3), activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2,2)))\nmodel.add(Conv2D(64, kernel_size=(3,3), activation = 'relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2,2)))\n#model.add(MaxPooling2D(pool_size=2))\nmodel.add(Dense(1280, activation='relu'))\nmodel.add(Dropout(0.5))\n\nmodel.add(Dense(3, activation='softmax'))\n#model.add(Dropout(0.5))\n#model.add(Dense(1, activation='sigmoid'))\nmodel.add(Flatten())","metadata":{"execution":{"iopub.status.busy":"2022-07-03T12:40:02.438847Z","iopub.execute_input":"2022-07-03T12:40:02.439226Z","iopub.status.idle":"2022-07-03T12:40:03.534407Z","shell.execute_reply.started":"2022-07-03T12:40:02.439195Z","shell.execute_reply":"2022-07-03T12:40:03.533596Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a id=\"6.1\"></a> <br>\n# 6.1 Displaying Model","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras.utils import plot_model\nfrom IPython.display import Image\nplot_model(model, to_file='convnet.png', show_shapes=True,show_layer_names=True)\nImage(filename='convnet.png') ","metadata":{"execution":{"iopub.status.busy":"2022-07-03T12:40:09.976549Z","iopub.execute_input":"2022-07-03T12:40:09.977079Z","iopub.status.idle":"2022-07-03T12:40:10.132419Z","shell.execute_reply.started":"2022-07-03T12:40:09.977035Z","shell.execute_reply":"2022-07-03T12:40:10.131503Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(loss=\"binary_crossentropy\", optimizer='adam', metrics=['accuracy'])\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2022-07-03T12:40:25.082340Z","iopub.execute_input":"2022-07-03T12:40:25.082753Z","iopub.status.idle":"2022-07-03T12:40:25.101943Z","shell.execute_reply.started":"2022-07-03T12:40:25.082717Z","shell.execute_reply":"2022-07-03T12:40:25.100971Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a id=\"7\"></a> <br>\n# 7 Train The model","metadata":{}},{"cell_type":"code","source":"History=model.fit(train_datagenerator,\n                       epochs=1,\n                       validation_data=test_datagenerator,\n                       validation_steps=dataset_test.shape[0]/150,\n                       steps_per_epoch=dataset_train.shape[0]/150)","metadata":{"execution":{"iopub.status.busy":"2022-07-03T12:46:00.329285Z","iopub.execute_input":"2022-07-03T12:46:00.329710Z","iopub.status.idle":"2022-07-03T12:48:58.793912Z","shell.execute_reply.started":"2022-07-03T12:46:00.329672Z","shell.execute_reply":"2022-07-03T12:48:58.793036Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a id=\"8\"></a> <br>\n# 8 Plotting The Result","metadata":{}},{"cell_type":"code","source":"acc = History.history['accuracy']\nval_acc = History.history['val_accuracy']\nloss = History.history['loss']\nval_loss = History.history['val_loss']\n\nepochs = range(len(acc))\n\nplt.plot(epochs, acc, 'bo', label='Training accuracy')\nplt.plot(epochs, val_acc, 'b', label='Validation accuracy')\nplt.title('Training and validation accuracy')\nplt.legend()\n\nplt.figure()\n\nplt.plot(epochs, loss, 'go', label='Training Loss')\nplt.plot(epochs, val_loss, 'g', label='Validation Loss')\nplt.title('Training and validation loss')\nplt.legend()\n\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-07-03T12:49:05.453428Z","iopub.execute_input":"2022-07-03T12:49:05.454043Z","iopub.status.idle":"2022-07-03T12:49:05.833096Z","shell.execute_reply.started":"2022-07-03T12:49:05.454005Z","shell.execute_reply":"2022-07-03T12:49:05.832347Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"[](http://)","metadata":{}},{"cell_type":"markdown","source":"\n\n<a id=\"9\"></a> <br>\n# 9 Predict the Results","metadata":{}},{"cell_type":"code","source":" test_loss, test_acc = model.evaluate(test_datagenerator, steps=len(test_datagenerator), verbose=1)\n print('Loss: %.3f' % (test_loss * 100.0))\n print('Accuracy: %.3f' % (test_acc * 100.0)) ","metadata":{"execution":{"iopub.status.busy":"2022-07-03T12:49:08.933927Z","iopub.execute_input":"2022-07-03T12:49:08.934309Z","iopub.status.idle":"2022-07-03T12:49:24.736904Z","shell.execute_reply.started":"2022-07-03T12:49:08.934277Z","shell.execute_reply":"2022-07-03T12:49:24.736110Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Confusion Matrix","metadata":{}},{"cell_type":"code","source":"from sklearn.metrics import confusion_matrix\nimport itertools","metadata":{"execution":{"iopub.status.busy":"2022-07-03T12:49:49.631962Z","iopub.execute_input":"2022-07-03T12:49:49.632330Z","iopub.status.idle":"2022-07-03T12:49:49.637394Z","shell.execute_reply.started":"2022-07-03T12:49:49.632300Z","shell.execute_reply":"2022-07-03T12:49:49.636094Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predictions = model.predict(x=test_datagenerator, steps= len(test_datagenerator), verbose=0)","metadata":{"execution":{"iopub.status.busy":"2022-07-03T12:49:55.546989Z","iopub.execute_input":"2022-07-03T12:49:55.547348Z","iopub.status.idle":"2022-07-03T12:50:12.847007Z","shell.execute_reply.started":"2022-07-03T12:49:55.547320Z","shell.execute_reply":"2022-07-03T12:50:12.846010Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_datagenerator.classes","metadata":{"execution":{"iopub.status.busy":"2022-07-03T12:50:12.848735Z","iopub.execute_input":"2022-07-03T12:50:12.849096Z","iopub.status.idle":"2022-07-03T12:50:12.873614Z","shell.execute_reply.started":"2022-07-03T12:50:12.849061Z","shell.execute_reply":"2022-07-03T12:50:12.872811Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cm = confusion_matrix(y_true=test_datagenerator.classes, y_pred=np.argmax(predictions, axis=-1))","metadata":{"execution":{"iopub.status.busy":"2022-07-03T12:50:17.034170Z","iopub.execute_input":"2022-07-03T12:50:17.034523Z","iopub.status.idle":"2022-07-03T12:50:17.108649Z","shell.execute_reply.started":"2022-07-03T12:50:17.034494Z","shell.execute_reply":"2022-07-03T12:50:17.107922Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def plot_confusion_matrix(cm, classes,normalize=False,title='Confusion matrix',cmap=plt.cm.Blues):\n    \n    plt.imshow(cm, interpolation='nearest', cmap=cmap)\n    plt.title(title)\n    plt.colorbar()\n    tick_marks = np.arange(len(classes))\n    plt.xticks(tick_marks, classes, rotation=45)\n    plt.yticks(tick_marks, classes)\n    if normalize:\n        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n        print(\"Normalized confusion matrix\")\n    else:\n        print('Confusion matrix, without normalization')\n        print(cm)\n    \n    thresh = cm.max() / 2.\n    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n        plt.text(j, i, cm[i, j],\n        horizontalalignment=\"center\",\n        color=\"white\" if cm[i, j] > thresh else \"black\")\n        plt.tight_layout()\n        plt.ylabel('True label')\n        plt.xlabel('Predicted label')","metadata":{"execution":{"iopub.status.busy":"2022-07-03T12:50:18.065305Z","iopub.execute_input":"2022-07-03T12:50:18.066963Z","iopub.status.idle":"2022-07-03T12:50:18.076539Z","shell.execute_reply.started":"2022-07-03T12:50:18.066916Z","shell.execute_reply":"2022-07-03T12:50:18.075744Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"\n\n\n<a id=\"10\"></a> <br>\n# 10 onfusion Matrix Plot\n","metadata":{}},{"cell_type":"code","source":"cm_plot_labels = ['0_cat', '1_dog']\n\nplot_confusion_matrix(cm=cm, classes=cm_plot_labels, title='Confusion Matrix')","metadata":{"execution":{"iopub.status.busy":"2022-07-03T12:50:19.748274Z","iopub.execute_input":"2022-07-03T12:50:19.748937Z","iopub.status.idle":"2022-07-03T12:53:42.930912Z","shell.execute_reply.started":"2022-07-03T12:50:19.748899Z","shell.execute_reply":"2022-07-03T12:53:42.929484Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}