{"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 5GB 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":{},"cell_type":"markdown","source":"# Import packages","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"import numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom keras.datasets import cifar10\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.layers import Input, Conv2D, Dense, Activation, Flatten, Dropout, MaxPooling2D, BatchNormalization\nfrom tensorflow.keras.models import Sequential, Model, load_model\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras import regularizers, optimizers\nfrom tensorflow.keras.callbacks import ReduceLROnPlateau, EarlyStopping, ModelCheckpoint","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Read data","execution_count":null},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"#cifar10 = tf.keras.datasets.cifar10\n(X_train, y_train), (X_test, y_test) = cifar10.load_data()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Data processing","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# number of classes\nK = len(set(y_train.flatten()))\nprint(\"number of classes:\", K)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train = X_train.astype('float32')/255\nX_test = X_test.astype('float32')/255\ny_train_cat = to_categorical(y_train, 10)\ny_test_cat = to_categorical(y_test, 10)\nprint(\"x_train.shape:\", X_train.shape)\nprint(\"y_train_cat.shape\", y_train.shape)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Build model","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"rlr = ReduceLROnPlateau(monitor='val_accuracy', mode ='max', factor=0.5, min_lr=1e-7, verbose = 1, patience=10)\nes = EarlyStopping(monitor='val_accuracy', mode='max', verbose = 1, patience=50, restore_best_weights=True)\nmc = ModelCheckpoint('cnn_best_model.h5', monitor='val_accuracy', mode='max', verbose = 1, save_best_only=True)\ncallback_list = [rlr, es, mc]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# build model\ndef build_model(lr = 0, dc = 0, dr = 0):\n    model = Sequential(name = 'CNN_cifar10')\n    model.add(Conv2D(32, (3, 3), activation='elu', kernel_initializer='he_uniform', kernel_regularizer=regularizers.l2(1e-4), padding='same', input_shape=(32, 32, 3)))\n    model.add(BatchNormalization())\n    model.add(Conv2D(32, (3, 3), activation='elu', kernel_initializer='he_uniform', kernel_regularizer=regularizers.l2(1e-4), padding='same'))\n    model.add(BatchNormalization())\n    model.add(MaxPooling2D((2, 2)))\n    model.add(Dropout(0.2))\n\n    model.add(Conv2D(64, (3, 3), activation='elu', kernel_initializer='he_uniform', kernel_regularizer=regularizers.l2(1e-4), padding='same'))\n    model.add(BatchNormalization())\n    model.add(Conv2D(64, (3, 3), activation='elu', kernel_initializer='he_uniform', kernel_regularizer=regularizers.l2(1e-4), padding='same'))\n    model.add(BatchNormalization())\n    model.add(MaxPooling2D((2, 2)))\n    model.add(Dropout(0.3))\n\n    model.add(Conv2D(128, (3, 3), activation='elu', kernel_initializer='he_uniform', kernel_regularizer=regularizers.l2(1e-4), padding='same'))\n    model.add(BatchNormalization())\n    model.add(Conv2D(128, (3, 3), activation='elu', kernel_initializer='he_uniform', kernel_regularizer=regularizers.l2(1e-4), padding='same'))\n    model.add(BatchNormalization())\n    model.add(MaxPooling2D((2, 2)))\n    model.add(Dropout(0.4))\n\n    model.add(Flatten())\n    model.add(Dense(256, activation='elu', kernel_initializer='he_uniform'))\n    model.add(BatchNormalization())\n    model.add(Dropout(dr))\n    model.add(Dense(10, activation='softmax'))\n    # compile model\n    opt = optimizers.Adam(lr = lr, decay = dc)\n    model.compile(loss='categorical_crossentropy', optimizer=opt, metrics=['accuracy'])\n    return model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = build_model(lr = 0.001, dc = 1e-5, dr = 0.5)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#data augmentation\ndatagen = ImageDataGenerator(\n                            rotation_range=15,\n                            width_shift_range=0.1,\n                            height_shift_range=0.1,\n                            horizontal_flip=True,\n                            vertical_flip=False\n                            )\ndatagen.fit(X_train)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Run model","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# run model\nmodel.fit_generator(datagen.flow(X_train, y_train_cat, batch_size = 64),\n                                 validation_data = (X_test, y_test_cat),\n                                 steps_per_epoch = X_train.shape[0] // 64, \n                                 epochs = 40, verbose = 1,\n                                 callbacks = callback_list)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Evaluate model","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"def plot_model(history): \n    fig, axs = plt.subplots(1,2,figsize=(16,5)) \n    # summarize history for accuracy\n    axs[0].plot(history.history['accuracy'], 'c') \n    axs[0].plot(history.history['val_accuracy'],'m') \n    axs[0].set_title('Model Accuracy')\n    axs[0].set_ylabel('Accuracy') \n    axs[0].set_xlabel('Epoch')\n    axs[0].legend(['train', 'validate'], loc='upper left')\n    # summarize history for loss\n    axs[1].plot(history.history['loss'], 'c') \n    axs[1].plot(history.history['val_loss'], 'm') \n    axs[1].set_title('Model Loss')\n    axs[1].set_ylabel('Loss') \n    axs[1].set_xlabel('Epoch')\n    axs[1].legend(['train', 'validate'], loc='upper right')\n    plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plot_model(model.history)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"saved_model = load_model('cnn_best_model.h5')\ntest_loss, test_acc = saved_model.evaluate(X_test, y_test_cat, verbose=0)\nprint('Test Accuracy:', round(test_acc, 2))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Submission","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"y_pred = saved_model.predict_classes(X_test, verbose=0)\n\nclass_names = ['airplane',\n                'automobile',\n                'bird',\n                'cat',\n                'deer',\n                'dog',\n                'frog',\n                'horse',\n                'ship',\n                'truck']\ny_pred = [class_names[i] for i in y_pred]\n\nsubmissions=pd.DataFrame({\"id\": list(range(1, len(y_pred)+1)),\n                          \"label\": y_pred})\n\nsubmissions.to_csv(\"submission.csv\", index=False)","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}