{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import os\nos.environ['CUDA_VISIBLE_DEVICES'] = '-1'","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd \nimport tensorflow as tf\nimport zipfile\nfrom keras.preprocessing.image import ImageDataGenerator, load_img\nfrom keras.utils import to_categorical\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D, Dropout, Flatten, Dense, Activation, BatchNormalization\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\nimport random\nimport os\nprint(os.listdir(\"../input/dogs-vs-cats\"))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"'''\n# Detect hardware, return appropriate distribution strategy\ntry:\n    # TPU detection. No parameters necessary if TPU_NAME environment variable is\n    # set: this is always the case on Kaggle.\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\n    print('Running on TPU ', tpu.master())\nexcept ValueError:\n    tpu = None\n\nif tpu:\n    tf.config.experimental_connect_to_cluster(tpu)\n    tf.tpu.experimental.initialize_tpu_system(tpu)\n    strategy = tf.distribute.experimental.TPUStrategy(tpu)\nelse:\n    # Default distribution strategy in Tensorflow. Works on CPU and single GPU.\n    strategy = tf.distribute.get_strategy()\n\nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)\n'''","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Define constants"},{"metadata":{"trusted":true},"cell_type":"code","source":"# Define constants:\nIMAGE_WIDTH    = 128\nIMAGE_HEIGHT   = 128\nIMAGE_SIZE     = (IMAGE_WIDTH, IMAGE_HEIGHT)\nIMAGE_CHANNELS = 3","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Prepare Training data "},{"metadata":{"trusted":true},"cell_type":"code","source":"# Extract zip files: \ndef extract_files(source_path, target_path):\n    zip_ref = zipfile.ZipFile(source_path, 'r')\n    zip_ref.extractall(target_path)\n    zip_ref.close()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Call extractor method to extract test1.zip and train.zip\nextract_files(\"../input/dogs-vs-cats/test1.zip\", '/kaggle/working/')\nextract_files(\"../input/dogs-vs-cats/train.zip\", '/kaggle/working/')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Creat a dataframe with images,categories\n\nfilenames = os.listdir('/kaggle/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({'filename' : filenames, 'category' : categories})","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df['category'].value_counts().plot.bar()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df['category'].value_counts()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Visualize a sample image: \nsample = random.choice(filenames)\nimage = load_img('/kaggle/working/train/'+sample)\nplt.imshow(image)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Build model"},{"metadata":{},"cell_type":"markdown","source":"### Input Layer \nrepresent the input image data. It will reshape image into single dimenstion.\n### Conv Layer\nExtract features from image\n### Fully Connected Layer \nConnect network from layers \n### Output Layer\nPredict values for input"},{"metadata":{"trusted":true},"cell_type":"code","source":"model = Sequential()\n\n# Layer 1\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\n# Layer 2\nmodel.add(Conv2D(64, (3,3), activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2,2)))\nmodel.add(Dropout(0.25))\n\n# Layer 3\nmodel.add(Conv2D(128, (3,3), activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2,2)))\nmodel.add(Dropout(0.25))\n\n# NN Layer\nmodel.add(Flatten())\nmodel.add(Dense(512, activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.25))\n\n# Output layer\nmodel.add(Dense(2, activation='softmax'))\n\nmodel.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Callbacks"},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.callbacks import EarlyStopping, ReduceLROnPlateau","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Early stopping \nTo prevent the model from getting low (accuracy)."},{"metadata":{"trusted":true},"cell_type":"code","source":"earlystop = EarlyStopping(patience=10)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Learning_rate "},{"metadata":{"trusted":true},"cell_type":"code","source":"learning_rate_reduction = ReduceLROnPlateau(monitor='val_acc', \n                                            patience=3, \n                                            verbose=0, \n                                            factor=0.5, \n                                            min_lr= 0.00001)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"callbacks = [earlystop,learning_rate_reduction]","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Prepare data "},{"metadata":{"trusted":true},"cell_type":"code","source":"df['category'] = df['category'].replace({0:'cat', 1:'dog'})","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"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)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.category.value_counts()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"validate_df.category.value_counts()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Train Generator"},{"metadata":{"trusted":true},"cell_type":"code","source":"total_train = train_df.shape[0]\ntotal_validate = validate_df.shape[0]\nbatch_size =15","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# data generation : data augmentation \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\ntrain_generator = train_datagen.flow_from_dataframe(\n                    train_df, \n                    '/kaggle/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)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# data generation for valiadation data\nvalidation_datagen = ImageDataGenerator(rescale= 1./255)\nvalidation_generator = validation_datagen.flow_from_dataframe(\n                        validate_df,\n                        '/kaggle/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)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## See the genarator work "},{"metadata":{"trusted":true},"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                    '/kaggle/working/train/',\n                    x_col = 'filename',\n                    y_col = 'category',\n                    target_size = IMAGE_SIZE,\n                    class_mode = 'categorical'\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"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()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Fit Model"},{"metadata":{"trusted":true},"cell_type":"code","source":"tf.test.gpu_device_name()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"epochs = 10\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)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Save Model "},{"metadata":{"trusted":true},"cell_type":"code","source":"model.save_weights('model.h5')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Visualize Training"},{"metadata":{"trusted":true},"cell_type":"code","source":"fig, (ax1, ax2) = plt.subplots(2,1, figsize=(16,12))\n\n# First graph\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))\n\n\n\n# Second graph\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()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Prepare Testing Data"},{"metadata":{"trusted":true},"cell_type":"code","source":"test_filename = os.listdir('/kaggle/working/test1')\ntest_df = pd.DataFrame({'filename': test_filenames})\nnb_samples = test_df.shape[0]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Create Testing Generator \ntest_gen = ImageDataGenerator(rescale= 1./255)\ntest_generator = test_gen.flow_from_dataframe(\n                test_df,\n                '/kaggle/working/test1/',\n                x_col = 'filename',\n                y_col = None,\n                target_size = IMAGE_SIZE,\n                batch_size= batch_size\n                )","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Predict "},{"metadata":{"trusted":true},"cell_type":"code","source":"predict = model.predict_generator(test_generator, steps= np.ceil(nb_samples//batch_size))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predict","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(np.argmax(predict, axis=-1))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df['category'] = np.argmax(predict, axis=-1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"label_map = dict((v,k) for k,v in train_generator.class_indices.items())\n# Label_map {1:'cat', 0:dog}\ntest_df['category'] = test_df['category'].replace(label_map)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df['category'].value_counts()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df['category'].value_counts().plot().bar()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_test = test_df.head(18)\n\nplt.fogure(figsize=(16,24))\nfor index, row in sample_test.iterrows():\n    filename = row['filename']\n    category = row['category']\n    img = load_img('/kaggle/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\nplt.tight_layout()\nplt.show()","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}