{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd\n\n\nfrom tensorflow import keras\nfrom tensorflow.keras.applications import DenseNet121\nimport matplotlib.pyplot as plt\n\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn import metrics\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"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))","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"TRAIN_IMG_LIST = os.listdir('../working/train')\nTEST_IMG_LIST = os.listdir('../working/test1')\nprint(len(TRAIN_IMG_LIST))\nprint(len(TEST_IMG_LIST))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"IMG_SIZE = 200\n\nimport cv2\nimg_idx = 1\nimg_path = '../working/train/' + str(TRAIN_IMG_LIST[img_idx])\nimg_label = TRAIN_IMG_LIST[img_idx][:3]\nsample_img = cv2.imread(img_path)\nsample_img = cv2.cvtColor(sample_img, cv2.COLOR_BGR2RGB)\nsample_img = cv2.resize(sample_img, (IMG_SIZE, IMG_SIZE))\nprint(sample_img.shape)\nplt.imshow(sample_img)\nplt.title(img_label)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df = pd.DataFrame()\n\nimgpaths = []\nlabels = []\n\nfor imgfile in TRAIN_IMG_LIST:\n    label =imgfile.split('.')[0]\n    full_path = '../working/train/' + imgfile\n    \n    imgpaths.append(full_path)\n    labels.append(label)\n    \ntrain_df['image_path'] = imgpaths\ntrain_df['label'] = labels\n\ntrain_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df, val_df = train_test_split(train_df, test_size=0.2, random_state=42)\nval_df.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#MODEL\ndensenet = DenseNet121(\n    weights = '../input/densenet-keras/DenseNet-BC-121-32-no-top.h5',\n    include_top = False,\n    input_shape = (IMG_SIZE, IMG_SIZE, 3)\n\n)\n\nmodel = keras.Sequential()\n# model.add(keras.layers.Conv2D(filters=64, kernel_size=(3,3), activation='relu', input_shape=(IMG_SIZE, IMG_SIZE, 3)))\n# model.add(keras.layers.MaxPooling2D(pool_size=(2,2)))\n# model.add(keras.layers.Conv2D(filters=64, kernel_size=(3,3), activation='relu'))\n# model.add(keras.layers.MaxPooling2D(pool_size=(2,2)))\n# model.add(keras.layers.Conv2D(filters=128, kernel_size=(3,3), activation='relu'))\n# model.add(keras.layers.MaxPooling2D(pool_size=(2,2)))\n# model.add(keras.layers.Conv2D(filters=128, kernel_size=(3,3), activation='relu'))\n# model.add(keras.layers.MaxPooling2D(pool_size=(2,2)))\n\nmodel.add(densenet)\n\nmodel.add(keras.layers.GlobalAveragePooling2D())\nmodel.add(keras.layers.Dense(256, activation='relu'))\nmodel.add(keras.layers.Dropout(0.3))\nmodel.add(keras.layers.BatchNormalization())\nmodel.add(keras.layers.Dense(2, activation='softmax'))\n\nmodel.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator\n\ntrain_datagen = ImageDataGenerator(\n    rotation_range=10,\n    rescale = 1./255.,\n    horizontal_flip = True,\n    width_shift_range = 0.1,\n    height_shift_range = 0.1\n)\n\ntrain_datagenerator = train_datagen.flow_from_dataframe(\n    dataframe = train_df,\n    x_col = 'image_path',\n    y_col = 'label',\n    target_size = (IMG_SIZE, IMG_SIZE),\n    class_mode = 'categorical',\n    batch_size = 100\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"val_datagen = ImageDataGenerator(\n    rescale = 1./255.\n)\n\nval_datagenerator = val_datagen.flow_from_dataframe(\n    dataframe = val_df,\n    x_col = 'image_path',\n    y_col = 'label',\n    target_size = (IMG_SIZE, IMG_SIZE),\n    class_mode = 'categorical',\n    batch_size = 100\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model.fit_generator(train_datagenerator,\n                              epochs = 30,\n                              validation_data = val_datagenerator,\n                              validation_steps = val_df.shape[0]//100,\n                              steps_per_epoch = train_df.shape[0]//100\n                             )","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.plot(history.history['accuracy'])\nplt.plot(history.history['val_accuracy'])\nplt.title('Model accuracy')\nplt.ylabel('Accuracy')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Test'], loc='upper left')\nplt.show()\n\n# Plot training & validation loss values\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('Model loss')\nplt.ylabel('Loss')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Test'], loc='upper left')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_datagenerator.class_indices","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.save('catvsdog_model.h5')","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":4}