{"cells":[{"metadata":{},"cell_type":"markdown","source":"## Importing Libraries"},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport seaborn as sns\n\n%matplotlib inline\nsns.set(style='white', context='notebook', palette='deep')\n\nnp.random.seed(2)\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix\n\nfrom keras.utils.np_utils import to_categorical\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D\nfrom keras.optimizers import RMSprop\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import ReduceLROnPlateau","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Importing Datasets"},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"# importing training and testing dataset\n\ntrain = pd.read_csv(\"../input/Kannada-MNIST/train.csv\")\ntest = pd.read_csv(\"../input/Kannada-MNIST/test.csv\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Checking Datasets"},{"metadata":{"trusted":true},"cell_type":"code","source":"# training dataset\ntrain.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# test dataset\ntest.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# train.isna().sum().sum()\n# test.isna().sum().sum()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# train.info()\n# train.describe()\ntrain.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# test.info()\n# test.describe()\ntest.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Store training features in X_train and training targets in Y_train\n\nX = train.drop([\"label\"], axis=1)\ny = train['label']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(X.shape)\nprint(y.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# sns.countplot(y)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Reshape Features"},{"metadata":{"trusted":true},"cell_type":"code","source":"X_reshape = X.to_numpy().reshape(-1,28,28)\nX_reshape.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=[10,5])\nplt.subplot(111)\nplt.imshow(X_reshape[0])\nplt.title(y[0])\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_reshape = X.to_numpy().reshape(-1,28,28,1)\nX_reshape.shape","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## One Hot Encode Target"},{"metadata":{"trusted":true},"cell_type":"code","source":"y_enc = to_categorical(y)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(X.shape)\nprint(y.shape)\nprint(X_reshape.shape)\nprint(y_enc.shape)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Train - Test split"},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train, X_test, y_train, y_test = train_test_split(X_reshape, y_enc, test_size = 0.1)\nprint(X_train.shape)\nprint(y_train.shape)\nprint(X_test.shape)\nprint(y_test.shape)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Train - Valid Split"},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train, X_valid, y_train, y_valid = train_test_split(X_train, y_train, test_size = 0.5)\nprint(X_train.shape)\nprint(y_train.shape)\nprint(X_valid.shape)\nprint(y_valid.shape)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Model Creation"},{"metadata":{"trusted":true},"cell_type":"code","source":"model = Sequential()\n\nmodel.add(Conv2D(32, (5,5), padding = 'Same', activation ='relu', input_shape = (28,28,1)))\nmodel.add(Conv2D(32, (5,5), padding = 'Same', activation ='relu'))\nmodel.add(MaxPool2D((2,2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Conv2D(64, (3,3), padding = 'Same', activation ='relu'))\nmodel.add(Conv2D(64, (3,3), padding = 'Same', activation ='relu'))\nmodel.add(MaxPool2D((2,2), strides=(2,2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Flatten())\nmodel.add(Dense(256, activation = \"relu\"))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(10, activation = \"softmax\"))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Compile Model"},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(optimizer = RMSprop(lr=0.001, rho=0.9, epsilon=1e-08, decay=0.0), \n              loss = \"categorical_crossentropy\", \n              metrics = [\"accuracy\"])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"datagen = ImageDataGenerator(featurewise_center=False,  # set input mean to 0 over the dataset\n                             samplewise_center=False,  # set each sample mean to 0\n                             featurewise_std_normalization=False,  # divide inputs by std of the dataset\n                             samplewise_std_normalization=False,  # divide each input by its std\n                             zca_whitening=False,  # apply ZCA whitening\n                             rotation_range=10,  # randomly rotate images in the range (degrees, 0 to 180)\n                             zoom_range = 0.1, # Randomly zoom image \n                             width_shift_range=0.1,  # randomly shift images horizontally (fraction of total width)\n                             height_shift_range=0.1,  # randomly shift images vertically (fraction of total height)\n                             horizontal_flip=False,  # randomly flip images\n                             vertical_flip=False)  # randomly flip images","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learning_rate_reduction = ReduceLROnPlateau(monitor='val_acc', \n                                            patience=3, \n                                            verbose=1, \n                                            factor=0.5, \n                                            min_lr=0.00001)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"epochs = 10\nbatch_size = 86","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model.fit_generator(datagen.flow(X_train, y_train, batch_size = batch_size),\n                              epochs = epochs, \n                              validation_data = (X_valid, y_valid),\n                              verbose = 2, \n                              steps_per_epoch = X_train.shape[0] // batch_size, \n                              callbacks = [learning_rate_reduction])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Plot the loss and accuracy curves for training and validation \n\nfig, ax = plt.subplots(1, 2, figsize=(12, 4))\nax[0].plot(history.history['loss'], color='b', label=\"Training loss\")\nax[0].plot(history.history['val_loss'], color='r', label=\"validation loss\",axes =ax[0])\nlegend = ax[0].legend(loc='best', shadow=True)\n\n\nax[1].plot(history.history['accuracy'], color='b', label=\"Training accuracy\")\nax[1].plot(history.history['val_accuracy'], color='r',label=\"Validation accuracy\")\nlegend = ax[1].legend(loc='best', shadow=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(model.summary())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"id = test['id']\ntest_data = test.drop('id', axis=1)\ntest_data = test_data.to_numpy().reshape(-1, 28, 28, 1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"results = model.predict(test_data)\nresults = np.argmax(results,axis = 1) # select the index with the maximum probability","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sim = pd.read_csv('/kaggle/input/Kannada-MNIST/sample_submission.csv')\nprint(sim.head())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"id = np.arange(0, results.shape[0])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"save = pd.DataFrame({'id':id,\n                     'label':results})\nprint(save.head())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"save.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":1}