{"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 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\nfrom tensorflow.keras.optimizers import RMSprop\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"../input\"))\n\nimport zipfile\n\nwith zipfile.ZipFile(\"../input/train.zip\",\"r\") as z:\n    z.extractall(\".\")\n    \nwith zipfile.ZipFile(\"../input/test1.zip\",\"r\") as z:\n    z.extractall(\".\")\n\n# Any results you write to the current directory are saved as output.\n\n#print(os.listdir(\"/kaggle/working/train\"))","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","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=(96, 96))\n    plt.imshow(new_img_array,cmap=\"gray\")\n    break","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"cfa2a50c1ea569d97806510e0e313e1ce9d7452b"},"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=(96, 96))\n        X.append(new_img_array)\n        y.append(category)\n    ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"6e30159db4207451532ac085e617bc2669c93714"},"cell_type":"code","source":"create_test_data(path)\nX = np.array(X).reshape(-1, 96,96,1)\ny = np.array(y)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"aac4daf7957d1429a9d47e19c75459c217f04d50"},"cell_type":"code","source":"#Normalize data\nX = X/255.0","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"80c4b5ece66f7a069cfb6194779dc02ef76ce3e8"},"cell_type":"code","source":"model = tf.keras.models.Sequential([\n\n    tf.keras.layers.Conv2D(16, (3, 3), padding='same', input_shape=X.shape[1:]),\n    tf.keras.layers.Activation('relu'),\n    tf.keras.layers.MaxPooling2D(pool_size=(2, 2)),\n    tf.keras.layers.Dropout(0.25),\n\n    tf.keras.layers.Conv2D(32, (3, 3), padding='same'),\n    tf.keras.layers.Activation('relu'),\n    tf.keras.layers.MaxPooling2D(pool_size=(2, 2)),\n    tf.keras.layers.Dropout(0.25),\n\n    tf.keras.layers.Conv2D(64, (3, 3), padding='same'),\n    tf.keras.layers.Activation('relu'),\n    tf.keras.layers.MaxPooling2D(pool_size=(2, 2)),\n    tf.keras.layers.Dropout(0.25),\n    \n    tf.keras.layers.Flatten(),\n    tf.keras.layers.Dense(512),\n    tf.keras.layers.Activation('relu'),\n    tf.keras.layers.Dropout(0.5),\n    tf.keras.layers.Dense(1),\n    tf.keras.layers.Activation('sigmoid')\n    ])\n\nmodel.compile(optimizer=\"adam\",\n              loss='binary_crossentropy',\n              metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"ec02e9538761ef147ba6e0c2129dba117a37efa1"},"cell_type":"code","source":"history = model.fit(X, y, epochs=20, batch_size=32, validation_split=0.2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\n\ndef plotmodelhistory(history): \n    fig, axs = plt.subplots(1,2,figsize=(15,5)) \n    # summarize history for accuracy\n    axs[0].plot(history.history['acc']) \n    axs[0].plot(history.history['val_acc']) \n    axs[0].set_title('Model Accuracy')\n    axs[0].set_ylabel('Accuracy') \n    axs[0].set_xlabel('Epoch')\n    axs[0].legend(['train', 'validate'], loc='upper left')\n    # summarize history for loss\n    axs[1].plot(history.history['loss']) \n    axs[1].plot(history.history['val_loss']) \n    axs[1].set_title('Model Loss')\n    axs[1].set_ylabel('Loss') \n    axs[1].set_xlabel('Epoch')\n    axs[1].legend(['train', 'validate'], loc='upper left')\n    plt.show()\n\n# list all data in history\nprint(history.history.keys())\n\nplotmodelhistory(history)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"6b55df2d3396f6d27d4e5d4ea4584a9e1733bc92"},"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=(96, 96))\n        X_test.append(new_img_array)\ncreate_test1_data(path)\nX_test = np.array(X_test).reshape(-1,96,96,1)\nX_test = X_test/255","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"7b902cc4d61cfaa770fdf3b674b399e87fd62ac5"},"cell_type":"code","source":"predictions = model.predict(X_test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"87ea9ff5a4e9cfa0ac21a1af18b08e86b9183425"},"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":"print(predicted_val)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(len(predicted_val))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pred_val_name = []\nx = 0\nfor x in range(len(predicted_val)):\n    if predicted_val[x] == 1:\n        pred_val_name.append('dog')\n    else:\n        pred_val_name.append('cat')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(pred_val_name)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"1496f4fb9e8752d359a5f0a6ccee6c544ee896a8"},"cell_type":"code","source":"submission_df = pd.DataFrame({'id':id_line, 'label':pred_val_name})","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":{"trusted":true,"_uuid":"2031743817724557d2b65b34541ade436133c657"},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"0963b84bf9f6e27235b37d1133c37868791a6eb9"},"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}