{"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)\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":"code","source":"import zipfile\nfrom tqdm import tqdm\nimport tensorflow as tf\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.layers import Flatten, Dense, Dropout\nfrom tensorflow.keras.layers import Conv2D, MaxPool2D, ZeroPadding2D\nfrom tensorflow.keras.optimizers import SGD\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom tensorflow.keras.models import Model\nfrom sklearn.model_selection import train_test_split","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def extract_files(source_path, target_path):\n    zip_ref = zipfile.ZipFile(source_path,'r')\n    zip_ref.extractall(target_path)\n    zip_ref.close()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"extract_files('/kaggle/input/dogs-vs-cats/test1.zip','/kaggle/working/')\nextract_files('/kaggle/input/dogs-vs-cats/train.zip','/kaggle/working/')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_dir = \"./train/\"\ntest_dir  = \"./test1/\"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"filenames = os.listdir(\"/kaggle/working/train\")\nlen(filenames)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"filenames = os.listdir(\"/kaggle/working/train\")\nbase_path = '/kaggle/working/train/'\nclasses = []\nimages = []\nfor filename in tqdm(filenames):\n    images.append(base_path + str(filename))\n    classes.append(filename.split('.')[0])\n\n\ndf = pd.DataFrame({\n    'filename': filenames,\n    'class': classes\n})","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.head()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df[\"class\"] = df[\"class\"].replace({0: 'cat', 1: 'dog'}) \ndf.head()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\ntrain_df, validation_df = train_test_split(df, test_size=0.2, random_state=42)\n\ntrain_df.head()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df.reset_index(drop=True).head()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"validation_df.reset_index(drop=True).head()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.preprocessing.image import ImageDataGenerator\ntrain_datagen = ImageDataGenerator(\n    rescale = 1./255,\n    shear_range = 0.2,\n    zoom_range = 0.2,\n    horizontal_flip = True\n)\ntraining_set = train_datagen.flow_from_dataframe(\n    train_df,\n    directory=train_dir,\n    x_col=\"filename\",\n    y_col=\"class\",\n    target_size=(224, 224),\n    batch_size=32,\n    class_mode='categorical'\n)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.preprocessing.image import ImageDataGenerator\nvalidation_datagen = ImageDataGenerator(\n    rescale = 1./255,\n    shear_range = 0.2,\n    zoom_range = 0.2,\n    horizontal_flip = True\n)\nvalidation_set = validation_datagen.flow_from_dataframe(\n    validation_df,\n    directory=train_dir,\n    x_col=\"filename\",\n    y_col=\"class\",\n    target_size=(224, 224),\n    batch_size=32,\n    class_mode='categorical'\n)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def Model(input_shape=None, classes=None):\n\n    img_input = layers.Input(shape=input_shape)\n\n    x = layers.Conv2D(64, (3, 3), activation='relu', padding='same', name='block1_conv1')(img_input)\n    x = layers.MaxPooling2D((2, 2), strides=(2, 2), name='pool1')(x)\n    x = layers.Conv2D(64, (3, 3), activation='relu', padding='same', name='block1_conv2')(x)\n    x = layers.BatchNormalization()(x)\n    x = layers.MaxPooling2D((2, 2), strides=(2, 2), name='pool2')(x)\n   \n    x = layers.Conv2D(128, (3, 3), activation='relu', padding='same', name='block2_conv1')(x)\n    x = layers.MaxPooling2D((2, 2), strides=(2, 2), name='pool3')(x)\n    x = layers.Conv2D(128, (3, 3), activation='relu', padding='same', name='block2_conv2')(x)\n    x = layers.BatchNormalization()(x)\n    x = layers.MaxPooling2D((2, 2), strides=(2, 2), name='pool4')(x)\n    \n\n\n    x = layers.Flatten(name='flatten')(x)\n    x = layers.Dense(500, activation='relu', name='fc1')(x)\n    x = layers.Dense(100, activation='relu', name='fc2')(x)\n    x = layers.Dense(classes, activation='softmax', name='predictions')(x)\n\n    model = tf.keras.Model(inputs=img_input, outputs=x, name=\"moldel\")\n    \n    return model\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = Model(input_shape=(224, 224,3), classes=2)\nprint(model.summary()) ","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(optimizer= tf.keras.optimizers.Adam(0.001), loss= 'categorical_crossentropy', metrics=['accuracy'])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"total_validate = len(validation_df)\ntotal_train = len(train_df)\nbatch_size = 32\nepochs=15\nhistory = model.fit(\n    training_set, \n    epochs=epochs,\n    validation_data=validation_set,\n    validation_steps=total_validate//batch_size,\n    steps_per_epoch=total_train//batch_size,\n\n)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# **Prediction part**","metadata":{}},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nplt.plot(history.history['accuracy'])\nplt.plot(history.history['val_accuracy'])\nplt.title('model accuracy')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'], loc='upper left')\nplt.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('model loss')\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'], loc='upper left')\nplt.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_filenames = os.listdir(\"/kaggle/working/test1\")\ntest_df = pd.DataFrame({\n    'filename': test_filenames\n})\nnb_samples = test_df.shape[0]","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df.count()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_datagen = ImageDataGenerator(rescale=1./255)\ntest_set = test_datagen.flow_from_dataframe(\n    test_df, \n    \"/kaggle/working/test1/\", \n    x_col='filename',\n    y_col=None,\n    class_mode=None,\n    target_size=(224, 224),\n    batch_size=32,\n    shuffle=False\n)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predict = model.predict(test_set, steps=np.ceil(nb_samples/32))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predict[1]","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df['category'] = np.argmax(predict, axis=-1)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df['category'] = test_df['category'].apply(lambda x: 0 if x < 0.5 else 1)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df.to_csv(\"submission.csv\")","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample_test = test_df.head(15)\nsample_test.head()\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.preprocessing.image import  load_img\n\nIMAGE_SIZE = 224\nplt.figure(figsize=(12, 24))\nfor index, row in sample_test.iterrows():\n    filename = row['filename']\n    category = row['category']\n    img = tf.keras.preprocessing.image.load_img(\"/kaggle/working/test1/\"+str(filename))\n    plt.subplot(6, 3, index+1)\n    plt.imshow(img)\n    plt.xlabel(filename + '(' + \"{}\".format(category) + ')' )\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"filename = 'dog.6990.jpg'\ncategory = 'dog'\n\nimage = tf.keras.preprocessing.image.load_img(\"/kaggle/working/train/\"+str(filename))\nplt.imshow(img)\nplt.xlabel(filename + '(' + \"{}\".format(category) + ')' )\n# plt.tight_layout()\nplt.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}