{"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":"# Importing Libraries\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras import layers\nfrom keras import models\nimport os\nfrom sklearn.model_selection import train_test_split\nimport shutil\nimport random\nimport math\nimport numpy as np\nimport zipfile\nimport pandas as pd\nimport matplotlib.image as mpimg\nimport matplotlib.pyplot as plt","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-06-05T19:21:31.755331Z","iopub.execute_input":"2023-06-05T19:21:31.755798Z","iopub.status.idle":"2023-06-05T19:21:39.885884Z","shell.execute_reply.started":"2023-06-05T19:21:31.755764Z","shell.execute_reply":"2023-06-05T19:21:39.884972Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Extracting Training Data\ntrain = '/kaggle/input/dogs-vs-cats/train.zip'\ndestination = '/kaggle/working/train_images/'\n\nos.makedirs(destination,exist_ok=True)\n\nwith zipfile.ZipFile(train,'r') as zip_ref:\n    zip_ref.extractall(destination)\n    ","metadata":{"execution":{"iopub.status.busy":"2023-06-05T19:21:39.887149Z","iopub.execute_input":"2023-06-05T19:21:39.891291Z","iopub.status.idle":"2023-06-05T19:21:51.213083Z","shell.execute_reply.started":"2023-06-05T19:21:39.891261Z","shell.execute_reply":"2023-06-05T19:21:51.211970Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"r='/kaggle/working/train_images'\nprint(os.listdir(r))","metadata":{"execution":{"iopub.status.busy":"2023-06-05T19:21:51.216516Z","iopub.execute_input":"2023-06-05T19:21:51.217159Z","iopub.status.idle":"2023-06-05T19:21:51.226382Z","shell.execute_reply.started":"2023-06-05T19:21:51.217131Z","shell.execute_reply":"2023-06-05T19:21:51.225261Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"path='/kaggle/working/train_images/train/'","metadata":{"execution":{"iopub.status.busy":"2023-06-05T19:21:51.230439Z","iopub.execute_input":"2023-06-05T19:21:51.230723Z","iopub.status.idle":"2023-06-05T19:21:51.236934Z","shell.execute_reply.started":"2023-06-05T19:21:51.230698Z","shell.execute_reply":"2023-06-05T19:21:51.236022Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Number of Images\nprint(f\"We have total {len(os.listdir(path))} images in our training data.\")","metadata":{"execution":{"iopub.status.busy":"2023-06-05T19:21:51.238388Z","iopub.execute_input":"2023-06-05T19:21:51.238979Z","iopub.status.idle":"2023-06-05T19:21:51.263628Z","shell.execute_reply.started":"2023-06-05T19:21:51.238945Z","shell.execute_reply":"2023-06-05T19:21:51.262586Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Exploring Training Data\nprint(f\"First 20 filenames: \\n {os.listdir(path)[:20]}\")","metadata":{"execution":{"iopub.status.busy":"2023-06-05T19:21:51.265220Z","iopub.execute_input":"2023-06-05T19:21:51.265561Z","iopub.status.idle":"2023-06-05T19:21:51.287070Z","shell.execute_reply.started":"2023-06-05T19:21:51.265530Z","shell.execute_reply":"2023-06-05T19:21:51.286032Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.image as mpimg\nimages =os.listdir(path)\n\n\nlabels, heights, widths, channels, filesize = [], [], [], [], []\n\nfor fname in images:\n    labels.append(str(fname)[:3])\n    img_shape = mpimg.imread(path+fname).shape\n    heights.append(img_shape[0])\n    widths.append(img_shape[1])\n    channels.append(img_shape[2])\n    filesize.append(os.path.getsize(path+fname))\n\ndf = pd.DataFrame({'images': images, 'class': labels, 'height': heights,\n                         'width': widths, 'channels': channels, 'filesize': filesize})","metadata":{"execution":{"iopub.status.busy":"2023-06-05T19:21:51.288736Z","iopub.execute_input":"2023-06-05T19:21:51.289109Z","iopub.status.idle":"2023-06-05T19:22:21.664787Z","shell.execute_reply.started":"2023-06-05T19:21:51.289075Z","shell.execute_reply":"2023-06-05T19:22:21.663837Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.head()","metadata":{"execution":{"iopub.status.busy":"2023-06-05T19:22:21.666298Z","iopub.execute_input":"2023-06-05T19:22:21.666654Z","iopub.status.idle":"2023-06-05T19:22:21.684821Z","shell.execute_reply.started":"2023-06-05T19:22:21.666621Z","shell.execute_reply":"2023-06-05T19:22:21.683835Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print((df['class']).value_counts())\ndogsVScats_count = df['class'].value_counts().plot.bar(title='Number of Dog vs Cat Images in Training Data')","metadata":{"execution":{"iopub.status.busy":"2023-06-05T19:22:21.686308Z","iopub.execute_input":"2023-06-05T19:22:21.686671Z","iopub.status.idle":"2023-06-05T19:22:21.991861Z","shell.execute_reply.started":"2023-06-05T19:22:21.686636Z","shell.execute_reply":"2023-06-05T19:22:21.990853Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Lets now look at few images from our dataset\nimport matplotlib.pyplot as plt\n\nfig = plt.gcf()\nfig.set_size_inches(3*4, 3*4)\n\nfor i in range(12):\n    sample = np.random.choice(images)\n    img_path =path+sample\n    sp = plt.subplot(3, 4, i + 1)\n    sp.axis('Off')\n    img = mpimg.imread(img_path)\n    plt.imshow(img)\n    plt.title(sample[:3])\n\nplt.show()\n\n","metadata":{"execution":{"iopub.status.busy":"2023-06-05T19:22:21.993309Z","iopub.execute_input":"2023-06-05T19:22:21.993641Z","iopub.status.idle":"2023-06-05T19:22:23.354222Z","shell.execute_reply.started":"2023-06-05T19:22:21.993615Z","shell.execute_reply":"2023-06-05T19:22:23.352692Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train , val =train_test_split(df[['images' , 'class']] ,test_size=0.3 ,random_state=42 , shuffle=True)","metadata":{"execution":{"iopub.status.busy":"2023-06-05T19:22:23.355232Z","iopub.execute_input":"2023-06-05T19:22:23.355547Z","iopub.status.idle":"2023-06-05T19:22:23.374346Z","shell.execute_reply.started":"2023-06-05T19:22:23.355520Z","shell.execute_reply":"2023-06-05T19:22:23.373027Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(train)\nprint(val)","metadata":{"execution":{"iopub.status.busy":"2023-06-05T19:22:23.376305Z","iopub.execute_input":"2023-06-05T19:22:23.377063Z","iopub.status.idle":"2023-06-05T19:22:23.389839Z","shell.execute_reply.started":"2023-06-05T19:22:23.377027Z","shell.execute_reply":"2023-06-05T19:22:23.388991Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# data augmentation\ntrain_datagen=ImageDataGenerator(rescale = 1.0/255,\n                                    rotation_range=40,\n                                    shear_range=0.2,\n                                    zoom_range=0.2,\n                                    horizontal_flip=True,\n                                    fill_mode='nearest')\ntest_datagen=ImageDataGenerator(rescale=1./255)\n\n\ntrain_generator=train_datagen.flow_from_dataframe(\n    train ,path,\n    target_size=(150,150),\n    batch_size=50,\n    class_mode='binary',\n    x_col='images',\n    y_col='class',\n    )\n\nval_generator=test_datagen.flow_from_dataframe(\n    val ,path,   \n    target_size=(150,150),\n    batch_size=50,\n    class_mode='binary',\n    x_col='images',\n    y_col='class',)","metadata":{"execution":{"iopub.status.busy":"2023-06-05T19:22:23.394066Z","iopub.execute_input":"2023-06-05T19:22:23.394639Z","iopub.status.idle":"2023-06-05T19:22:23.709897Z","shell.execute_reply.started":"2023-06-05T19:22:23.394604Z","shell.execute_reply":"2023-06-05T19:22:23.708951Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample = df.sample(n=1)\nsample_generator = train_datagen.flow_from_dataframe(\n    sample, \n    path, \n    x_col='images',\n    y_col='class',\n    target_size=(150,150),\n    class_mode='categorical'\n)\n\nplt.figure(figsize=(10, 10))\nfor i in range(9):\n    plt.subplot(3, 3, i+1)\n    for x_batch, y_batch in sample_generator:\n        image = x_batch[0]\n        plt.imshow(image)\n        plt.axis('Off')\n        break\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-06-05T19:22:23.711279Z","iopub.execute_input":"2023-06-05T19:22:23.711724Z","iopub.status.idle":"2023-06-05T19:22:24.903566Z","shell.execute_reply.started":"2023-06-05T19:22:23.711690Z","shell.execute_reply":"2023-06-05T19:22:24.902678Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model=models.Sequential()\nmodel.add(layers.Conv2D(32 ,(3,3) , activation='relu' , input_shape=(150,150,3 ) ) )\nmodel.add(layers.MaxPooling2D( (2,2)))\n\nmodel.add(layers.Conv2D(64 , (3,3) , activation='relu'))\nmodel.add(layers.MaxPooling2D( (2,2)))\n\nmodel.add(layers.Conv2D(128 , (3,3) , activation='relu'))\nmodel.add(layers.MaxPooling2D( (2,2)))\n          \nmodel.add(layers.Conv2D(128 , (3,3) , activation='relu'))\nmodel.add(layers.MaxPooling2D( (2,2)))","metadata":{"execution":{"iopub.status.busy":"2023-06-05T19:22:24.905046Z","iopub.execute_input":"2023-06-05T19:22:24.905607Z","iopub.status.idle":"2023-06-05T19:22:28.382612Z","shell.execute_reply.started":"2023-06-05T19:22:24.905575Z","shell.execute_reply":"2023-06-05T19:22:28.381683Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.add(layers.Flatten() )\nmodel.add(layers.Dropout(0.25))\nmodel.add(layers.Dense( 512 ,activation='relu' ))\nmodel.add(layers.Dropout(0.25))\nmodel.add(layers.Dense( 1 , activation='sigmoid' ) )","metadata":{"execution":{"iopub.status.busy":"2023-06-05T19:22:28.383937Z","iopub.execute_input":"2023-06-05T19:22:28.384451Z","iopub.status.idle":"2023-06-05T19:22:28.448331Z","shell.execute_reply.started":"2023-06-05T19:22:28.384420Z","shell.execute_reply":"2023-06-05T19:22:28.447530Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"execution":{"iopub.status.busy":"2023-06-05T19:22:28.449558Z","iopub.execute_input":"2023-06-05T19:22:28.450063Z","iopub.status.idle":"2023-06-05T19:22:28.502533Z","shell.execute_reply.started":"2023-06-05T19:22:28.450032Z","shell.execute_reply":"2023-06-05T19:22:28.501929Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras import optimizers\nmodel.compile(loss='binary_crossentropy' , optimizer='adam' , metrics=['acc'] ,)","metadata":{"execution":{"iopub.status.busy":"2023-06-05T19:42:54.430985Z","iopub.execute_input":"2023-06-05T19:42:54.431350Z","iopub.status.idle":"2023-06-05T19:42:54.446877Z","shell.execute_reply.started":"2023-06-05T19:42:54.431320Z","shell.execute_reply":"2023-06-05T19:42:54.445902Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history=model.fit_generator(train_generator , steps_per_epoch=100 , epochs=30 , validation_data=val_generator , validation_steps=50)","metadata":{"execution":{"iopub.status.busy":"2023-06-05T19:43:00.012338Z","iopub.execute_input":"2023-06-05T19:43:00.012698Z","iopub.status.idle":"2023-06-05T20:02:24.526298Z","shell.execute_reply.started":"2023-06-05T19:43:00.012667Z","shell.execute_reply":"2023-06-05T20:02:24.525045Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#  Accuracy and Loss Curves \nacc = history.history['acc']\nval_acc = history.history['val_acc']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs   = range(len(acc))\n\nplt.plot(epochs, acc, label=\"Training accuracy\")\nplt.plot(epochs, val_acc, label=\"Validation accuracy\")\nplt.title('Training and validation accuracy')\nplt.legend()\nplt.show()\n\nplt.plot(epochs, loss, label=\"Training loss\")\nplt.plot(epochs, val_loss, label=\"Validation loss\")\nplt.title('Training and validation loss')\nplt.legend()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-06-05T20:03:09.837957Z","iopub.execute_input":"2023-06-05T20:03:09.838309Z","iopub.status.idle":"2023-06-05T20:03:10.376706Z","shell.execute_reply.started":"2023-06-05T20:03:09.838278Z","shell.execute_reply":"2023-06-05T20:03:10.375731Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Model Evaluation\n\n\nloss, accuracy = model.evaluate_generator(val_generator)\nprint(\"Test: accuracy = %f  ;  loss = %f \" % (accuracy, loss))","metadata":{"execution":{"iopub.status.busy":"2023-06-05T20:32:32.390320Z","iopub.execute_input":"2023-06-05T20:32:32.390687Z","iopub.status.idle":"2023-06-05T20:32:43.469494Z","shell.execute_reply.started":"2023-06-05T20:32:32.390657Z","shell.execute_reply":"2023-06-05T20:32:43.468593Z"},"trusted":true},"execution_count":null,"outputs":[]}]}