{"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)\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nfrom os.path import join\nfrom tqdm import tqdm\nfrom keras.preprocessing import image\nfrom sklearn.preprocessing import label_binarize\nfrom sklearn.model_selection import train_test_split\nfrom mpl_toolkits.axes_grid1 import ImageGrid\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.callbacks import ModelCheckpoint\nfrom tensorflow.keras.models import load_model\nfrom tensorflow.keras.losses import categorical_crossentropy\nfrom tensorflow.keras.optimizers import SGD, Adam\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\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":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"# Read the labels.csv file\n\nDATA_DIR = \"../input/dog-breed-identification\"\n\nlabels_all = pd.read_csv(join(DATA_DIR, \"labels.csv\"))\nprint(labels_all.shape)\nlabels_all.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Visualize the number of each breeds\nbreeds_all = labels_all[\"breed\"]\nplt.figure(figsize=(15,7))\ng = sns.countplot(breeds_all, palette=\"icefire\")\nplt.title(\"Number of breed classes\")\nbreed_counts = breeds_all.value_counts()\nbreed_counts","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Selecting breeds\n\nCLASS_NAMES = ['scottish_deerhound',\n               'maltese_dog',\n               'bernese_mountain_dog']\n\nlabels = labels_all[(labels_all['breed'].isin(CLASS_NAMES))]\n\nlabels = labels.reset_index()\nlabels.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def read_img(img_id, train_or_test, size):\n    \"\"\"Read and resize image.\n    # Arguments\n        img_id: string, name of the file\n        train_or_test: string 'train' or 'test'\n        size: resize the original image\n    # Returns\n        Image as numpy array\n    \"\"\"\n    img = image.load_img(join(DATA_DIR, train_or_test, '%s.jpg' % img_id), target_size=size)\n    img = image.img_to_array(img)\n    return img","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Loading the training set\n\nIMG_SIZE = 224\n\nX_all = np.zeros((len(labels), IMG_SIZE, IMG_SIZE, 3), dtype='float32')\nY_all = label_binarize(labels['breed'], classes = CLASS_NAMES)\n\nfor i in tqdm(range(len(labels))):\n    img = read_img(labels['id'][i], 'train', (IMG_SIZE, IMG_SIZE))\n    x = np.expand_dims(img.copy(), axis=0)\n    X_all[i] = x / 255.0\n    \nprint('Train Images shape: {} size: {:,}'.format(X_all.shape, X_all.size))\nprint('One-hot encoded output shape: {} size: {:,}'.format(Y_all.shape, Y_all.size))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Show example images\n\nIMG_GRID_ROWS = 4\nIMG_GRID_COLUMNS = 4\nnum_of_images = IMG_GRID_ROWS * IMG_GRID_COLUMNS\nfig = plt.figure(1, figsize=(IMG_GRID_COLUMNS * 4, IMG_GRID_ROWS * 4))\ngrid = ImageGrid(fig, 111, nrows_ncols=(IMG_GRID_ROWS, IMG_GRID_COLUMNS), axes_pad=0.05)\n\nfor i in range(num_of_images):\n    ax = grid[i]\n    ax.imshow(X_all[i,:,:,:])\n    class_index = np.argmax(Y_all[i])\n    ax.text(10, 200, ('LABEL: %s' % CLASS_NAMES[class_index]), backgroundcolor='w')\n    ax.axis('off')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Building the Model\n\nmodel = Sequential()\n\n# 1. Convolution Layer + MaxPool\nmodel.add(Conv2D(filters = 8, kernel_size = (5,5),\n                 activation ='relu', input_shape = (IMG_SIZE,IMG_SIZE,3)))\nmodel.add(MaxPool2D(pool_size=(2,2)))\nmodel.add(Dropout(0.2))\n\n# 2. Convolution Layer + MaxPool\nmodel.add(Conv2D(filters = 16, kernel_size = (3,3), \n                 activation ='relu'))\nmodel.add(MaxPool2D(pool_size=(2,2)))\nmodel.add(Dropout(0.2))\n\n# 3. Convolution Layer + MaxPool\nmodel.add(Conv2D(filters = 32, kernel_size = (7,7),\n                 activation ='relu'))\nmodel.add(MaxPool2D(pool_size=(2,2)))\nmodel.add(Dropout(0.2))\n\n# 4. Convolution Layer + MaxPool\nmodel.add(Conv2D(filters = 64, kernel_size = (5,5),\n                 activation ='relu'))\nmodel.add(MaxPool2D(pool_size=(2,2)))\nmodel.add(Dropout(0.2))\n\n# fully connected\nmodel.add(Flatten())\nmodel.add(Dense(2048, activation = \"relu\"))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(2048, activation = \"relu\"))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(2048, activation = \"relu\"))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(1024, activation = \"relu\"))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(len(CLASS_NAMES), activation = \"softmax\"))\n\nlearning_rate = 0.0005\n\nmodel.compile(loss = categorical_crossentropy,\n              optimizer = Adam(learning_rate),\n              metrics=['accuracy'])\n\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Splitting the training data set into training and validation data sets\n\nX_train_and_val, X_test, Y_train_and_val, Y_test = train_test_split(X_all, Y_all, test_size = 0.1)\n\nX_train, X_val, Y_train, Y_val = train_test_split(X_train_and_val, Y_train_and_val, test_size = 0.2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Save the model during training \n\nsave_at = \"/kaggle/working/model.hdf5\"\nsave_best = ModelCheckpoint (save_at, monitor='val_accuracy', verbose=0, save_best_only=True, save_weights_only=False, mode='max')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Data augmentation\n\ndatagen = ImageDataGenerator(\n        rotation_range = 20,  # randomly rotate images\n        zoom_range = 0.2, # Randomly zoom images\n        width_shift_range = 0.25,  # randomly shift images horizontally\n        height_shift_range = 0.25,  # randomly shift images vertically\n        horizontal_flip = True,  # randomly flip images horizontally\n        vertical_flip = False)  # randomly flip images vertically\n\ndatagen.fit(X_train)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true},"cell_type":"code","source":"# Training the model\n\nepochs = 300\nbatch_size = 20\n\n# Normal training\n\n#history = model.fit(X_train, Y_train,\n#                    batch_size = batch_size,\n#                    epochs = epochs,\n#                    validation_data = (X_val, Y_val),\n#                    callbacks = [save_best],)\n\n# Training with data augmentation\n\nhistory = model.fit_generator(datagen.flow(X_train,Y_train, batch_size=batch_size),\n                              epochs = epochs,\n                              validation_data = (X_val, Y_val),\n                              callbacks = [save_best],\n                              steps_per_epoch=X_train.shape[0] // batch_size)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Plot the training history\n\nplt.figure(figsize=(12, 5))\n\nplt.subplot(121)\nplt.plot(history.history['loss'], color='r')\nplt.plot(history.history['val_loss'], color='b')\nplt.title('Model Loss', weight='bold', fontsize=16)\nplt.ylabel('loss', weight='bold', fontsize=14)\nplt.xlabel('epoch', weight='bold', fontsize=14)\nplt.ylim(0.0, 1.2)\nplt.xticks(weight='bold', fontsize=12)\nplt.yticks(weight='bold', fontsize=12)\nplt.legend(['train', 'val'], loc='upper right', prop={'size': 14})\nplt.grid(color = 'y', linewidth='0.5')\n\nplt.subplot(122)\nplt.plot(history.history['accuracy'], color='r')\nplt.plot(history.history['val_accuracy'], color='b')\nplt.title('Model Accuracy', weight='bold', fontsize=16)\nplt.ylabel('accuracy', weight='bold', fontsize=14)\nplt.xlabel('epoch', weight='bold', fontsize=14)\nplt.ylim(0.2, 1.0)\nplt.xticks(weight='bold', fontsize=12)\nplt.yticks(weight='bold', fontsize=12)\nplt.legend(['train', 'val'], loc='lower right', prop={'size': 14})\nplt.grid(color = 'y', linewidth='0.5')\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Making predictions on the test dataset\n\nmodel = load_model('/kaggle/working/model.hdf5')\n\nY_pred = model.predict(X_test)\nscore = model.evaluate(X_test, Y_test)\nprint('Accuracy over the test set: \\n ', round((score[1]*100), 2), '%')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Show example predictions\n\nIMG_GRID_ROWS = 6\nIMG_GRID_COLUMNS = 4\nnum_of_images = IMG_GRID_ROWS * IMG_GRID_COLUMNS\nfig = plt.figure(1, figsize=(IMG_GRID_COLUMNS * 4, IMG_GRID_ROWS * 4))\ngrid = ImageGrid(fig, 111, nrows_ncols=(IMG_GRID_ROWS, IMG_GRID_COLUMNS), axes_pad=0.05)\n\nfor i in range(num_of_images):\n    ax = grid[i]\n    ax.imshow(X_test[i,:,:,:])\n    \n    class_index_pred = np.argmax(Y_pred[i])\n    class_index_val = np.argmax(Y_test[i])\n    \n    if class_index_val == class_index_pred:\n        background_color = 'g'\n    else:\n        background_color = 'r'\n        \n    ax.text(10, 200, ('LABEL: %s' % (CLASS_NAMES[class_index_pred])),\n            color = 'w',\n            backgroundcolor = background_color)\n    \n    ax.axis('off')\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}