{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"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 in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport tensorflow as tf\n\n# Input data files are available in the \"../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# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"main_dir = \"../input/\"\ntrain_dir = \"dogs-vs-cats/\"\npath = os.path.join(main_dir,train_dir)\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## **Reading and Labeling Data**"},{"metadata":{"trusted":true},"cell_type":"code","source":"import zipfile\n\nimport zipfile\nwith zipfile.ZipFile(\"/kaggle/input/dogs-vs-cats/train.zip\", 'r') as zip_ref:\n    zip_ref.extractall(\"./kaggle/input/data/train/\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"with zipfile.ZipFile(\"/kaggle/input/dogs-vs-cats/test1.zip\", 'r') as zip_ref:\n    zip_ref.extractall(\"./kaggle/input/data/test/\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import cv2\nimport matplotlib.pyplot as plt\n\ntrain_data_path = \"./kaggle/input/data/train/train/\"\n\nfor f in os.listdir(train_data_path):\n    # Load an color image in grayscale\n    print(f)\n    img = cv2.imread(train_data_path + str(f),cv2.IMREAD_GRAYSCALE)\n    resized_img = cv2.resize(img, dsize =(80,80))\n    plt.imshow(resized_img)\n    break","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#label the train data form the file names\nX_train_orig = []\ny_train_orig = []\n\ntrain_data_path = \"./kaggle/input/data/train/train/\"\n\nfor f in os.listdir(train_data_path):\n    y_train_orig.append(int(f.split('.')[0] == \"dog\"))\n    img = cv2.imread(train_data_path+str(f), cv2.IMREAD_GRAYSCALE)\n    X_train_orig.append(cv2.resize(img, dsize=(80,80)))\n    \nprint(len(X_train_orig))\nprint(len(y_train_orig))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"unique_elements, counts_elements = np.unique(np.array(y_train_orig), return_counts=True)\nprint(counts_elements)\n\nplt.xticks(unique_elements, (\"Cat\", \"Dog\"))\nplt.bar(unique_elements, counts_elements)\nplt.title(\"No. of cat and dog examples in train dataset\")\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## **Train and CV Data prep**"},{"metadata":{"trusted":true},"cell_type":"code","source":"# resize and normalize X for train\n\nX_train_orig = np.reshape(X_train_orig, (-1, 80,80,1))\nprint(X_train_orig.shape)\n\nX_train = X_train_orig/255.0","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#divide X_train into train cv datasets\nnp.random.seed(1)\n\n#shuffle the indexes for diversity\nshuffled_indexes = np.arange(X_train.shape[0])\nnp.random.shuffle(shuffled_indexes)\n\nX_train = np.array(X_train)[shuffled_indexes]\n\ny_train = np.array(y_train_orig)[shuffled_indexes]\n\n\nX_train = X_train[:int(len(X_train)*0.8)]\n\nX_cv = X_train[int(len(X_train)*0.8):]\n\ny_train = y_train[:int(len(y_train)*0.8)]\n\ny_cv = y_train[int(len(y_train)*0.8):]\n\nprint(len(X_train))\nprint(len(X_cv))\nprint(len(y_train))\nprint(len(y_cv))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = tf.keras.Sequential([\n    tf.keras.layers.Conv2D(128, (3,3), activation=\"relu\", input_shape=(80, 80, 1)),\n    tf.keras.layers.MaxPool2D((3,3)),\n    tf.keras.layers.Conv2D(64, (3,3), activation=\"relu\"),\n    tf.keras.layers.MaxPool2D((3,3)),\n    tf.keras.layers.Flatten(),\n    tf.keras.layers.Dense(units=18, activation=\"relu\"),\n    tf.keras.layers.Dense(units=9, activation=\"relu\"),\n    tf.keras.layers.Dense(units=2, activation=\"softmax\")\n])\n\nmodel.compile(optimizer=\"adam\", loss='sparse_categorical_crossentropy', metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# callback to stop the training if accuracy reaches above 99.8\n\nclass Acc_call_back(tf.keras.callbacks.Callback):\n    def on_epoch_finished(self, epoch, logs={}):\n        if logs.get(\"accuracy\") > 0.998:\n            print(\"Accuracy reached more than 99.8%, stopping training\")\n            self.model.stop_training = True\n    ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"cb = Acc_call_back()\nmodel.fit(X_train, y_train, epochs=25, callbacks = [cb])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.evaluate(X_cv, y_cv)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(X_cv.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"preds = model.predict(X_cv)\n\nprint(preds[0])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## **Test Data Prep:**"},{"metadata":{"trusted":true},"cell_type":"code","source":"#read test data\n\ntest_data_path = \"./kaggle/input/data/test/test1/\"\n\nX_test_orig = []\n\nfor f in os.listdir(test_data_path):\n    img = cv2.imread(test_data_path+str(f), cv2.IMREAD_GRAYSCALE)\n    X_test_orig.append(cv2.resize(img, dsize=(80,80)))\n\nprint(len(X_test_orig))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Nrmalize and reshape test data.\nX_test = np.reshape(X_test_orig,(-1, 80,80,1))\n\nX_test = X_test/255.0\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## **Predict:**"},{"metadata":{"trusted":true},"cell_type":"code","source":"predictions = model.predict(X_test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"result = pd.DataFrame(np.arange(1,len(predictions)+1))\n\nresult.columns = [\"index\"]\n\nresult[\"label\"] = np.argmax(predictions,axis=1)\n\nresult.to_csv(\"./kaggle/input/data/result.csv\",index=False)\n                      \n                      ","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":1}