{"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"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":3362,"databundleVersionId":31148,"sourceType":"competition"}],"dockerImageVersionId":30627,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"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 matplotlib.pyplot as plt\nimport tensorflow as tf\n\nimport os\nprint(os.listdir(\"../input\"))\n\nimport zipfile\n\nwith zipfile.ZipFile(\"/kaggle/input/dogs-vs-cats/train.zip\",\"r\") as z:\n    z.extractall(\".\")\n    \nwith zipfile.ZipFile(\"/kaggle/input/dogs-vs-cats/test1.zip\",\"r\") as z:\n    z.extractall(\".\")","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-12-27T03:21:21.585580Z","iopub.execute_input":"2023-12-27T03:21:21.585879Z","iopub.status.idle":"2023-12-27T03:21:34.697812Z","shell.execute_reply.started":"2023-12-27T03:21:21.585854Z","shell.execute_reply":"2023-12-27T03:21:34.697001Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Reads the image, resizes it to 128x128 pixels, and then displays it\n\npath = \"/kaggle/working/train\"\nfor p in os.listdir(path):\n    category = p.split(\".\")[0]\n    img_array = cv2.imread(os.path.join(path,p),cv2.IMREAD_GRAYSCALE)\n    new_img_array = cv2.resize(img_array, dsize=(128, 128))\n    plt.imshow(new_img_array,cmap=\"gray\")\n    break","metadata":{"execution":{"iopub.status.busy":"2023-12-27T04:10:40.830288Z","iopub.execute_input":"2023-12-27T04:10:40.830666Z","iopub.status.idle":"2023-12-27T04:10:41.153115Z","shell.execute_reply.started":"2023-12-27T04:10:40.830633Z","shell.execute_reply":"2023-12-27T04:10:41.152176Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Defined the image width, height, and size for data\nIMAGE_WIDTH=128\nIMAGE_HEIGHT=128\nIMAGE_SIZE=(IMAGE_WIDTH, IMAGE_HEIGHT)","metadata":{"execution":{"iopub.status.busy":"2023-12-27T03:27:42.232666Z","iopub.execute_input":"2023-12-27T03:27:42.233652Z","iopub.status.idle":"2023-12-27T03:27:42.238042Z","shell.execute_reply.started":"2023-12-27T03:27:42.233614Z","shell.execute_reply":"2023-12-27T03:27:42.237060Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Architecture of image classification model**\n\n1. Convolutional Layer with 32 filters and a (3, 3) kernel, followed by BatchNormalization, MaxPooling, and Dropout.\n2. Convolutional Layer with 64 filters and a (3, 3) kernel, followed by BatchNormalization, MaxPooling, and Dropout.\n3. Convolutional Layer with 128 filters and a (3, 3) kernel, followed by BatchNormalization, MaxPooling, and Dropout.\n4. Flatten layer to flatten the output from the previous layers.\n5. Dense layer with 512 units and ReLU activation, followed by BatchNormalization and Dropout.\n6. Output layer with 1 unit and a sigmoid activation function for binary classification.\n\nI'm using BatchNormalization and Dropout after convolutional and dense layers helps with regularization and generalization. The model is compiled with binary cross-entropy loss and the Adam optimizer.","metadata":{}},{"cell_type":"code","source":"from keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D, Dropout, Flatten, Dense, Activation, BatchNormalization\n\nmodel = Sequential()\n\nmodel.add(Conv2D(32, (3, 3), activation='relu', input_shape=(IMAGE_WIDTH, IMAGE_HEIGHT, 1)))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.2))\n\nmodel.add(Conv2D(64, (3, 3), activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.2))\n\nmodel.add(Conv2D(128, (3, 3), activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.2))\n\nmodel.add(Flatten())\nmodel.add(Dense(512, activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.5))\nmodel.add(Dense(1, activation='sigmoid'))\n\nmodel.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\n\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2023-12-27T04:06:58.314738Z","iopub.execute_input":"2023-12-27T04:06:58.315154Z","iopub.status.idle":"2023-12-27T04:06:58.511192Z","shell.execute_reply.started":"2023-12-27T04:06:58.315122Z","shell.execute_reply":"2023-12-27T04:06:58.508993Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**I'm changing the problem to cat detection for classifying images as either containing a cat or not**","metadata":{}},{"cell_type":"code","source":"X = []\ny = []\nconvert = lambda category : int(category == 'cat')\ndef create_test_data(path):\n    for p in os.listdir(path):\n        category = p.split(\".\")[0]\n        category = convert(category)\n        img_array = cv2.imread(os.path.join(path,p),cv2.IMREAD_GRAYSCALE)\n        new_img_array = cv2.resize(img_array, dsize=(128, 128))\n        X.append(new_img_array)\n        y.append(category)","metadata":{"execution":{"iopub.status.busy":"2023-12-27T04:11:25.286509Z","iopub.execute_input":"2023-12-27T04:11:25.286885Z","iopub.status.idle":"2023-12-27T04:11:25.295509Z","shell.execute_reply.started":"2023-12-27T04:11:25.286855Z","shell.execute_reply":"2023-12-27T04:11:25.294568Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"create_test_data(path)\nX = np.array(X).reshape(-1, 128,128,1)\ny = np.array(y)","metadata":{"execution":{"iopub.status.busy":"2023-12-27T04:11:27.504034Z","iopub.execute_input":"2023-12-27T04:11:27.504822Z","iopub.status.idle":"2023-12-27T04:11:49.632192Z","shell.execute_reply.started":"2023-12-27T04:11:27.504789Z","shell.execute_reply":"2023-12-27T04:11:49.631185Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X = X/255.0","metadata":{"execution":{"iopub.status.busy":"2023-12-27T04:12:02.025630Z","iopub.execute_input":"2023-12-27T04:12:02.026405Z","iopub.status.idle":"2023-12-27T04:12:03.020358Z","shell.execute_reply.started":"2023-12-27T04:12:02.026369Z","shell.execute_reply":"2023-12-27T04:12:03.019385Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#fit my model with training data\nmodel.fit(X, y, epochs=50, batch_size=32, validation_split=0.2)","metadata":{"execution":{"iopub.status.busy":"2023-12-27T04:12:04.024381Z","iopub.execute_input":"2023-12-27T04:12:04.025077Z","iopub.status.idle":"2023-12-27T04:23:01.347255Z","shell.execute_reply.started":"2023-12-27T04:12:04.025042Z","shell.execute_reply":"2023-12-27T04:23:01.346188Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Preporcess test data also same as training data**","metadata":{}},{"cell_type":"code","source":"path = \"/kaggle/working/test1\"\nX_test = []\nid_line = []\ndef create_test1_data(path):\n    for p in os.listdir(path):\n        id_line.append(p.split(\".\")[0])\n        img_array = cv2.imread(os.path.join(path,p),cv2.IMREAD_GRAYSCALE)\n        new_img_array = cv2.resize(img_array, dsize=(128, 128))\n        X_test.append(new_img_array)\ncreate_test1_data(path)\nX_test = np.array(X_test).reshape(-1,128,128,1)\nX_test = X_test/255","metadata":{"execution":{"iopub.status.busy":"2023-12-27T04:23:04.683428Z","iopub.execute_input":"2023-12-27T04:23:04.684307Z","iopub.status.idle":"2023-12-27T04:23:15.999997Z","shell.execute_reply.started":"2023-12-27T04:23:04.684271Z","shell.execute_reply":"2023-12-27T04:23:15.999104Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Prediction test data**","metadata":{}},{"cell_type":"code","source":"predictions = model.predict(X_test)","metadata":{"execution":{"iopub.status.busy":"2023-12-27T04:23:17.655851Z","iopub.execute_input":"2023-12-27T04:23:17.656614Z","iopub.status.idle":"2023-12-27T04:23:21.692837Z","shell.execute_reply.started":"2023-12-27T04:23:17.656575Z","shell.execute_reply":"2023-12-27T04:23:21.691977Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predicted_val = [int(round(p[0])) for p in predictions]","metadata":{"execution":{"iopub.status.busy":"2023-12-27T04:23:23.706418Z","iopub.execute_input":"2023-12-27T04:23:23.706875Z","iopub.status.idle":"2023-12-27T04:23:23.743891Z","shell.execute_reply.started":"2023-12-27T04:23:23.706836Z","shell.execute_reply":"2023-12-27T04:23:23.743010Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission_df = pd.DataFrame({'id':id_line, 'label':predicted_val})","metadata":{"execution":{"iopub.status.busy":"2023-12-27T04:23:30.256911Z","iopub.execute_input":"2023-12-27T04:23:30.257318Z","iopub.status.idle":"2023-12-27T04:23:30.269026Z","shell.execute_reply.started":"2023-12-27T04:23:30.257288Z","shell.execute_reply":"2023-12-27T04:23:30.268125Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission_df","metadata":{"execution":{"iopub.status.busy":"2023-12-27T04:23:31.863615Z","iopub.execute_input":"2023-12-27T04:23:31.864505Z","iopub.status.idle":"2023-12-27T04:23:31.875124Z","shell.execute_reply.started":"2023-12-27T04:23:31.864472Z","shell.execute_reply":"2023-12-27T04:23:31.874128Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission_df[\"label\"] = submission_df[\"label\"].replace({0: 'dog', 1: 'cat'}) ","metadata":{"execution":{"iopub.status.busy":"2023-12-27T04:23:34.949008Z","iopub.execute_input":"2023-12-27T04:23:34.949644Z","iopub.status.idle":"2023-12-27T04:23:34.956791Z","shell.execute_reply.started":"2023-12-27T04:23:34.949608Z","shell.execute_reply":"2023-12-27T04:23:34.955995Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**See predicted result with images**","metadata":{}},{"cell_type":"code","source":"from keras.preprocessing.image import load_img\nsample_test = submission_df.head(18)\nsample_test.head()\nplt.figure(figsize=(12, 24))\nfor index, row in sample_test.iterrows():\n    filename = row['id']\n    category = row['label']\n    img = load_img(\"/kaggle/working/test1/\"+filename+\".jpg\", target_size=IMAGE_SIZE)\n    plt.subplot(6, 3, index+1)\n    plt.imshow(img)\n    plt.xlabel(filename + '(' + \"{}\".format(category) + ')' )\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-12-27T04:25:33.276068Z","iopub.execute_input":"2023-12-27T04:25:33.276961Z","iopub.status.idle":"2023-12-27T04:25:37.697075Z","shell.execute_reply.started":"2023-12-27T04:25:33.276902Z","shell.execute_reply":"2023-12-27T04:25:37.695454Z"},"trusted":true},"execution_count":null,"outputs":[]}]}