{"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":"markdown","source":"<div style='background-color: lightblue'><font size='5'><b>What is Convolutional Nueral network?</b></font></br>\n\nA convolutional neural network (CNN) is a type of artificial neural network specifically designed for image recognition and processing. It is composed of a series of interconnected layers that process the input image through a series of convolutions, pooling, and nonlinear activation functions to extract features and make predictions.\n\nConvolutional layers in a CNN apply a set of learnable filters to the input image, which scan the image and identify specific features such as edges, corners, and textures. These features are then passed through nonlinear activation functions, which introduce nonlinearity to the model and allow it to learn more complex relationships between the input and output. Pooling layers are also commonly used in CNNs to reduce the dimensionality of the feature maps and improve the model's ability to generalize to new data.\n\nCNNs have been very successful in a wide range of image recognition tasks, such as object detection, face recognition, and image classification. They are particularly well suited for image processing tasks due to their ability to extract features from images using convolutional filters, which can be learned from data.</div>","metadata":{}},{"cell_type":"markdown","source":"<div style='background-color: lightblue'><font size='5'><b>Why CNN over ANN?</b></font></br>\nConvolutional neural networks (CNNs) are a type of artificial neural network specifically designed for image recognition and processing tasks. They are generally preferred over traditional feedforward neural networks (FFNNs) or artificial neural networks (ANNs) for image processing tasks because they are more efficient at learning and extracting features from images.</br>\n\n\nOne reason CNNs are more efficient at learning image features is because they use convolutional layers, which apply a set of learnable filters to the input image and identify specific features such as edges, corners, and textures. These features are then passed through nonlinear activation functions, which introduce nonlinearity to the model and allow it to learn more complex relationships between the input and output. In contrast, FFNNs and ANNs do not have these specialized layers and must rely on fully connected layers, which can be less efficient at learning image features due to the large number of parameters they require.\n\nAnother reason CNNs are generally preferred for image processing tasks is that they are able to learn more robust and generalizable models by using pooling layers, which reduce the dimensionality of the feature maps and improve the model's ability to generalize to new data. In contrast, FFNNs and ANNs do not have these pooling layers and may be more prone to overfitting.\n\nOverall, CNNs are a powerful tool for image recognition and processing tasks due to their ability to efficiently learn and extract image features, and their ability to learn more robust and generalizable models using pooling layers.</div>\n\n\n","metadata":{}},{"cell_type":"markdown","source":"<div style='background-color: blue'><font size='5'><font color='white'><b>Importing the necessary libraries</b></font></font></div>","metadata":{}},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom tensorflow import keras\nimport zipfile\nfrom zipfile import ZipFile\nimport os\nimport cv2\nimport shutil\nfrom tensorflow import keras\nfrom tensorflow.keras import layers","metadata":{"execution":{"iopub.status.busy":"2022-12-30T14:40:24.266599Z","iopub.execute_input":"2022-12-30T14:40:24.267414Z","iopub.status.idle":"2022-12-30T14:40:31.399190Z","shell.execute_reply.started":"2022-12-30T14:40:24.267233Z","shell.execute_reply":"2022-12-30T14:40:31.397611Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<div style='background-color: blue'><font size='3'><font color='white'><b>Extracting zip file</b></font></font></div>","metadata":{}},{"cell_type":"code","source":"trn_zip=ZipFile(\"/kaggle/input/dogs-vs-cats/train.zip\",\"r\")\ntrn_zip.extractall()","metadata":{"execution":{"iopub.status.busy":"2022-12-30T14:40:31.401746Z","iopub.execute_input":"2022-12-30T14:40:31.402420Z","iopub.status.idle":"2022-12-30T14:40:44.611717Z","shell.execute_reply.started":"2022-12-30T14:40:31.402382Z","shell.execute_reply":"2022-12-30T14:40:44.610372Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"len(os.listdir(\"/kaggle/working/train\"))","metadata":{"execution":{"iopub.status.busy":"2022-12-30T14:40:44.613192Z","iopub.execute_input":"2022-12-30T14:40:44.613704Z","iopub.status.idle":"2022-12-30T14:40:44.638664Z","shell.execute_reply.started":"2022-12-30T14:40:44.613658Z","shell.execute_reply":"2022-12-30T14:40:44.637808Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<div style='background-color: yellow'><font size='2.5'><font color='black'><b>There are 25000 cat, dog images in train directory</b></font></font></div>","metadata":{}},{"cell_type":"markdown","source":"<div style='background-color: blue'><font size='3'><font color='white'><b>Reading image with imread() function and appending the image array and corresponding label in data list</b></font></font></div>","metadata":{}},{"cell_type":"code","source":"data=[]\nsize=120\nimages=os.listdir(\"/kaggle/working/train\")\ntrain_pth=\"/kaggle/working/train\"\nfor img in images:\n    img_path=os.path.join(train_pth,img)\n    if img.split(\".\")[0]==\"cat\":\n        img_arr=cv2.imread(img_path)\n        img_arr=cv2.resize(img_arr,(size,size))\n        data.append([img_arr,0])\n    else:\n        img_arr=cv2.imread(img_path)\n        img_arr=cv2.resize(img_arr,(size,size))\n        data.append([img_arr,1])","metadata":{"execution":{"iopub.status.busy":"2022-12-30T14:40:44.640571Z","iopub.execute_input":"2022-12-30T14:40:44.641478Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<div style='background-color: blue'><font size='3'><font color='white'><b>Lets check one image</b></font></font></div>","metadata":{}},{"cell_type":"code","source":"plt.imshow(data[112][0])","metadata":{"execution":{"iopub.status.idle":"2022-12-30T14:41:40.171470Z","shell.execute_reply.started":"2022-12-30T14:41:39.874233Z","shell.execute_reply":"2022-12-30T14:41:40.170273Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<div style='background-color: blue'><font size='3'><font color='white'><b>X=feautures</br>y=label</b></font></font></div>","metadata":{}},{"cell_type":"code","source":"X=[]\ny=[]","metadata":{"execution":{"iopub.status.busy":"2022-12-30T14:41:40.173363Z","iopub.execute_input":"2022-12-30T14:41:40.173793Z","iopub.status.idle":"2022-12-30T14:41:40.178102Z","shell.execute_reply.started":"2022-12-30T14:41:40.173758Z","shell.execute_reply":"2022-12-30T14:41:40.177170Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for arr in data:\n    X.append(arr[0])\n    y.append(arr[1])","metadata":{"execution":{"iopub.status.busy":"2022-12-30T14:41:40.179484Z","iopub.execute_input":"2022-12-30T14:41:40.180125Z","iopub.status.idle":"2022-12-30T14:41:40.200050Z","shell.execute_reply.started":"2022-12-30T14:41:40.180091Z","shell.execute_reply":"2022-12-30T14:41:40.198736Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X=np.array(X)\ny=np.array(y)","metadata":{"execution":{"iopub.status.busy":"2022-12-30T14:41:40.201279Z","iopub.execute_input":"2022-12-30T14:41:40.202146Z","iopub.status.idle":"2022-12-30T14:41:40.690523Z","shell.execute_reply.started":"2022-12-30T14:41:40.202086Z","shell.execute_reply":"2022-12-30T14:41:40.689494Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X.shape","metadata":{"execution":{"iopub.status.busy":"2022-12-30T14:41:40.691634Z","iopub.execute_input":"2022-12-30T14:41:40.692315Z","iopub.status.idle":"2022-12-30T14:41:40.699572Z","shell.execute_reply.started":"2022-12-30T14:41:40.692264Z","shell.execute_reply":"2022-12-30T14:41:40.698368Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y.shape","metadata":{"execution":{"iopub.status.busy":"2022-12-30T14:41:40.704470Z","iopub.execute_input":"2022-12-30T14:41:40.704935Z","iopub.status.idle":"2022-12-30T14:41:40.713503Z","shell.execute_reply.started":"2022-12-30T14:41:40.704900Z","shell.execute_reply":"2022-12-30T14:41:40.712007Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<div style='background-color: blue'><font size='3'><font color='white'><b>Normalizing the features in X</b></font></font></div>","metadata":{}},{"cell_type":"code","source":"X=X/255","metadata":{"execution":{"iopub.status.busy":"2022-12-30T14:41:40.714599Z","iopub.execute_input":"2022-12-30T14:41:40.714932Z","iopub.status.idle":"2022-12-30T14:41:44.648123Z","shell.execute_reply.started":"2022-12-30T14:41:40.714895Z","shell.execute_reply":"2022-12-30T14:41:44.646990Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<div style='background-color: blue'><font size='3'><font color='white'><b>train-test split</b></font></font></div>","metadata":{}},{"cell_type":"code","source":"X_train,X_test,y_train,y_test=X[:20000],X[20000:],y[:20000],y[20000:]","metadata":{"execution":{"iopub.status.busy":"2022-12-30T14:41:44.649488Z","iopub.execute_input":"2022-12-30T14:41:44.649908Z","iopub.status.idle":"2022-12-30T14:41:44.655340Z","shell.execute_reply.started":"2022-12-30T14:41:44.649868Z","shell.execute_reply":"2022-12-30T14:41:44.654513Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<div style='background-color: blue'><font size='5'><font color='white'><b>Convolutional neural network</b></font></font></div>","metadata":{}},{"cell_type":"code","source":"model=keras.Sequential()\n#first convolutional layer\nmodel.add(layers.Conv2D(filters=64,kernel_size=(3,3),input_shape=(120,120,3),activation=\"relu\"))\nmodel.add(layers.MaxPooling2D((2,2)))\n\n#second convolutional layer\nmodel.add(layers.Conv2D(filters=64,kernel_size=(3,3),activation=\"relu\"))\nmodel.add(layers.MaxPooling2D((2,2)))\n#third convolutional layer\nmodel.add(layers.Conv2D(filters=128,kernel_size=(3,3),activation=\"relu\"))\nmodel.add(layers.MaxPooling2D((2,2)))\n\nmodel.add(layers.Flatten())\n\nmodel.add(layers.Dense(units=128,activation=\"relu\"))\n\nmodel.add(layers.Dense(units=2,activation=\"softmax\"))","metadata":{"execution":{"iopub.status.busy":"2022-12-30T14:41:44.656735Z","iopub.execute_input":"2022-12-30T14:41:44.657077Z","iopub.status.idle":"2022-12-30T14:41:44.859701Z","shell.execute_reply.started":"2022-12-30T14:41:44.657048Z","shell.execute_reply":"2022-12-30T14:41:44.858430Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.callbacks import EarlyStopping\n\nearly_stop = EarlyStopping(monitor='val_loss', patience=5)\nmodel.compile(optimizer=\"adam\",loss=\"sparse_categorical_crossentropy\",metrics=[\"accuracy\"])\nhistory=model.fit(X_train, y_train, epochs=5, validation_data=(X_test, y_test), callbacks=[early_stop])","metadata":{"execution":{"iopub.status.busy":"2022-12-30T14:41:44.861477Z","iopub.execute_input":"2022-12-30T14:41:44.861814Z","iopub.status.idle":"2022-12-30T15:06:18.328177Z","shell.execute_reply.started":"2022-12-30T14:41:44.861784Z","shell.execute_reply":"2022-12-30T15:06:18.327240Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<div style='background-color: yellow'><font size='2.5'><font color='black'><b>Early stopping is a technique that allows you to stop training the model once the performance on the validation set starts to degrade. This can help prevent overfitting, which is when the model performs well on the training data but poorly on the test data. You can use early stopping by specifying the EarlyStopping callback when you fit the model</b></font></font></div>","metadata":{}},{"cell_type":"markdown","source":"<div style='background-color: blue'><font size='5'><font color='white'><b>Performance check</b></font></font></div>","metadata":{}},{"cell_type":"code","source":"print(\"Test Accuracy\",model.evaluate(X_test,y_test))","metadata":{"execution":{"iopub.status.busy":"2022-12-30T15:07:17.964583Z","iopub.execute_input":"2022-12-30T15:07:17.965491Z","iopub.status.idle":"2022-12-30T15:07:36.119709Z","shell.execute_reply.started":"2022-12-30T15:07:17.965445Z","shell.execute_reply":"2022-12-30T15:07:36.118605Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.plot(history.history['accuracy'])\nplt.plot(history.history['val_accuracy'])\nplt.title('Model accuracy')\nplt.ylabel('Accuracy')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Val'], loc='upper left')\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2022-12-30T15:06:18.329927Z","iopub.execute_input":"2022-12-30T15:06:18.330568Z","iopub.status.idle":"2022-12-30T15:06:18.504234Z","shell.execute_reply.started":"2022-12-30T15:06:18.330532Z","shell.execute_reply":"2022-12-30T15:06:18.503085Z"},"trusted":true},"execution_count":null,"outputs":[]}]}