{"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":"import tensorflow as tf\n\nimport keras\nfrom keras.datasets import mnist\nfrom keras import backend as K\nimport pandas as pd\nimport numpy as np\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import train_test_split\nfrom keras import layers, callbacks\nfrom keras.layers import AveragePooling2D,Add, concatenate, Convolution2D, Conv2D, Input, MaxPooling2D, UpSampling2D, Activation, ZeroPadding2D,Dropout,Conv2DTranspose\nfrom keras.layers.core import Reshape, Permute, Flatten\nfrom keras.layers.normalization import BatchNormalization \nfrom keras.layers import LeakyReLU, Dense, MaxPool2D\nfrom keras.optimizers import RMSprop,SGD,Adam\nfrom keras.models import Model\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import ReduceLROnPlateau\nfrom keras.models import Sequential\nfrom sklearn import metrics\nfrom keras.callbacks import LearningRateScheduler, ModelCheckpoint\nfrom sklearn.utils import shuffle","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"batch_size = 500\nnum_classes = 10\nepochs = 300\nimg_rows, img_cols = 28,28\n\n\n# In[3]:\n\n\ntest = pd.read_csv('/kaggle/input/Kannada-MNIST/test.csv')\ntrain = pd.read_csv('/kaggle/input/Kannada-MNIST/train.csv')\nDig_MNIST = pd.read_csv(\"/kaggle/input/Kannada-MNIST/Dig-MNIST.csv\")\n\nx_dig=Dig_MNIST.drop('label',axis=1).iloc[:,:].values\nx_dig = x_dig.reshape(x_dig.shape[0], 28, 28,1)\ny_dig=Dig_MNIST.label\n\nX=train.iloc[:,1:].values \nY=train.iloc[:,0].values\n\nX = X.reshape(X.shape[0], 28, 28,1) \nY = keras.utils.to_categorical(Y, 10) \n\nx_test=test.drop('id', axis=1).iloc[:,:].values\nx_test = x_test.reshape(x_test.shape[0], 28, 28,1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# y_dig = keras.utils.to_categorical(y_dig, 10) \n# y_dig.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# X = np.concatenate((X,x_dig), axis=0)\n# Y = np.concatenate((Y,y_dig), axis=0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X,Y = shuffle(X,Y)\nX_train, X_valid, Y_train, Y_valid = train_test_split(X, Y, test_size = 0.2, random_state=42)\n\n\ntrain_datagen = ImageDataGenerator(rescale = 1./255.,\n                                   rotation_range = 12,\n                                   width_shift_range = 0.25,\n                                   height_shift_range = 0.25,\n                                   #shear_range = 0.15,\n                                   zoom_range = 0.15,\n                                   horizontal_flip = False,\n                                   vertical_flip = False)\n\nvalid_datagen = ImageDataGenerator(rescale=1./255) ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"initial_learningrate = 5e-3\nbatch_size = 128\nepochs = 100\n\ndef lr_decay(epoch):#lrv\n    return initial_learningrate * 0.99 ** epoch","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learning_rate_reduction = ReduceLROnPlateau(monitor='loss', \n                                            patience=4, \n                                            verbose=1, \n                                            factor=0.5, \n                                            min_lr=0.00001)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_model(num_classes, input_shape):\n    model = Sequential()\n\n    model.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same', \n                 activation ='relu', input_shape = (28,28,1)))\n    model.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same', \n                 activation ='relu'))\n    model.add(BatchNormalization())\n    model.add(MaxPool2D(pool_size=(2,2)))\n    model.add(Dropout(0.2))\n\n\n    model.add(Conv2D(filters = 64, kernel_size = (5,5),padding = 'Same', \n                 activation ='relu'))\n    model.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same', \n                 activation ='relu'))\n    model.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same', \n                 activation ='relu'))\n    model.add(BatchNormalization())\n    model.add(MaxPool2D(pool_size=(2,2), strides=(2,2)))\n    model.add(Dropout(0.2))\n\n\n    model.add(Flatten())\n    model.add(Dense(256, activation = \"relu\"))\n    model.add(BatchNormalization())\n    model.add(Dropout(0.4))\n    model.add(Dense(84, activation = \"relu\"))\n    model.add(BatchNormalization())\n    model.add(Dropout(0.4))\n    model.add(Dense(10, activation = \"softmax\"))\n    \n    return model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def lenet():\n    model = Sequential()\n    model.add(Conv2D(filters=32, kernel_size=(5,5), padding='same', activation='relu', input_shape=(28, 28, 1)))\n    model.add(MaxPool2D(strides=2))\n    model.add(Conv2D(filters=48, kernel_size=(5,5), padding='valid', activation='relu'))\n    model.add(MaxPool2D(strides=2))\n    model.add(Flatten())\n    model.add(Dense(256, activation='relu'))\n    model.add(Dense(84, activation='relu'))\n    model.add(Dense(10, activation='softmax'))\n    \n    return model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"input_shape = (28,28,1)\nmodel = get_model(num_classes, input_shape)\n# model = lenet()\n# optimizer = RMSprop(lr=0.001, rho=0.9, epsilon=1e-08, decay=0.0)\noptimizer = Adam(lr=initial_learningrate)\n# model.summary()\n\nmodel.compile(loss=\"categorical_crossentropy\",\n              optimizer= optimizer,\n              metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = 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=70,\n      callbacks=[learning_rate_reduction           \n               ],\n      validation_data=valid_datagen.flow(X_valid,Y_valid),\n      #validation_steps=50,  \n      verbose=2\n    ,class_weight = {0:2,1:1,2:1,3:1,4:1,5:1,6:2,7:2,8:1,9:1})","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# model.load_weights('./model.h5',overwrite=True)\n# preds_dig=model.predict(x_dig/255.)\n# preds_dig = np.argmax(preds_dig,axis=-1)\n# print(metrics.accuracy_score(preds_dig, y_dig))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predictions = model.predict(x_test/255.)\n# predictions = np.argmax(predictions)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predictions.shape\n# Y.shape,y2_train.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x2_train, x2_test, y2_train, y2_test = train_test_split(x_test, predictions, test_size=0.15)\nx_train_final = np.concatenate((X,x2_train), axis=0)\ny_train_final = np.concatenate((Y,y2_train), axis=0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train, X_test, Y_train, Y_test = train_test_split(x_train_final, y_train_final, test_size=0.2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"keras.backend.clear_session()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model2 = get_model(num_classes, input_shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learning_rate_reduction2 = ReduceLROnPlateau(monitor='loss', patience=4, verbose=1, factor=0.5, min_lr=0.00001)\ncheckpoint2 = ModelCheckpoint(\"bestmodel.model\", monitor='loss', verbose=1, save_best_only=True)\nmodel2.compile(loss='categorical_crossentropy', optimizer=Adam(lr=0.002), metrics=['acc'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history2 = model2.fit_generator(\n    train_datagen.flow(X_train, Y_train, batch_size=128),\n    steps_per_epoch=X_train.shape[0] // 128,\n    epochs=70,\n    validation_data=valid_datagen.flow(X_test, Y_test),\n    validation_steps=X_test.shape[0] // 128,\n    callbacks=[checkpoint2, learning_rate_reduction2],\n    class_weight = {0:2,1:1,2:1,3:1,4:1,5:1,6:2,7:2,8:1,9:1})","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model2.load_weights('bestmodel.model')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"preds_dig=model2.predict(x_dig/255.)\npreds_dig = np.argmax(preds_dig,axis=-1)\nprint(metrics.accuracy_score(preds_dig, y_dig))\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"results=model2.predict(x_test/255.0)\npredictions=np.argmax(results, axis=-1)\nsubmission = pd.read_csv('/kaggle/input/Kannada-MNIST/sample_submission.csv')\nsubmission['label'] = predictions\nsubmission.to_csv(\"submission.csv\",index=False)\nprint('Done')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"misclassified = []\nfor i in range(len(preds_dig)):\n    if preds_dig[i] != y_dig[i]:\n        misclassified.append((preds_dig[i],y_dig[i]))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"cnt = {}\nfor a,b in misclassified:\n    if b not in cnt:\n        cnt[b] = 0\n    cnt[b] += 1","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"cnt","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# from sklearn.metrics import plot_confusion_matrix\n# import matplotlib.pyplot as plt","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# plot_confusion_matrix(model, x_dig, y_dig,\n#                                  display_labels=[0,1,2,3,4,5,6,7,8,9],\n#                                  cmap=plt.cm.Blues,\n#                                  normalize=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":1}