{"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":"# 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\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\n\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom keras.utils import to_categorical\nfrom keras.preprocessing.image import ImageDataGenerator, load_img\nfrom PIL import Image\nimport random\n\n# Input data files are available in the read-only \"../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# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Unzipping training and testing data","metadata":{}},{"cell_type":"code","source":"import zipfile\nwith zipfile.ZipFile(\"../input/dogs-vs-cats/train.zip\", 'r') as zip_ref:\n    zip_ref.extractall('./train')\nwith zipfile.ZipFile(\"../input/dogs-vs-cats/test1.zip\", 'r') as zip_ref:\n    zip_ref.extractall('./test')    ","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"filenames = os.listdir(\"./train/train\")\ncategories = []\nfor f_name in filenames:\n    category = f_name.split('.')[0]\n    if category=='dog':\n        categories.append(1)\n    else:\n        categories.append(0)\n    \ndf=pd.DataFrame({\n    'filename':filenames,\n    'category':categories\n})","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"path = os.listdir('./test/test1')\ncount = 0\nnames = []\nfor x in path:\n    count += 1\n    names.append(x)\nprint('No. of test examples: ', count)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cwd = './train/train/'\ndata = []\nlabels = []\nfor i in range(25000):\n    image = Image.open(cwd + df.filename[i])\n    image = image.resize((128,128))\n    image = np.array(image)\n    data.append(image)\n    labels.append(df.category[i])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data = np.array(data) # Converting the list into an array\nlabels = np.array(labels)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_train, X_test, y_train, y_test = train_test_split(data, labels, train_size = 0.6)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Creating and training the model","metadata":{}},{"cell_type":"code","source":"model = keras.Sequential([\n    keras.layers.Flatten(input_shape = (128,128,3)),\n    keras.layers.BatchNormalization(),\n    keras.layers.Dense(2048, activation = 'relu'),\n    keras.layers.BatchNormalization(),\n    keras.layers.Dense(1024, activation='relu'),\n    keras.layers.BatchNormalization(),\n    keras.layers.Dense(128, activation = 'relu'),\n    keras.layers.BatchNormalization(),\n    keras.layers.Dense(32, activation='relu'),\n    keras.layers.BatchNormalization(),\n    keras.layers.Dense(2, activation='sigmoid')\n])\n\nmodel.compile(optimizer='adam',\n             loss = 'sparse_categorical_crossentropy',\n             metrics=['accuracy'])\n\nmod = model.fit(X_train, y_train, epochs = 28, batch_size = 64)\nmod","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Accuracy on test set","metadata":{}},{"cell_type":"code","source":"model.evaluate(X_test, y_test)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(15,8))\nplt.plot(mod.history['accuracy'], label = 'accuracy')\nplt.xlabel(\"Epochs\")\nplt.ylabel(\"Accuracy\")\nplt.legend()\nplt.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_img = []\nfor i in range(12500):\n    image = Image.open('./test/test1/' + names[i])\n    image = image.resize((128,128))\n    image = np.array(image)\n    test_img.append(image)\n","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_predicted = model.predict(X_test)\ny_predicted_labels = [np.argmax(i) for i in y_predicted]","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"index = 2384\nlab = y_predicted_labels[index]\nanimal='dog'\nif lab==0:\n    animal='cat'\nplt.xlabel(animal)\nplt.imshow(test_img[index])","metadata":{"trusted":true},"execution_count":null,"outputs":[]}]}