{"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 tensorflow as tf \nimport numpy as np\nimport pandas as pd \nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator, load_img\nfrom tensorflow.keras.utils import to_categorical\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\nimport random\nimport os\nimport zipfile\nprint(os.listdir(\"../input\"))","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-02-20T14:43:14.370167Z","iopub.execute_input":"2022-02-20T14:43:14.370414Z","iopub.status.idle":"2022-02-20T14:43:20.047469Z","shell.execute_reply.started":"2022-02-20T14:43:14.370386Z","shell.execute_reply":"2022-02-20T14:43:20.046718Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_zip_path = '../input/dogs-vs-cats/train.zip'\ntest_zip_path = '../input/dogs-vs-cats/test1.zip'\nroot_path = './'\ntrain_folder = os.path.join(root_path,'train')\ntest_folder = os.path.join(root_path,'test')\nprint('zip train files')\nwith zipfile.ZipFile(train_zip_path, 'r') as zip_ref:\n    zip_ref.extractall()\nprint('zip test files')\nwith zipfile.ZipFile(test_zip_path, 'r') as zip_ref:\n    zip_ref.extractall()","metadata":{"execution":{"iopub.status.busy":"2022-02-20T14:43:22.973529Z","iopub.execute_input":"2022-02-20T14:43:22.974203Z","iopub.status.idle":"2022-02-20T14:43:38.746692Z","shell.execute_reply.started":"2022-02-20T14:43:22.974165Z","shell.execute_reply":"2022-02-20T14:43:38.745949Z"},"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\nfilenames = os.listdir(train_folder)\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":"2022-02-20T14:43:38.748475Z","iopub.execute_input":"2022-02-20T14:43:38.748742Z","iopub.status.idle":"2022-02-20T14:43:38.793369Z","shell.execute_reply.started":"2022-02-20T14:43:38.748708Z","shell.execute_reply":"2022-02-20T14:43:38.792658Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample = random.choice(filenames)\nimage = load_img(\"./train/\"+sample)\nplt.imshow(image)","metadata":{"execution":{"iopub.status.busy":"2022-02-20T13:07:18.055942Z","iopub.execute_input":"2022-02-20T13:07:18.056381Z","iopub.status.idle":"2022-02-20T13:07:18.316422Z","shell.execute_reply.started":"2022-02-20T13:07:18.056301Z","shell.execute_reply":"2022-02-20T13:07:18.315234Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df['category'].value_counts().plot.bar()","metadata":{"execution":{"iopub.status.busy":"2022-02-20T13:07:18.318882Z","iopub.execute_input":"2022-02-20T13:07:18.319471Z","iopub.status.idle":"2022-02-20T13:07:18.514429Z","shell.execute_reply.started":"2022-02-20T13:07:18.319428Z","shell.execute_reply":"2022-02-20T13:07:18.513392Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.models import Sequential\nfrom tensorflow.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":"2022-02-20T13:08:20.306631Z","iopub.execute_input":"2022-02-20T13:08:20.307669Z","iopub.status.idle":"2022-02-20T13:08:23.177233Z","shell.execute_reply.started":"2022-02-20T13:08:20.307636Z","shell.execute_reply":"2022-02-20T13:08:23.176003Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.callbacks import EarlyStopping, ReduceLROnPlateau\nearlystop = EarlyStopping(patience=10)\nlearning_rate_reduction = ReduceLROnPlateau(monitor='val_acc', \n                                            patience=2, \n                                            verbose=1, \n                                            factor=0.5, \n                                            min_lr=0.00001)\ncallbacks = [earlystop, learning_rate_reduction]\n\ndf[\"category\"] = df[\"category\"].replace({0: 'cat', 1: 'dog'}) \n\ntrain_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":"2022-02-20T13:08:53.026071Z","iopub.execute_input":"2022-02-20T13:08:53.026412Z","iopub.status.idle":"2022-02-20T13:08:53.03434Z","shell.execute_reply.started":"2022-02-20T13:08:53.026379Z","shell.execute_reply":"2022-02-20T13:08:53.033212Z"},"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":"2022-02-20T13:10:42.982395Z","iopub.execute_input":"2022-02-20T13:10:42.982677Z","iopub.status.idle":"2022-02-20T13:10:42.987843Z","shell.execute_reply.started":"2022-02-20T13:10:42.982648Z","shell.execute_reply":"2022-02-20T13:10:42.986764Z"},"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    \"./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":"2022-02-20T13:11:07.527351Z","iopub.execute_input":"2022-02-20T13:11:07.527679Z","iopub.status.idle":"2022-02-20T13:11:07.750314Z","shell.execute_reply.started":"2022-02-20T13:11:07.527648Z","shell.execute_reply":"2022-02-20T13:11:07.749282Z"},"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    \"./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":"2022-02-20T13:11:50.876992Z","iopub.execute_input":"2022-02-20T13:11:50.877258Z","iopub.status.idle":"2022-02-20T13:11:51.025182Z","shell.execute_reply.started":"2022-02-20T13:11:50.877229Z","shell.execute_reply":"2022-02-20T13:11:51.024075Z"},"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    \"./train/\", \n    x_col='filename',\n    y_col='category',\n    target_size=IMAGE_SIZE,\n    class_mode='categorical'\n)","metadata":{"execution":{"iopub.status.busy":"2022-02-20T13:12:05.652185Z","iopub.execute_input":"2022-02-20T13:12:05.652707Z","iopub.status.idle":"2022-02-20T13:12:05.687509Z","shell.execute_reply.started":"2022-02-20T13:12:05.652649Z","shell.execute_reply":"2022-02-20T13:12:05.68646Z"},"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":"2022-02-20T13:12:28.301169Z","iopub.execute_input":"2022-02-20T13:12:28.301952Z","iopub.status.idle":"2022-02-20T13:12:30.662002Z","shell.execute_reply.started":"2022-02-20T13:12:28.30192Z","shell.execute_reply":"2022-02-20T13:12:30.661167Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"epochs=3 if FAST_RUN else 1\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":"2022-02-20T13:26:35.238377Z","iopub.execute_input":"2022-02-20T13:26:35.239294Z","iopub.status.idle":"2022-02-20T13:29:13.671956Z","shell.execute_reply.started":"2022-02-20T13:26:35.239259Z","shell.execute_reply":"2022-02-20T13:29:13.670942Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.save(\"./model.h5\")","metadata":{"execution":{"iopub.status.busy":"2022-02-20T13:35:54.263955Z","iopub.execute_input":"2022-02-20T13:35:54.264267Z","iopub.status.idle":"2022-02-20T13:35:54.627256Z","shell.execute_reply.started":"2022-02-20T13:35:54.264237Z","shell.execute_reply":"2022-02-20T13:35:54.626256Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n","metadata":{"execution":{"iopub.status.busy":"2022-02-20T13:36:06.581873Z","iopub.execute_input":"2022-02-20T13:36:06.58254Z","iopub.status.idle":"2022-02-20T13:36:07.142406Z","shell.execute_reply.started":"2022-02-20T13:36:06.582504Z","shell.execute_reply":"2022-02-20T13:36:07.140354Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"'''from tensorflow.keras.models import load_model\nmodel = load_model('./model.h5')\nfig, (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['acc'], color='b', label=\"Training accuracy\")\nax2.plot(history.history['val_acc'], 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":"2022-02-20T13:29:53.217736Z","iopub.execute_input":"2022-02-20T13:29:53.218019Z","iopub.status.idle":"2022-02-20T13:29:53.552799Z","shell.execute_reply.started":"2022-02-20T13:29:53.217988Z","shell.execute_reply":"2022-02-20T13:29:53.551365Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# predict","metadata":{}},{"cell_type":"code","source":"'''predict = model.predict_generator(test_generator, steps=np.ceil(nb_samples/batch_size))\ntest_df['category'] = np.argmax(predict, axis=-1)\n\nlabel_map = dict((v,k) for k,v in train_generator.class_indices.items())\ntest_df['category'] = test_df['category'].replace(label_map)\ntest_df['category'] = test_df['category'].replace({ 'dog': 1, 'cat': 0 })\n\ntest_df['category'].value_counts().plot.bar()'''","metadata":{"execution":{"iopub.status.busy":"2022-02-20T14:43:06.981115Z","iopub.execute_input":"2022-02-20T14:43:06.981432Z","iopub.status.idle":"2022-02-20T14:43:07.060837Z","shell.execute_reply.started":"2022-02-20T14:43:06.981351Z","shell.execute_reply":"2022-02-20T14:43:07.059669Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"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(\"../input/test1/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_count":null,"outputs":[]}]}