{"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":{"trusted":true},"cell_type":"code","source":"import random","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.models import Sequential\nfrom keras import layers\nfrom keras.utils.np_utils import to_categorical\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras import optimizers\nfrom keras.callbacks import ReduceLROnPlateau\nfrom keras.callbacks import ModelCheckpoint\nfrom keras.models import load_model\n# from keras.callbacks import TensorBoard\nfrom keras.callbacks import LearningRateScheduler","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import confusion_matrix","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\n# import seaborn as sns\n# sns.set()","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"train_df = pd.read_csv('/kaggle/input/Kannada-MNIST/train.csv')\ntest_df = pd.read_csv('/kaggle/input/Kannada-MNIST/test.csv')\nval_df = pd.read_csv('/kaggle/input/Kannada-MNIST/Dig-MNIST.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.tail()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"val_df.tail()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df.tail()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df = pd.concat([train_df, val_df], axis = 0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"Y_train = train_df['label']\nY_id = test_df['id']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.drop('label', axis = 1, inplace = True)\ntest_df.drop('id', axis = 1, inplace = True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# X_train = train_df.to_numpy()\n# X_test = test_df.to_numpy()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(train_df.shape)\nprint(test_df.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train = train_df.values.reshape(train_df.shape[0], 28, 28, 1)\nX_test = test_df.values.reshape(test_df.shape[0], 28, 28, 1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"Y_train = np.asarray(Y_train)\nprint(Y_train.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(X_train.shape)\nprint(X_test.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def plot_digit(dataset, samples, labels):\n#     Generate a random set of samples and plot them\n#     random_samples = []\n    for pts in range(samples):\n        r_n = random.randint(0,dataset.shape[0])\n#         random_samples  = [23,43,445,44,34]\n        img = dataset[r_n].reshape(28,28)\n        plt.imshow(img, cmap = 'gray')\n        plt.title(labels[r_n])\n        plt.show()\n        ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# plot_digit(X_train, 5, Y_train)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"Y_train = to_categorical(Y_train, num_classes = 10)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train, X_val, Y_train, Y_val = train_test_split(X_train, Y_train, stratify = Y_train, random_state = 31, shuffle = True, test_size = 0.2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_datagen = ImageDataGenerator(rotation_range=30, width_shift_range=0.3,\n                                   height_shift_range=0.3, brightness_range=None, shear_range=0.3,\n                                   zoom_range=0.3, horizontal_flip=False,\n                                   vertical_flip=False, rescale=1/255.,\n                                   data_format='channels_last', validation_split=0.0,\n                                   interpolation_order=1, dtype='float32')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_val = X_val / 255.                    # Scaling validation Data","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_test = X_test / 255.","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(X_train.shape)\nprint(X_val.shape)\nprint(Y_train.shape)\nprint(Y_val.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_datagen.fit(X_train)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = Sequential()\n\nmodel.add(layers.Conv2D(128, 3, input_shape = (28,28,1), padding = 'same', activation = None))\nmodel.add(layers.LeakyReLU(alpha = 0.3))\nmodel.add(layers.BatchNormalization(axis=1))\nmodel.add(layers.Dropout(0.2))\n\nmodel.add(layers.MaxPooling2D(pool_size=(2, 2), strides=None, padding='valid', data_format=None))\n\nmodel.add(layers.Conv2D(64, 3, padding = 'same', activation = None))\nmodel.add(layers.LeakyReLU(alpha = 0.3))\nmodel.add(layers.BatchNormalization(axis=1))\nmodel.add(layers.Dropout(0.3))\n\nmodel.add(layers.MaxPooling2D(pool_size=(2, 2), strides=None, padding='valid', data_format=None))\n\nmodel.add(layers.Conv2D(64, 3, padding = 'same', activation = None))\nmodel.add(layers.LeakyReLU(alpha = 0.3))\nmodel.add(layers.BatchNormalization(axis=1))\nmodel.add(layers.Dropout(0.3))\n\nmodel.add(layers.MaxPooling2D(pool_size=(2, 2), strides=None, padding='valid', data_format=None))\n\nmodel.add(layers.Conv2D(64, 3, padding = 'same', activation = None))\nmodel.add(layers.LeakyReLU(alpha = 0.3))\nmodel.add(layers.BatchNormalization(axis=1))\nmodel.add(layers.Dropout(0.3))\n\nmodel.add(layers.MaxPooling2D(pool_size=(2, 2), strides=None, padding='valid', data_format=None))\n\nmodel.add(layers.Conv2D(32, 3, padding = 'same', activation = None))\nmodel.add(layers.LeakyReLU(alpha = 0.3))\nmodel.add(layers.BatchNormalization(axis=1))\nmodel.add(layers.Dropout(0.3))\n\nmodel.add(layers.Flatten())\nmodel.add(layers.Dense(256))\nmodel.add(layers.LeakyReLU(alpha = 0.3))\nmodel.add(layers.Dense(10, activation = 'softmax'))\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"opt1 = optimizers.Adam(learning_rate=0.0002, beta_1=0.9, beta_2=0.999)\nopt2 = optimizers.Nadam(learning_rate=0.0002, beta_1=0.9, beta_2=0.999)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"filepath1 = 'kannada_cnn_model1.hdf5'\nfilepath2 = 'kannada_cnn_model2.hdf5'\nreducelr = ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=5, verbose=1, mode='auto', min_delta=0.0001, cooldown=0, min_lr=0)\ncheckpoint1 = ModelCheckpoint(filepath1, monitor='val_loss', verbose=1, save_best_only=True, save_weights_only=False, mode='auto', period=1)\ncheckpoint2 = ModelCheckpoint(filepath2, monitor='val_loss', verbose=1, save_best_only=True, save_weights_only=False, mode='auto', period=1)\ncallback_l = [reducelr, checkpoint1]\ncallback_l2 = [reducelr, checkpoint2]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(optimizer = opt1, loss = 'categorical_crossentropy', metrics = ['acc'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"epochs = 50\nbatch_size = 128","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# print(Y_train[1])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model.fit_generator(train_datagen.flow(X_train, Y_train, batch_size = batch_size ),\n                              epochs = epochs, validation_data = (X_val, Y_val), verbose = 1,\n                              steps_per_epoch=X_train.shape[0] // batch_size, callbacks = callback_l)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# acc = history.history['acc']\n# val_acc = history.history['val_acc']\n# loss = history.history['loss']\n# val_loss = history.history['val_loss']\n\n# epochs = range(1, len(acc) + 1)\n\n# plt.plot(epochs, acc, 'g', label='Training acc')\n# plt.plot(epochs, val_acc, 'b', label='Validation acc')\n# plt.title('Training and validation accuracy')\n# plt.legend()\n# plt.figure()\n\n# plt.plot(epochs, loss, 'g', label='Training loss')\n# plt.plot(epochs, val_loss, 'b', label='Validation loss')\n# plt.title('Training and validation loss')\n# plt.legend()\n# plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# model.compile(optimizer = opt2, loss = 'categorical_crossentropy', metrics = ['acc'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# history = model.fit_generator(train_datagen.flow(X_train, Y_train, batch_size = batch_size ),\n#                               epochs = 50, validation_data = (X_val, Y_val), verbose = 1,\n#                               steps_per_epoch=X_train.shape[0] // batch_size, callbacks = callback_l2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# acc = history.history['acc']\n# val_acc = history.history['val_acc']\n# loss = history.history['loss']\n# val_loss = history.history['val_loss']\n\n# epochs = range(1, len(acc) + 1)\n\n# plt.plot(epochs, acc, 'g', label='Training acc')\n# plt.plot(epochs, val_acc, 'b', label='Validation acc')\n# plt.title('Training and validation accuracy')\n# plt.legend()\n# plt.figure()\n\n# plt.plot(epochs, loss, 'g', label='Training loss')\n# plt.plot(epochs, val_loss, 'b', label='Validation loss')\n# plt.title('Training and validation loss')\n# plt.legend()\n# plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"best_model = Sequential()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"best_model = load_model(filepath1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_pred = best_model.predict(X_test)\ny_pred = np.argmax(y_pred, axis = 1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_sub = pd.read_csv('/kaggle/input/Kannada-MNIST/sample_submission.csv')\nsample_sub['label'] = y_pred\nsample_sub.to_csv('submission.csv', index = False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_sub.tail()","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":1}