{"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\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","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Pre-processing data"},{"metadata":{"trusted":true},"cell_type":"code","source":"import zipfile\nwith zipfile.ZipFile(\"../input/dogs-vs-cats/train.zip\",\"r\") as z:\n    z.extractall(\".\")\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":"import os\ntrain_path = '/kaggle/working/train'\nfilenames = os.listdir(train_path)\ncategories = []\nfor f in filenames:\n    category = f.split(\".\")[0]\n    if category == 'dog':\n        categories.append(1)\n    else:\n        categories.append(0)\nprint(len(categories))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import pandas as pd\ndf = pd.DataFrame({'file':filenames,'category':categories})\ndf.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df['category'].value_counts()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Visualisation"},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.preprocessing import image\nimport matplotlib.pyplot as plt\nfor i in range(5):\n    plt.figure(figsize=(10, 10))\n    plt.subplot(2, 3, i+1)\n    img_path = os.path.join(train_path, filenames[i])\n    img = image.load_img(img_path)\n    plt.imshow(img)\nplt.tight_layout()    \nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Pre-train model"},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.applications import VGG16\nconv = VGG16(weights='imagenet', include_top=False, input_shape=(224, 224, 3))\nconv.trainable = False\nconv.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D, Dense, Dropout, Activation, Flatten\nfrom keras.regularizers import l2\nmodel = Sequential()\nmodel.add(conv)\nmodel.add(Flatten())\nmodel.add(Dense(512, activation='relu', kernel_regularizer=l2(0.001)))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(1, activation='sigmoid'))\nmodel.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy'])\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.preprocessing.image import ImageDataGenerator\ndatagen = ImageDataGenerator(\n        rescale=1./255,\n        width_shift_range=0.2,\n        height_shift_range=0.2,\n        shear_range=0.5,\n        rotation_range=40,\n        zoom_range=0.2,\n        horizontal_flip=True,\n        fill_mode='nearest'\n)\nval_datagen = ImageDataGenerator(rescale=1./255)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df['category'] = df['category'].map({1:'dog',0:'cat'})\nfrom sklearn.model_selection import train_test_split\ntrain, validate = train_test_split(df, train_size=0.8)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_generator = datagen.flow_from_dataframe(train,\n                                              directory=train_path,\n                                              x_col='file',\n                                              y_col='category',\n                                              target_size=(224, 224),\n                                              batch_size=32,\n                                              class_mode='binary')\nvalidation_generator = val_datagen.flow_from_dataframe(validate,\n                                        directory=train_path,\n                                        x_col='file',\n                                        y_col='category',\n                                        target_size=(224, 224),\n                                        batch_size=32,\n                                        class_mode='binary')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample = df.sample(n=1)\nsample_generator = datagen.flow_from_dataframe(sample,\n                                               directory=train_path,\n                                               x_col='file',\n                                               y_col='category',\n                                               target_size=(224,224),\n                                               class_mode='categorical')\nfor i in range(6):\n    plt.subplot(2,3,i+1)\n    for i,l in sample_generator:\n        plt.imshow(i[0])\n        break\nplt.show()      ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model.fit(train_generator, validation_data=validation_generator, batch_size=32, epochs=10, verbose=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\nacc = history.history['accuracy']\nval_accuracy = history.history['val_accuracy']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\nepochs = range(1, len(acc)+1)\nplt.figure()\nplt.plot(epochs, acc,'r-', label='Training Accuracy')\nplt.plot(epochs, val_accuracy, 'b-', label='Validation Accuracy')\nplt.xlabel('Epochs')\nplt.ylabel('Accuracy')\nplt.title('Train-Validation-Accuracy-Curve')\nplt.ylim([0,1])\nplt.legend()\nplt.figure()\nplt.plot(epochs,loss, 'r-', label='Training Loss')\nplt.plot(epochs, val_loss,'b-', label='Validation loss')\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.title('Train-Validation-loss-Curve')\nplt.legend()\nplt.ylim([0,1])\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_layer = False\nfor i in conv.layers:\n    if i.name == 'block5_conv1':\n        train_layer = True\n    if train_layer == True:\n        i.trainable = True\n        print(i,' :yes')\n    else:\n        print(i,' :no')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras import optimizers\nmodel.compile(loss='binary_crossentropy', optimizer=optimizers.RMSprop(lr=1e-4), metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history_fine = model.fit(train_generator, validation_data=validation_generator, batch_size=32, epochs=10, verbose=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\nacc = history_fine.history['accuracy']\nval_accuracy = history_fine.history['val_accuracy']\nloss = history_fine.history['loss']\nval_loss = history.history['val_loss']\nepochs = range(1, len(acc)+1)\nplt.figure()\nplt.plot(epochs, acc,'r-', label='Training Accuracy')\nplt.plot(epochs, val_accuracy, 'b-', label='Validation Accuracy')\nplt.xlabel('Epochs')\nplt.ylabel('Accuracy')\nplt.title('Train-Validation-Accuracy-Curve')\nplt.ylim([0,1])\nplt.legend()\nplt.figure()\nplt.plot(epochs,loss, 'r-', label='Training Loss')\nplt.plot(epochs, val_loss,'b-', label='Validation loss')\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.title('Train-Validation-loss-Curve')\nplt.legend()\nplt.ylim([0,1])\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_path='/kaggle/working/test1'\ntest_file=os.listdir('/kaggle/working/test1')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df=pd.DataFrame({'file':test_file})\ntest_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_generator = val_datagen.flow_from_dataframe(test_df,directory=test_path,\n                                                 x_col='file',\n                                                 y_col=None,\n                                                 class_mode=None,\n                                                 target_size=(224,224),\n                                                 batch_size=32,\n                                                 shuffle=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predict=model.predict(test_generator)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sub = np.around(predict).astype(int)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"img = image.load_img(os.path.join(test_path,test_file[0]))\nplt.subplot(1, 2, 1)\nplt.imshow(img)\nplt.title(str(predict[0]))\nplt.subplot(1, 2, 2)\nimg = image.load_img(os.path.join(test_path,test_file[1]))\nplt.imshow(img)\nplt.title(str(predict[1]))\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission = test_df.copy()\nsubmission['id'] = submission['file'].str.split(\".\").str[0]\nsubmission['label'] = sub\nsubmission.drop(['file'], axis=1, inplace=True)\nsubmission['id'] = submission['id'].astype('int')\nsubmission = submission.sort_values(by=['id'])\nsubmission.to_csv('submission.csv', index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"Your submission was successfully saved!\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"!rm -rf \"/kaggle/working/train\""},{"metadata":{"trusted":true},"cell_type":"code","source":"!rm -rf train","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!rm -rf test1","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ls -a","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.save_weights(\"model.h5\")","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}