{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"from keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Sequential\nfrom keras.layers import  Conv2D ,MaxPool2D\nfrom keras.layers import Activation,Dropout,Flatten, Dense\nfrom keras import backend as k\nimport numpy as np\nfrom keras.preprocessing import image\nimport tensorflow as tf\nimport os\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tqdm\nfrom sklearn.utils import shuffle\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Activation, Conv2D, Flatten, BatchNormalization, Dropout, MaxPool2D\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ReduceLROnPlateau, EarlyStopping\nfrom keras.utils import np_utils\nimport pandas as pd\nimport tensorflow as tf\nimport time","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_dir = \"train/\"\ntest_dir= \"test1/\"\n\nIMG_SIZE = (150, 150)\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"labels = []\nimg_path = []\npath= '/kaggle/working/train'\nfor img in os.listdir(train_dir):\n    img_path.append(os.path.join(path,img))\n    \n    if img.startswith(\"cat\"):\n        labels.append(\"cat\")\n    elif img.startswith(\"dog\"):\n        labels.append(\"dog\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df = pd.DataFrame({\n    'image' : img_path,\n    'class' : labels\n})","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df['class'].value_counts().plot.bar()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_datagen = ImageDataGenerator(validation_split = 0.25, rescale = 1. / 255)\ntrain_generator = train_datagen.flow_from_dataframe(dataframe = df, \n                                                    x_col = 'image', \n                                                    y_col = 'class', \n                                                    batch_size = 64, \n                                                    seed = 11, \n                                                    class_mode = 'categorical', \n                                                    target_size = IMG_SIZE,\n                                                    shuffle = True,\n                                                    subset=\"training\"\n                                                   )\n\nval_generator = train_datagen.flow_from_dataframe(dataframe = df, \n                                                    x_col = 'image', \n                                                    y_col = 'class', \n                                                    batch_size = 64, \n                                                    seed = 11, \n                                                    class_mode = 'categorical', \n                                                    target_size = IMG_SIZE,\n                                                    shuffle = True,\n                                                    subset=\"validation\"\n                                                   )\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_steps = train_generator.n // train_generator.batch_size\nvalidation_steps = val_generator.n // val_generator.batch_size\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.applications import DenseNet201\n\nbase_model = DenseNet201(include_top=False, weights=\"imagenet\",  input_shape=(150,150,3), pooling='avg' )\n\n\nfor layer in base_model.layers:\n    layer.trainable = False\n\nmodel = Sequential([\nbase_model,\n\nDense(512, activation='relu'),\nDropout(0.25),\nBatchNormalization(),\n\nDense(512, activation='relu'),\nDropout(0.25),\nBatchNormalization(),\n\n\n    \nDense(2, activation='softmax')])\n\n\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"optimizer = Adam(lr=0.001, beta_1=0.9, beta_2=0.999, amsgrad=False)\n\nmodel.compile(optimizer,loss='binary_crossentropy',metrics=[\"accuracy\"])\n\nes = EarlyStopping(monitor='val_loss',mode='min', verbose=1,patience=10)\n\nlr = ReduceLROnPlateau(monitor='val_accuracy', patience=3,verbose=1, factor=0.25, min_lr=0.0001)\n\nepochs = 10","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model.fit_generator(generator=train_generator,\n                    steps_per_epoch= train_steps, epochs=epochs, callbacks = [es, lr],\n                    validation_data = val_generator,validation_steps = validation_steps, max_queue_size=100, use_multiprocessing=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_acc = history.history['accuracy']\nval_acc = history.history['val_accuracy']\n\nepochs = range(len(train_acc))\n\n\nplt.plot(epochs, train_acc, label = 'Train Accuracy')\nplt.plot(epochs, val_acc, label = 'validation Accuracy')\nplt.legend(loc=0)\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_loss = history.history['loss']\nval_loss = history.history['val_loss']\n\n\n\n\nplt.plot(epochs, train_loss, label = 'Train loss')\nplt.plot(epochs, val_loss, label = 'validation loss')\nplt.legend(loc=0)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_img_path = []\n\ntest_path = '/kaggle/working/test1'\n\nfor img in os.listdir(test_path):\n    test_img_path.append(os.path.join(test_path, img))\n    \ndf_test = pd.DataFrame({'image_path': test_img_path})\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_datagen = ImageDataGenerator(rescale = 1./ 255)\ntest_generator = test_datagen.flow_from_dataframe(dataframe = df_test,\n                                                 x_col = 'image_path',\n                                                 y_col = None,\n                                                 batch_size = 50,\n                                                 seed = 11,\n                                                 target_size = IMG_SIZE,\n                                                   class_mode=None,)\n\n\n\n\n\ntest_steps = test_generator.n // test_generator.batch_size\n\npredictions = model.predict(test_generator,steps = test_steps, verbose= 1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(type(predictions))\nprint(predictions[:10])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predictions = np.argmax(predictions,axis=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(len(predictions))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import matplotlib.image as mpimg\nimport matplotlib.pyplot as plt\n\nfig = plt.figure(figsize = (10,10))\nfig.suptitle(\"predictions\", fontsize = 16)\n\nfor i, img in enumerate(df_test.image_path[:10]):\n  plt.subplot(5, 5, i + 1)\n  img = mpimg.imread(img)\n  plt.imshow(img)\n  plt.title(str(predictions[i]))\n  plt.xticks([])\n  plt.yticks([])\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_test[\"label\"]=predictions\ndf_test.to_csv(\"submission.csv\",index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","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":1}