{"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)\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport tensorflow as tf\nfrom tensorflow.keras import Sequential\nfrom tensorflow.keras.layers import Conv2D, Dropout, Dense, Flatten, BatchNormalization, MaxPooling2D,LeakyReLU\n#from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D\nfrom tensorflow.keras.optimizers import RMSprop,Nadam,Adadelta\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.callbacks import ReduceLROnPlateau, EarlyStopping\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras.regularizers import l2\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\nimport seaborn as sns\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":"tf.test.gpu_device_name()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train = pd.read_csv('../input/Kannada-MNIST/train.csv')\ntest = pd.read_csv('../input/Kannada-MNIST/test.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(train)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_train=train[\"label\"]\nx_train= train.drop(labels=[\"label\"],axis=1)\ng = sns.countplot(y_train)\n\ny_train.value_counts()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_train.isnull().any().describe()\ntest.isnull().any().describe()\ntest= test.drop(labels=[\"id\"],axis=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"num=6\nnumber = train.iloc[num,1:].values.reshape(28,28)\nprint(\"Picture of \"+ str(num) + \"in Kannada style\")\nplt.imshow(number, cmap=plt.get_cmap('gray'))\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_train = x_train / 255.0\ntest = test / 255.0\nx_train = x_train.values.reshape(-1,28,28,1)\ntest = test.values.reshape(-1,28,28,1)\ng = plt.imshow(x_train[0][:,:,0])\ny_train = to_categorical(y_train, num_classes = 10)\nrandom_seed = 2\n\nfrom sklearn.model_selection import train_test_split\nx_train, x_val, y_train, y_val = train_test_split(x_train, y_train, test_size = 0.1, random_state=random_seed)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Modeling"},{"metadata":{"trusted":true},"cell_type":"code","source":"model = Sequential()\n\nmodel.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same', \n                 activation ='relu', input_shape = (28,28,1)))\nmodel.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same', \n                 activation ='relu'))\nmodel.add(tf.keras.layers.MaxPooling2D(pool_size=(2,2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same', \n                 activation ='relu'))\nmodel.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same', \n                 activation ='relu'))#  \nmodel.add(tf.keras.layers.MaxPooling2D(pool_size=(2,2), strides=(2,2)))\nmodel.add(Dropout(0.25))\n\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":{"trusted":true},"cell_type":"code","source":"optimizer = RMSprop(lr=0.001, rho=0.9, epsilon=1e-08, decay=0.0)\nmodel.compile(optimizer = optimizer , loss = \"categorical_crossentropy\", metrics=[\"accuracy\"])\nlearning_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 = 5\nbatch_size = 86","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"datagen = ImageDataGenerator(rotation_range=15,\n                             width_shift_range = 0.15,\n                             height_shift_range = 0.15,\n                             shear_range = 0.15,\n                             zoom_range = 0.4,\n                              horizontal_flip = False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"datagen.fit(x_train)\n","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, validation_data = (x_val,y_val),\n                              verbose = 2, 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":"tf.keras.utils.plot_model(model, to_file=\"model.png\", show_shapes=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.plot(history.history['accuracy'])\nplt.plot(history.history['val_accuracy'])\nplt.title('Model accuracy')\nplt.ylabel('Accuracy')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Validation'], loc='upper left')\nplt.show()\n\n# Plot training & validation loss values\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('Model loss')\nplt.ylabel('Loss')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Validation'], loc='upper left')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.evaluate(x_val, y_val, verbose=2);\n# CM:\ny_predicted = model.predict(x_val)\ny_grand_truth = y_val\ny_predicted = np.argmax(y_predicted,axis=1)\ny_grand_truth = np.argmax(y_grand_truth,axis=1)\nfrom sklearn.metrics import confusion_matrix\ncm = confusion_matrix(y_grand_truth, y_predicted)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"f, ax = plt.subplots(figsize=(10,10))\nsns.heatmap(cm,fmt=\".0f\", annot=True,linewidths=0.1, linecolor=\"purple\", ax=ax)\nplt.xlabel(\"Predicted\")\nplt.ylabel(\"Grand Truth\")\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"F1 Score\n"},{"metadata":{"trusted":true},"cell_type":"code","source":"scores = np.zeros((10,3))\ndef calc_F1(num):\n  TP = cm[num,num]\n  FN = np.sum(cm[num,:])-cm[num,num]\n  FP = np.sum(cm[:,num])-cm[num,num]\n  precision = TP/(TP+FP)\n  recall = TP/(TP+FN)\n  F1_score = 2*(recall * precision) / (recall + precision)\n  return precision, recall, F1_score\nfor i in range(10):\n   precision, recall, F1_score = calc_F1(i)\n   scores[i,:] = precision, recall, F1_score\nscores_frame = pd.DataFrame(scores,columns=[\"Precision\", \"Recall\", \"F1 Score\"], index=[list(range(0, 10))])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"f, ax = plt.subplots(figsize = (4,6))\nax.set_title('Number Scores')\nsns.heatmap(scores_frame, annot=True, fmt=\".3f\", linewidths=0.5, cmap=\"PuBu\", cbar=True, ax=ax)\nbottom, top = ax.get_ylim()\nplt.ylabel(\"\")\nax.set_ylim(bottom + 0.5, top - 0.5)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#fig, ax = plt.subplots(2,1)\n#ax[0].plot(history.history['loss'], color='b', label=\"Training loss\")\n#ax[0].plot(history.history['val_loss'], color='r', label=\"validation loss\",axes =ax[0])\n#legend = ax[0].legend(loc='best', shadow=True)\n\n#ax[1].plot(history.history['acc'], color='b', label=\"Training accuracy\")\n#ax[1].plot(history.history['val_acc'], color='r',label=\"Validation accuracy\")\n#legend = ax[1].legend(loc='best', shadow=True)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Predicting\n"},{"metadata":{"trusted":true},"cell_type":"code","source":"results = model.predict(test)\n\n# select the index with the maximum probability\nresults = np.argmax(results,axis = 1)\n\nresults = pd.Series(results,name=\"Label\")\nsubmission = pd.concat([pd.Series(range(1,28001),name = \"ImageId\"),results],axis = 1)\n\nsubmission.to_csv(\"submission.csv\",index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#sub=model.predict(test)     ##making prediction\n#sub=np.argmax(sub,axis=1) ##changing the prediction intro labels\n\n#sample_sub['label']=sub\n#sample_sub.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}