{"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":"import numpy as np\nimport pandas as pd \nfrom keras.preprocessing.image import ImageDataGenerator, load_img\nfrom keras.utils import to_categorical\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\nimport random\nimport os\nprint(os.listdir(\"../input/dogs-vs-cats\"))","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2021-05-28T02:29:16.612789Z","iopub.execute_input":"2021-05-28T02:29:16.613109Z","iopub.status.idle":"2021-05-28T02:29:22.46011Z","shell.execute_reply.started":"2021-05-28T02:29:16.613081Z","shell.execute_reply":"2021-05-28T02:29:22.459237Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"FAST_RUN = False\nIMAGE_WIDTH=128\nIMAGE_HEIGHT=128\nIMAGE_SIZE=(IMAGE_WIDTH, IMAGE_HEIGHT)\nIMAGE_CHANNELS=3","metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","execution":{"iopub.status.busy":"2021-05-28T02:29:26.04503Z","iopub.execute_input":"2021-05-28T02:29:26.045371Z","iopub.status.idle":"2021-05-28T02:29:26.049734Z","shell.execute_reply.started":"2021-05-28T02:29:26.04534Z","shell.execute_reply":"2021-05-28T02:29:26.048883Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import zipfile\n\n\nzip_files = ['test1', 'train']\n# Will unzip the files so that you can see them..\nfor zip_file in zip_files:\n    with zipfile.ZipFile(\"../input/dogs-vs-cats/{}.zip\".format(zip_file),\"r\") as z:\n        z.extractall(\".\")\n        print(\"{} unzipped\".format(zip_file))","metadata":{"execution":{"iopub.status.busy":"2021-05-28T02:29:28.98002Z","iopub.execute_input":"2021-05-28T02:29:28.980372Z","iopub.status.idle":"2021-05-28T02:29:46.340149Z","shell.execute_reply.started":"2021-05-28T02:29:28.980341Z","shell.execute_reply":"2021-05-28T02:29:46.339254Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"filenames = os.listdir(\"../working/train\")\ncategories = []\nfor filename in filenames:\n    category = filename.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":{"execution":{"iopub.status.busy":"2021-05-28T02:29:50.660822Z","iopub.execute_input":"2021-05-28T02:29:50.66113Z","iopub.status.idle":"2021-05-28T02:29:50.708266Z","shell.execute_reply.started":"2021-05-28T02:29:50.661103Z","shell.execute_reply":"2021-05-28T02:29:50.707411Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.head()","metadata":{"execution":{"iopub.status.busy":"2021-05-28T02:29:57.157032Z","iopub.execute_input":"2021-05-28T02:29:57.15739Z","iopub.status.idle":"2021-05-28T02:29:57.1838Z","shell.execute_reply.started":"2021-05-28T02:29:57.157356Z","shell.execute_reply":"2021-05-28T02:29:57.182578Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.tail()","metadata":{"execution":{"iopub.status.busy":"2021-05-28T02:30:01.940939Z","iopub.execute_input":"2021-05-28T02:30:01.941369Z","iopub.status.idle":"2021-05-28T02:30:01.953677Z","shell.execute_reply.started":"2021-05-28T02:30:01.941319Z","shell.execute_reply":"2021-05-28T02:30:01.952235Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df['category'].value_counts().plot.bar()","metadata":{"execution":{"iopub.status.busy":"2021-05-28T02:30:05.494036Z","iopub.execute_input":"2021-05-28T02:30:05.494383Z","iopub.status.idle":"2021-05-28T02:30:05.660845Z","shell.execute_reply.started":"2021-05-28T02:30:05.494353Z","shell.execute_reply":"2021-05-28T02:30:05.660147Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample = random.choice(filenames)\nimage = load_img(\"../working/train/\"+sample)\nplt.imshow(image)","metadata":{"execution":{"iopub.status.busy":"2021-05-28T02:30:13.54256Z","iopub.execute_input":"2021-05-28T02:30:13.542875Z","iopub.status.idle":"2021-05-28T02:30:13.826375Z","shell.execute_reply.started":"2021-05-28T02:30:13.542846Z","shell.execute_reply":"2021-05-28T02:30:13.825456Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D, Dropout, Flatten, Dense, Activation, BatchNormalization\n\nmodel = Sequential()\n\nmodel.add(Conv2D(32, (3, 3), activation='relu', input_shape=(IMAGE_WIDTH, IMAGE_HEIGHT, IMAGE_CHANNELS)))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Conv2D(64, (3, 3), activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Conv2D(128, (3, 3), activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Flatten())\nmodel.add(Dense(512, activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.5))\nmodel.add(Dense(2, activation='softmax')) # 2 because we have cat and dog classes\n\nmodel.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])\n\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2021-05-28T02:30:23.11916Z","iopub.execute_input":"2021-05-28T02:30:23.119521Z","iopub.status.idle":"2021-05-28T02:30:25.490303Z","shell.execute_reply.started":"2021-05-28T02:30:23.11949Z","shell.execute_reply":"2021-05-28T02:30:25.487772Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.callbacks import EarlyStopping, ReduceLROnPlateau","metadata":{"execution":{"iopub.status.busy":"2021-05-28T02:30:39.894093Z","iopub.execute_input":"2021-05-28T02:30:39.894472Z","iopub.status.idle":"2021-05-28T02:30:39.89877Z","shell.execute_reply.started":"2021-05-28T02:30:39.894441Z","shell.execute_reply":"2021-05-28T02:30:39.897893Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"earlystop = EarlyStopping(patience=3)","metadata":{"execution":{"iopub.status.busy":"2021-05-28T02:30:43.541864Z","iopub.execute_input":"2021-05-28T02:30:43.542181Z","iopub.status.idle":"2021-05-28T02:30:43.547619Z","shell.execute_reply.started":"2021-05-28T02:30:43.542151Z","shell.execute_reply":"2021-05-28T02:30:43.546087Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"learning_rate_reduction = ReduceLROnPlateau(monitor='val_acc', \n                                            patience=2, \n                                            verbose=1, \n                                            factor=0.5, \n                                            min_lr=0.00001)","metadata":{"execution":{"iopub.status.busy":"2021-05-28T02:30:49.790186Z","iopub.execute_input":"2021-05-28T02:30:49.790531Z","iopub.status.idle":"2021-05-28T02:30:49.797381Z","shell.execute_reply.started":"2021-05-28T02:30:49.790502Z","shell.execute_reply":"2021-05-28T02:30:49.796697Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"callbacks = [earlystop, learning_rate_reduction]","metadata":{"execution":{"iopub.status.busy":"2021-05-28T02:30:52.469598Z","iopub.execute_input":"2021-05-28T02:30:52.47Z","iopub.status.idle":"2021-05-28T02:30:52.477183Z","shell.execute_reply.started":"2021-05-28T02:30:52.469967Z","shell.execute_reply":"2021-05-28T02:30:52.476311Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df[\"category\"] = df[\"category\"].replace({0: 'cat', 1: 'dog'}) ","metadata":{"execution":{"iopub.status.busy":"2021-05-28T02:30:57.753595Z","iopub.execute_input":"2021-05-28T02:30:57.753937Z","iopub.status.idle":"2021-05-28T02:30:57.764745Z","shell.execute_reply.started":"2021-05-28T02:30:57.753903Z","shell.execute_reply":"2021-05-28T02:30:57.763746Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df, validate_df = train_test_split(df, test_size=0.20, random_state=42)\ntrain_df = train_df.reset_index(drop=True)\nvalidate_df = validate_df.reset_index(drop=True)","metadata":{"execution":{"iopub.status.busy":"2021-05-28T02:31:07.174303Z","iopub.execute_input":"2021-05-28T02:31:07.174642Z","iopub.status.idle":"2021-05-28T02:31:07.186535Z","shell.execute_reply.started":"2021-05-28T02:31:07.174611Z","shell.execute_reply":"2021-05-28T02:31:07.185678Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df['category'].value_counts().plot.bar()","metadata":{"execution":{"iopub.status.busy":"2021-05-28T02:31:13.286944Z","iopub.execute_input":"2021-05-28T02:31:13.287285Z","iopub.status.idle":"2021-05-28T02:31:13.394082Z","shell.execute_reply.started":"2021-05-28T02:31:13.287252Z","shell.execute_reply":"2021-05-28T02:31:13.392962Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"validate_df['category'].value_counts().plot.bar()","metadata":{"execution":{"iopub.status.busy":"2021-05-28T02:31:20.598266Z","iopub.execute_input":"2021-05-28T02:31:20.598589Z","iopub.status.idle":"2021-05-28T02:31:20.707105Z","shell.execute_reply.started":"2021-05-28T02:31:20.598558Z","shell.execute_reply":"2021-05-28T02:31:20.706203Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"total_train = train_df.shape[0]\ntotal_validate = validate_df.shape[0]\nbatch_size=15","metadata":{"execution":{"iopub.status.busy":"2021-05-28T02:31:31.555555Z","iopub.execute_input":"2021-05-28T02:31:31.55595Z","iopub.status.idle":"2021-05-28T02:31:31.560526Z","shell.execute_reply.started":"2021-05-28T02:31:31.555918Z","shell.execute_reply":"2021-05-28T02:31:31.5594Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_datagen = ImageDataGenerator(\n    rotation_range=15,\n    rescale=1./255,\n    shear_range=0.1,\n    zoom_range=0.2,\n    horizontal_flip=True,\n    width_shift_range=0.1,\n    height_shift_range=0.1\n)\n\ntrain_generator = train_datagen.flow_from_dataframe(\n    train_df, \n    \"../working/train/\", \n    x_col='filename',\n    y_col='category',\n    target_size=IMAGE_SIZE,\n    class_mode='categorical',\n    batch_size=batch_size\n)","metadata":{"execution":{"iopub.status.busy":"2021-05-28T02:31:40.070738Z","iopub.execute_input":"2021-05-28T02:31:40.071054Z","iopub.status.idle":"2021-05-28T02:31:40.297815Z","shell.execute_reply.started":"2021-05-28T02:31:40.071025Z","shell.execute_reply":"2021-05-28T02:31:40.296934Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"validation_datagen = ImageDataGenerator(rescale=1./255)\nvalidation_generator = validation_datagen.flow_from_dataframe(\n    validate_df, \n    \"../working/train/\", \n    x_col='filename',\n    y_col='category',\n    target_size=IMAGE_SIZE,\n    class_mode='categorical',\n    batch_size=batch_size\n)","metadata":{"execution":{"iopub.status.busy":"2021-05-28T02:31:48.038785Z","iopub.execute_input":"2021-05-28T02:31:48.0391Z","iopub.status.idle":"2021-05-28T02:31:48.101302Z","shell.execute_reply.started":"2021-05-28T02:31:48.039072Z","shell.execute_reply":"2021-05-28T02:31:48.10041Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"example_df = train_df.sample(n=1).reset_index(drop=True)\nexample_generator = train_datagen.flow_from_dataframe(\n    example_df, \n    \"../working/train/\", \n    x_col='filename',\n    y_col='category',\n    target_size=IMAGE_SIZE,\n    class_mode='categorical'\n)","metadata":{"execution":{"iopub.status.busy":"2021-05-28T02:31:52.286015Z","iopub.execute_input":"2021-05-28T02:31:52.286352Z","iopub.status.idle":"2021-05-28T02:31:52.297453Z","shell.execute_reply.started":"2021-05-28T02:31:52.286319Z","shell.execute_reply":"2021-05-28T02:31:52.29659Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(12, 12))\nfor i in range(0, 15):\n    plt.subplot(5, 3, i+1)\n    for X_batch, Y_batch in example_generator:\n        image = X_batch[0]\n        plt.imshow(image)\n        break\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2021-05-28T02:31:59.888424Z","iopub.execute_input":"2021-05-28T02:31:59.888791Z","iopub.status.idle":"2021-05-28T02:32:01.975824Z","shell.execute_reply.started":"2021-05-28T02:31:59.888757Z","shell.execute_reply":"2021-05-28T02:32:01.972331Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"epochs=6\nhistory = model.fit_generator(\n    train_generator, \n    epochs=epochs,\n    validation_data=validation_generator,\n    validation_steps=total_validate//batch_size,\n    steps_per_epoch=total_train//batch_size,\n    callbacks=callbacks\n)","metadata":{"execution":{"iopub.status.busy":"2021-05-28T02:32:13.337445Z","iopub.execute_input":"2021-05-28T02:32:13.337773Z","iopub.status.idle":"2021-05-28T02:44:48.757695Z","shell.execute_reply.started":"2021-05-28T02:32:13.337743Z","shell.execute_reply":"2021-05-28T02:44:48.756734Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.save_weights(\"model.h5\")","metadata":{"execution":{"iopub.status.busy":"2021-05-28T02:45:06.40009Z","iopub.execute_input":"2021-05-28T02:45:06.400442Z","iopub.status.idle":"2021-05-28T02:45:06.527893Z","shell.execute_reply.started":"2021-05-28T02:45:06.400409Z","shell.execute_reply":"2021-05-28T02:45:06.527072Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 12))\nax1.plot(history.history['loss'], color='b', label=\"Training loss\")\nax1.plot(history.history['val_loss'], color='r', label=\"validation loss\")\nax1.set_xticks(np.arange(1, epochs, 1))\nax1.set_yticks(np.arange(0, 1, 0.1))\n\nax2.plot(history.history['accuracy'], color='b', label=\"Training accuracy\")\nax2.plot(history.history['val_accuracy'], color='r',label=\"Validation accuracy\")\nax2.set_xticks(np.arange(1, epochs, 1))\n\nlegend = plt.legend(loc='best', shadow=True)\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2021-05-28T02:45:08.270722Z","iopub.execute_input":"2021-05-28T02:45:08.271051Z","iopub.status.idle":"2021-05-28T02:45:08.557796Z","shell.execute_reply.started":"2021-05-28T02:45:08.271022Z","shell.execute_reply":"2021-05-28T02:45:08.55694Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_filenames = os.listdir(\"../working/test1\")\ntest_df = pd.DataFrame({\n    'filename': test_filenames\n})\nnb_samples = test_df.shape[0]","metadata":{"execution":{"iopub.status.busy":"2021-05-28T02:45:26.768532Z","iopub.execute_input":"2021-05-28T02:45:26.768849Z","iopub.status.idle":"2021-05-28T02:45:26.784471Z","shell.execute_reply.started":"2021-05-28T02:45:26.768819Z","shell.execute_reply":"2021-05-28T02:45:26.783336Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_gen = ImageDataGenerator(rescale=1./255)\ntest_generator = test_gen.flow_from_dataframe(\n    test_df, \n    \"../working/test1/\", \n    x_col='filename',\n    y_col=None,\n    class_mode=None,\n    target_size=IMAGE_SIZE,\n    batch_size=batch_size,\n    shuffle=False\n)","metadata":{"execution":{"iopub.status.busy":"2021-05-28T02:45:29.824483Z","iopub.execute_input":"2021-05-28T02:45:29.824814Z","iopub.status.idle":"2021-05-28T02:45:29.933858Z","shell.execute_reply.started":"2021-05-28T02:45:29.824783Z","shell.execute_reply":"2021-05-28T02:45:29.932974Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predict = model.predict_generator(test_generator, steps=np.ceil(nb_samples/batch_size))","metadata":{"execution":{"iopub.status.busy":"2021-05-28T02:45:36.415634Z","iopub.execute_input":"2021-05-28T02:45:36.415966Z","iopub.status.idle":"2021-05-28T02:46:04.992918Z","shell.execute_reply.started":"2021-05-28T02:45:36.415937Z","shell.execute_reply":"2021-05-28T02:46:04.992084Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df['category'] = np.argmax(predict, axis=-1)","metadata":{"execution":{"iopub.status.busy":"2021-05-28T02:46:23.984623Z","iopub.execute_input":"2021-05-28T02:46:23.98494Z","iopub.status.idle":"2021-05-28T02:46:23.991271Z","shell.execute_reply.started":"2021-05-28T02:46:23.984912Z","shell.execute_reply":"2021-05-28T02:46:23.990307Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"label_map = dict((v,k) for k,v in train_generator.class_indices.items())\ntest_df['category'] = test_df['category'].replace(label_map)","metadata":{"execution":{"iopub.status.busy":"2021-05-28T02:46:26.897036Z","iopub.execute_input":"2021-05-28T02:46:26.89751Z","iopub.status.idle":"2021-05-28T02:46:26.905906Z","shell.execute_reply.started":"2021-05-28T02:46:26.897472Z","shell.execute_reply":"2021-05-28T02:46:26.905081Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df['category'] = test_df['category'].replace({ 'dog': 1, 'cat': 0 })","metadata":{"execution":{"iopub.status.busy":"2021-05-28T02:46:32.128373Z","iopub.execute_input":"2021-05-28T02:46:32.128715Z","iopub.status.idle":"2021-05-28T02:46:32.143477Z","shell.execute_reply.started":"2021-05-28T02:46:32.128685Z","shell.execute_reply":"2021-05-28T02:46:32.142408Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df['category'].value_counts().plot.bar()","metadata":{"execution":{"iopub.status.busy":"2021-05-28T02:46:34.288499Z","iopub.execute_input":"2021-05-28T02:46:34.288867Z","iopub.status.idle":"2021-05-28T02:46:34.414993Z","shell.execute_reply.started":"2021-05-28T02:46:34.288835Z","shell.execute_reply":"2021-05-28T02:46:34.414176Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample_test = test_df.head(18)\nsample_test.head()\nplt.figure(figsize=(12, 24))\nfor index, row in sample_test.iterrows():\n    filename = row['filename']\n    category = row['category']\n    img = load_img(\"../working/test1/\"+filename, target_size=IMAGE_SIZE)\n    plt.subplot(6, 3, index+1)\n    plt.imshow(img)\n    plt.xlabel(filename + '(' + \"{}\".format(category) + ')' )\n    if(category ==0):\n        predict_name = 'kucing'\n    else:\n        predict_name = 'anjing'\n    print(filename + '(' + predict_name + ')' )\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2021-05-28T02:49:57.866897Z","iopub.execute_input":"2021-05-28T02:49:57.867283Z","iopub.status.idle":"2021-05-28T02:50:01.097715Z","shell.execute_reply.started":"2021-05-28T02:49:57.86725Z","shell.execute_reply":"2021-05-28T02:50:01.096781Z"},"trusted":true},"execution_count":null,"outputs":[]}]}