{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd \nimport cv2\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Flatten, Dropout, Activation, Conv2D, MaxPooling2D\n\nimport os\nprint(os.listdir(\"../input\"))\n\nimport zipfile\n\nwith zipfile.ZipFile(\"../input/dogs-vs-cats/train.zip\",\"r\") as z:\n    z.extractall(\".\")\n    \nwith zipfile.ZipFile(\"../input/dogs-vs-cats/test1.zip\",\"r\") as z:\n    z.extractall(\".\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"main_dir = \"/kaggle/working/\"\ntrain_dir = \"train\"\npath = os.path.join(main_dir,train_dir)\n\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=(80, 80))\n    plt.imshow(new_img_array,cmap=\"gray\")\n    break","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X = []\ny = []\nconvert = lambda category : int(category == 'dog')\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=(80, 80))\n        X.append(new_img_array)\n        y.append(category)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"create_test_data(path)\nX = np.array(X).reshape(-1, 80,80,1)\ny = np.array(y)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X = X/255.0","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Implementation with Keras"},{"metadata":{},"cell_type":"markdown","source":"### **Types of layer in a CNN:**\n\n1. Convolution\n2. Pooling\n3. Fully Connected"},{"metadata":{},"cell_type":"markdown","source":"### Convolution Operation (Conv2D)\n\n* The convulution operation is one of the fundemantal building a CNN.\n* We have a input matrix(the input picture) and a filter(feature detector).\n* Filter usally is a 3x3 matrix but it is not a rule.\n* Filter detects horizantal or vertical lines and convex shape on the picture. For example in a person picture, we can find ears or noise etc."},{"metadata":{},"cell_type":"markdown","source":"## **Pooling Operation (MaxPooling2D)**\n\n We apply pooling to reduce the size of network and speed the computation. We can apply avarage pooling or max pooling. Let's suppose we have 4x4 input matrix, If we apply max pooling then the output will be 2x2 matrix. The way you do that is really simple. It has two hyperparameters, filter size(f) and stride(s).\n "},{"metadata":{},"cell_type":"markdown","source":"![pooling](https://media.geeksforgeeks.org/wp-content/uploads/20190721025744/Screenshot-2019-07-21-at-2.57.13-AM.png)"},{"metadata":{},"cell_type":"markdown","source":"### **Flattening (Flatten())**\n\nFlattening is converting the output of convolutional layers into a 1 dimensional array for inputing  it to next layer. It is connected to fully connected layer.\n\n###### ![flattening](https://miro.medium.com/max/1732/0*4afqrwiDydc8hw7g)"},{"metadata":{"trusted":true},"cell_type":"code","source":"model = Sequential()\n\nmodel.add(Conv2D(32,(3,3), activation = 'relu', input_shape = X.shape[1:]))\nmodel.add(MaxPooling2D(pool_size = (2,2)))\n\nmodel.add(Conv2D(64,(3,3), activation = 'relu'))\nmodel.add(MaxPooling2D(pool_size = (2,2)))\n\n\nmodel.add(Flatten())\nmodel.add(Dense(64, activation = 'relu'))\n\nmodel.add(Dense(1, activation = 'sigmoid'))\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### *Optimizers*\n\nOptimizers are used to change the attributes of a neural network such as weights and learning rate in order to reduce the losses. We will apply Adam optimizer.\n\n\n\n"},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(\n    optimizer = \"adam\",\n    loss = \"binary_crossentropy\",\n    metrics = [\"accuracy\"]\n\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.fit(X, y, epochs=10, batch_size=32, validation_split=0.2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_dir = \"test1\"\npath = os.path.join(main_dir,train_dir)\n#os.listdir(path)\n\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=(80, 80))\n        X_test.append(new_img_array)\ncreate_test1_data(path)\nX_test = np.array(X_test).reshape(-1,80,80,1)\nX_test = X_test/255","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predictions = model.predict(X_test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predicted_val = [int(round(p[0])) for p in predictions]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission_df = pd.DataFrame({'id':id_line, 'label':predicted_val})","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission_df.to_csv(\"submission.csv\", index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"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":4,"nbformat_minor":4}