{"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 in \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 \"../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# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"%matplotlib inline\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nfrom pathlib import Path\nimport matplotlib.pyplot as plt\nimport keras\nfrom keras.datasets import mnist\nfrom keras.layers import Input, Dense, Dropout, Flatten, add\nfrom keras.layers import Conv2D, Activation, MaxPooling2D, AveragePooling2D, BatchNormalization\nfrom keras import backend as K\nfrom keras.callbacks import ModelCheckpoint\nimport tensorflow as tf\nfrom keras.models import Model\nfrom keras.utils import plot_model\nfrom keras.preprocessing. image import ImageDataGenerator\nfrom keras.callbacks import ModelCheckpoint\nfrom keras.optimizers import Adam\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.layers import Input, Dense, PReLU, Dropout\nfrom keras.models import Model\nfrom keras.callbacks import LearningRateScheduler, ModelCheckpoint, TensorBoard, EarlyStopping, ReduceLROnPlateau\nfrom keras.optimizers import SGD, Adam\nimport cv2\nfrom PIL import Image\nfrom skimage import io\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import os\nprint(os.listdir(\"../input\"))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data_dir = '../input/Kannada-MNIST/'\ntrain_data = pd.read_csv('/kaggle/input/Kannada-MNIST/train.csv')\ntest_data = pd.read_csv('/kaggle/input/Kannada-MNIST/test.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_data.columns","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_data.groupby(by='label').size()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"IMG_SIZE = 28","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.utils import to_categorical\nimg_train = train_data.drop([\"label\"], axis=1).values.reshape(-1, IMG_SIZE, IMG_SIZE, 1).astype('float32')\nimg_label = to_categorical(train_data[\"label\"])\n\nimg_test = test_data.drop([\"id\"], axis=1).values.reshape(-1, IMG_SIZE, IMG_SIZE, 1).astype('float32')\n\nprint(\"img_train.shape = \", img_train.shape)\nprint(\"img_label.shape = \", img_label.shape)\nprint(\"img_test.shape = \", img_test.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\n\nx_train, x_test, y_train, y_test = train_test_split(img_train, img_label, test_size=0.15)\nprint(\"x_train.shape = \", x_train.shape)\nprint(\"y_train.shape = \", y_train.shape)\nprint(\"x_test.shape = \", x_test.shape)\nprint(\"y_test.shape = \", y_test.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"## creating the model defination.","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def build_model(input_shape=(28, 28, 1), classes = 10):\n    input_layer = Input(shape=input_shape)\n    x = Conv2D(16, (3,3), strides=1, padding=\"same\", name=\"conv1\")(input_layer)\n    x = BatchNormalization(momentum=0.1, epsilon=1e-5, gamma_initializer=\"uniform\", name=\"batch1\")(x)\n    x = Activation('relu',name='relu1')(x)\n    x = Dropout(0.1)(x)\n    \n    x = Conv2D(32, (3,3), strides=1, padding=\"same\", name=\"conv2\")(x)\n    x = BatchNormalization(momentum=0.15, epsilon=1e-5, gamma_initializer=\"uniform\", name=\"batch2\")(x)\n    x = Activation('relu',name='relu2')(x)\n    x = Dropout(0.15)(x)\n    x = MaxPooling2D(pool_size=2, strides=2, padding=\"same\", name=\"max2\")(x)\n    \n    x = Conv2D(64, (5,5), strides=1, padding =\"same\", name=\"conv3\")(x)\n    x = BatchNormalization(momentum=0.17, epsilon=1e-5, gamma_initializer=\"uniform\", name=\"batch3\")(x)\n    x = Activation('relu', name=\"relu3\")(x)\n    x = MaxPooling2D(pool_size=2, strides=2, padding=\"same\", name=\"max3\")(x)\n    \n    x = Conv2D(128, (5,5), strides=1, padding=\"same\", name=\"conv4\")(x)\n    x = BatchNormalization(momentum=0.15, epsilon=1e-5, gamma_initializer=\"uniform\", name=\"batch4\")(x)\n    x = Activation('relu', name=\"relu4\")(x)\n    x = Dropout(0.17)(x)\n    \n    x = Conv2D(64, (3,3), strides=1, padding=\"same\", name=\"conv5\")(x)\n    x = BatchNormalization(momentum=0.15, epsilon=1e-5, gamma_initializer=\"uniform\", name=\"batch5\")(x)\n    x = Activation('relu', name='relu5')(x)\n    x = Dropout(0.2)(x)\n    \n    x = Conv2D(32, (3,3), strides=1, padding=\"same\", name=\"conv6\")(x)\n    x = BatchNormalization(momentum=0.15, epsilon=1e-5, gamma_initializer=\"uniform\", name=\"batch6\" )(x)\n    \n    x = Activation('relu', name=\"relu6\")(x)\n    x = Dropout(0.05)(x)\n    \n    x = Flatten()(x)\n    x = Dense(50, name=\"Dense1\")(x)\n    x = Activation('relu', name='relu7')(x)\n    x = Dropout(0.05)(x)\n    x = Dense(25, name=\"Dense2\")(x)\n    x = Activation('relu', name='relu8')(x)\n    x = Dropout(0.03)(x)\n    x = Dense(classes, name=\"Dense3\")(x)\n    x = Activation('softmax')(x)\n\n    model = Model(inputs=input_layer, outputs=x)\n    return model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# define the model class\nmodel = build_model(input_shape=(28, 28, 1), classes = 10)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# create iagedatagenerator\ntrain_datagen = ImageDataGenerator(\n    rotation_range=9, \n    zoom_range=0.25, \n    width_shift_range=0.25, \n    height_shift_range=0.25,\n    rescale=1./255\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# fit traiing data to ImageDataGenerator\ntrain_datagen.fit(x_train)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_datagen = ImageDataGenerator(rescale=1./255)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# define optimizer and checkpoints\nadam = Adam(lr=0.002, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=False)\n\nsgd = SGD(lr=0.01, momentum=0.0, decay=0.0, nesterov=False)\n\nlearning_rate_reduction = ReduceLROnPlateau(monitor='val_loss', patience=5, verbose=1, factor=0.5, min_lr=0.00001)\n\ncheckpoint = ModelCheckpoint(\"bestmodel.model\", monitor='val_acc', verbose=1, save_best_only=True)\n\nearlyStopping = EarlyStopping(monitor='val_acc', patience=15, verbose=1, mode='min')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['acc'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"epochs = 80\nbatch_size = 128","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\n\nhistory = model.fit_generator(\n    train_datagen.flow(x_train, y_train, batch_size=batch_size),\n    steps_per_epoch=x_train.shape[0] // batch_size,\n    epochs=epochs,\n    validation_data=test_datagen.flow(x_test, y_test),\n    validation_steps=x_test.shape[0] // batch_size,\n    callbacks=[checkpoint, learning_rate_reduction])\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.load_weights('bestodel.model')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"results = model.predict(img_test/255.0)\nresults = np.argmax(results,axis=1)\nsub = pd.DataFrame()\nsub['id'] = list(test_data.values[0:,0])\nsub['label'] = results","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sub.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sub.to_csv(\"submission.csv\", index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":""}],"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}