{"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 pandas as pd\ndata = pd.read_csv('../input/Kannada-MNIST/train.csv')\ndata.append(pd.read_csv('../input/Kannada-MNIST/Dig-MNIST.csv'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data.hist(column='label')","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\n\nimage = data.drop('label', axis=1)\nimage = image.iloc[0].values.reshape(28,28)\nplt.subplot(131)\nplt.title(data.iloc[0]['label'])\nplt.imshow(image)\n\nimage = data.drop('label', axis=1)\nimage = image.iloc[1].values.reshape(28,28)\nplt.subplot(132)\nplt.title(data.iloc[1]['label'])\nplt.imshow(image)\n\nimage = data.drop('label', axis=1)\nimage = image.iloc[2].values.reshape(28,28)\nplt.subplot(133)\nplt.title(data.iloc[2]['label'])\nplt.imshow(image)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(data.drop('label', axis=1), data['label'], test_size=0.33)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_test","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_train","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_test","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train = X_train.values.reshape(len(X_train), 28,28,1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_test = X_test.values.reshape(len(X_test), 28,28,1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_train = pd.get_dummies(y_train)\ny_train","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_test = pd.get_dummies(y_test)\ny_test","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow import keras\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Flatten, Convolution1D, Dropout, MaxPooling2D, Input, Activation\nfrom keras.models import Model\nfrom keras.optimizers import SGD\nfrom tensorflow.keras.layers import Dense, Flatten, Conv2D\n\nimg_rows = 28\nimg_cols = 28\nnum_classes = 10\n\nmodel = Sequential()\nmodel.add(Conv2D(12, kernel_size=3, activation=\"relu\", input_shape=(img_rows,img_cols,1)))\nmodel.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))\nmodel.add(Conv2D(20, activation='relu', kernel_size=3, strides=2))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Conv2D(20, activation='relu', kernel_size=3))\nmodel.add(Flatten())\nmodel.add(Dense(100, activation='relu'))\nmodel.add(Dense(num_classes, activation='softmax'))\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(optimizer=\"adam\", loss='categorical_crossentropy', metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"callbacks_list = [keras.callbacks.EarlyStopping(monitor='val_acc', patience=10)]\nhistory = model.fit(X_train, y_train, batch_size=32, epochs = 100, validation_data=(X_test, y_test), callbacks = callbacks_list, verbose=1, shuffle=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.plot(history.history['acc'])\nplt.plot(history.history['val_acc'])\nplt.title('model accuracy')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.legend(['train', 'val'], loc='upper left')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('model loss')\nplt.ylabel('loss')\nplt.xlabel('epoch')\n\nplt.legend(['train', 'val'], loc='upper left')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(model.metrics_names)\nmodel.evaluate(X_test, y_test, verbose=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_pred = pd.DataFrame(model.predict_classes(X_test, verbose=1))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_pred","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.metrics import confusion_matrix\ncm = confusion_matrix((y_test.iloc[:, 1:] == 1).idxmax(1), y_pred)\nprint(cm)\nfig = plt.figure()\nax = fig.add_subplot(111)\ncax = ax.matshow(cm)\nplt.title('Confusion matrix of the classifier')\nfig.colorbar(cax)\n#ax.set_xticklabels([''] + labels)\n#ax.set_yticklabels([''] + labels)\nplt.xlabel('Predicted')\nplt.ylabel('True')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data = pd.read_csv('../input/Kannada-MNIST/test.csv')\ndata","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pred_y = model.predict_classes(data.drop('id', axis=1).values.reshape(len(data),28,28,1), verbose=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pred_y = pd.DataFrame(pred_y, columns=['label'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pred_y['id'] = data['id']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pred_y.to_csv('submission.csv', index=False, columns=['id', 'label'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#file = open('submission.csv', 'r') \n#print(file.read())","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}