{"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\nimport matplotlib.pyplot as plt\nimport random\nimport os\nimport zipfile\nimport tensorflow as tf","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2021-08-23T10:50:39.575610Z","iopub.execute_input":"2021-08-23T10:50:39.575975Z","iopub.status.idle":"2021-08-23T10:50:44.066332Z","shell.execute_reply.started":"2021-08-23T10:50:39.575894Z","shell.execute_reply":"2021-08-23T10:50:44.065481Z"},"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\n\nos.mkdir('../Dataset/')\nos.mkdir('../Dataset/Train/')\nos.mkdir('../Dataset/Test/')","metadata":{"execution":{"iopub.status.busy":"2021-08-23T10:50:48.916123Z","iopub.execute_input":"2021-08-23T10:50:48.916501Z","iopub.status.idle":"2021-08-23T10:50:48.924938Z","shell.execute_reply.started":"2021-08-23T10:50:48.916466Z","shell.execute_reply":"2021-08-23T10:50:48.924111Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with zipfile.ZipFile('../input/dogs-vs-cats/train.zip', 'r') as Z:\n    Z.extractall('../Dataset/Train/')\n\nwith zipfile.ZipFile('../input/dogs-vs-cats/test1.zip', 'r') as Z:\n    Z.extractall('../Dataset/Test/')","metadata":{"execution":{"iopub.status.busy":"2021-08-23T10:50:52.384176Z","iopub.execute_input":"2021-08-23T10:50:52.384529Z","iopub.status.idle":"2021-08-23T10:51:10.515701Z","shell.execute_reply.started":"2021-08-23T10:50:52.384497Z","shell.execute_reply":"2021-08-23T10:51:10.514821Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"filenames = os.listdir('../Dataset/Train/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({'filename': filenames, 'category': categories})\ndf = df.sample(frac = 1, random_state = 23).reset_index(drop = True)\ndf.head()","metadata":{"execution":{"iopub.status.busy":"2021-08-23T10:51:10.517154Z","iopub.execute_input":"2021-08-23T10:51:10.517548Z","iopub.status.idle":"2021-08-23T10:51:10.731088Z","shell.execute_reply.started":"2021-08-23T10:51:10.517510Z","shell.execute_reply":"2021-08-23T10:51:10.730001Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df['category'].value_counts().plot.bar()","metadata":{"execution":{"iopub.status.busy":"2021-08-23T10:51:10.733091Z","iopub.execute_input":"2021-08-23T10:51:10.733451Z","iopub.status.idle":"2021-08-23T10:51:10.899167Z","shell.execute_reply.started":"2021-08-23T10:51:10.733413Z","shell.execute_reply":"2021-08-23T10:51:10.898170Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.preprocessing.image import load_img\nsample = random.choice(filenames)\nimage = load_img('../Dataset/Train/train/' + sample)\nplt.imshow(image)","metadata":{"execution":{"iopub.status.busy":"2021-08-23T10:51:10.900765Z","iopub.execute_input":"2021-08-23T10:51:10.901159Z","iopub.status.idle":"2021-08-23T10:51:11.156330Z","shell.execute_reply.started":"2021-08-23T10:51:10.901120Z","shell.execute_reply":"2021-08-23T10:51:11.155482Z"},"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.25))\nmodel.add(Dense(2, activation = 'softmax'))\n\nmodel.compile(loss = 'categorical_crossentropy', optimizer = 'rmsprop', metrics = ['accuracy'])\n\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2021-08-23T10:51:11.157619Z","iopub.execute_input":"2021-08-23T10:51:11.157921Z","iopub.status.idle":"2021-08-23T10:51:13.258696Z","shell.execute_reply.started":"2021-08-23T10:51:11.157890Z","shell.execute_reply":"2021-08-23T10:51:13.257863Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.callbacks import EarlyStopping, ReduceLROnPlateau\n\nearlystop = EarlyStopping(patience = 10)\n\nlearning_rate_redn = ReduceLROnPlateau(monitor = 'val_loss', patience = 2, verbose = 1, factor = 0.5, min_lr = 0.00001)\n\ncallbacks = [earlystop, learning_rate_redn]","metadata":{"execution":{"iopub.status.busy":"2021-08-23T10:51:13.260786Z","iopub.execute_input":"2021-08-23T10:51:13.261187Z","iopub.status.idle":"2021-08-23T10:51:13.268270Z","shell.execute_reply.started":"2021-08-23T10:51:13.261147Z","shell.execute_reply":"2021-08-23T10:51:13.267423Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\ndf['category'] = df['category'].replace({0: 'cat', 1: 'dog'})\n\ntrain_df, validate_df = train_test_split(df, test_size = 0.20, random_state = 23)\ntrain_df = train_df.reset_index(drop = True)\nvalidate_df = validate_df.reset_index(drop = True)","metadata":{"execution":{"iopub.status.busy":"2021-08-23T10:51:13.269914Z","iopub.execute_input":"2021-08-23T10:51:13.270248Z","iopub.status.idle":"2021-08-23T10:51:13.789721Z","shell.execute_reply.started":"2021-08-23T10:51:13.270213Z","shell.execute_reply":"2021-08-23T10:51:13.788886Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df['category'].value_counts().plot.bar()","metadata":{"execution":{"iopub.status.busy":"2021-08-23T10:51:13.835187Z","iopub.execute_input":"2021-08-23T10:51:13.835506Z","iopub.status.idle":"2021-08-23T10:51:13.970079Z","shell.execute_reply.started":"2021-08-23T10:51:13.835477Z","shell.execute_reply":"2021-08-23T10:51:13.969318Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"validate_df['category'].value_counts().plot.bar()","metadata":{"execution":{"iopub.status.busy":"2021-08-23T10:51:14.531737Z","iopub.execute_input":"2021-08-23T10:51:14.532070Z","iopub.status.idle":"2021-08-23T10:51:14.663067Z","shell.execute_reply.started":"2021-08-23T10:51:14.532037Z","shell.execute_reply":"2021-08-23T10:51:14.662201Z"},"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-08-23T10:51:22.719547Z","iopub.execute_input":"2021-08-23T10:51:22.719884Z","iopub.status.idle":"2021-08-23T10:51:22.726431Z","shell.execute_reply.started":"2021-08-23T10:51:22.719853Z","shell.execute_reply":"2021-08-23T10:51:22.725467Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.preprocessing.image import ImageDataGenerator\n\ntrain_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    '../Dataset/Train/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-08-23T10:51:26.131358Z","iopub.execute_input":"2021-08-23T10:51:26.131732Z","iopub.status.idle":"2021-08-23T10:51:26.359388Z","shell.execute_reply.started":"2021-08-23T10:51:26.131700Z","shell.execute_reply":"2021-08-23T10:51:26.358519Z"},"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    '../Dataset/Train/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-08-23T10:51:29.216266Z","iopub.execute_input":"2021-08-23T10:51:29.216774Z","iopub.status.idle":"2021-08-23T10:51:29.323250Z","shell.execute_reply.started":"2021-08-23T10:51:29.216729Z","shell.execute_reply":"2021-08-23T10:51:29.322151Z"},"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    '../Dataset/Train/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-08-23T10:51:30.408785Z","iopub.execute_input":"2021-08-23T10:51:30.409116Z","iopub.status.idle":"2021-08-23T10:51:30.419500Z","shell.execute_reply.started":"2021-08-23T10:51:30.409086Z","shell.execute_reply":"2021-08-23T10:51:30.418351Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize = (12, 12))\nfor i in range(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-08-23T10:51:35.370751Z","iopub.execute_input":"2021-08-23T10:51:35.371083Z","iopub.status.idle":"2021-08-23T10:51:37.226619Z","shell.execute_reply.started":"2021-08-23T10:51:35.371051Z","shell.execute_reply":"2021-08-23T10:51:37.225843Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"epochs = 3 if FAST_RUN else 50\nhistory = model.fit(\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-08-23T10:52:06.420638Z","iopub.execute_input":"2021-08-23T10:52:06.420963Z","iopub.status.idle":"2021-08-23T12:37:27.018740Z","shell.execute_reply.started":"2021-08-23T10:52:06.420932Z","shell.execute_reply":"2021-08-23T12:37:27.017578Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.save_weights(\"model.h5\")","metadata":{"execution":{"iopub.status.busy":"2021-08-23T12:49:12.837048Z","iopub.execute_input":"2021-08-23T12:49:12.837466Z","iopub.status.idle":"2021-08-23T12:49:12.982148Z","shell.execute_reply.started":"2021-08-23T12:49:12.837389Z","shell.execute_reply":"2021-08-23T12:49:12.981148Z"},"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-08-23T12:50:32.666925Z","iopub.execute_input":"2021-08-23T12:50:32.667278Z","iopub.status.idle":"2021-08-23T12:50:33.627869Z","shell.execute_reply.started":"2021-08-23T12:50:32.667249Z","shell.execute_reply":"2021-08-23T12:50:33.627002Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_filenames = os.listdir(\"../Dataset/Test/test1\")\ntest_df = pd.DataFrame({\n    'filename': test_filenames\n})\nnb_samples = test_df.shape[0]","metadata":{"execution":{"iopub.status.busy":"2021-08-23T12:50:40.332568Z","iopub.execute_input":"2021-08-23T12:50:40.332899Z","iopub.status.idle":"2021-08-23T12:50:40.349077Z","shell.execute_reply.started":"2021-08-23T12:50:40.332871Z","shell.execute_reply":"2021-08-23T12:50:40.348155Z"},"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    \"../Dataset/Test/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-08-23T12:50:42.431900Z","iopub.execute_input":"2021-08-23T12:50:42.432211Z","iopub.status.idle":"2021-08-23T12:50:42.557159Z","shell.execute_reply.started":"2021-08-23T12:50:42.432182Z","shell.execute_reply":"2021-08-23T12:50:42.556040Z"},"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-08-23T12:50:45.219015Z","iopub.execute_input":"2021-08-23T12:50:45.219392Z","iopub.status.idle":"2021-08-23T12:51:17.893814Z","shell.execute_reply.started":"2021-08-23T12:50:45.219326Z","shell.execute_reply":"2021-08-23T12:51:17.892965Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df['category'] = np.argmax(predict, axis = -1)","metadata":{"execution":{"iopub.status.busy":"2021-08-23T12:51:21.409772Z","iopub.execute_input":"2021-08-23T12:51:21.410101Z","iopub.status.idle":"2021-08-23T12:51:21.417236Z","shell.execute_reply.started":"2021-08-23T12:51:21.410070Z","shell.execute_reply":"2021-08-23T12:51:21.416359Z"},"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-08-23T12:51:24.595307Z","iopub.execute_input":"2021-08-23T12:51:24.595662Z","iopub.status.idle":"2021-08-23T12:51:24.603524Z","shell.execute_reply.started":"2021-08-23T12:51:24.595631Z","shell.execute_reply":"2021-08-23T12:51:24.602364Z"},"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-08-23T12:51:27.928713Z","iopub.execute_input":"2021-08-23T12:51:27.929038Z","iopub.status.idle":"2021-08-23T12:51:27.944042Z","shell.execute_reply.started":"2021-08-23T12:51:27.929000Z","shell.execute_reply":"2021-08-23T12:51:27.943271Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df['category'].value_counts().plot.bar()","metadata":{"execution":{"iopub.status.busy":"2021-08-23T12:51:29.394123Z","iopub.execute_input":"2021-08-23T12:51:29.394454Z","iopub.status.idle":"2021-08-23T12:51:29.527008Z","shell.execute_reply.started":"2021-08-23T12:51:29.394420Z","shell.execute_reply":"2021-08-23T12:51:29.526034Z"},"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(\"../Dataset/Test/test1/\" + filename, target_size = IMAGE_SIZE)\n    plt.subplot(6, 3, index + 1)\n    plt.imshow(img)\n    plt.xlabel(filename + '(' + \"{}\".format(category) + ')' )\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2021-08-23T12:51:32.879059Z","iopub.execute_input":"2021-08-23T12:51:32.879382Z","iopub.status.idle":"2021-08-23T12:51:36.022954Z","shell.execute_reply.started":"2021-08-23T12:51:32.879349Z","shell.execute_reply":"2021-08-23T12:51:36.021999Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}