{"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":{},"cell_type":"markdown","source":"**Read all Data**"},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"train = pd.read_csv('/kaggle/input/Kannada-MNIST/train.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test = pd.read_csv('/kaggle/input/Kannada-MNIST/test.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_sub = pd.read_csv('/kaggle/input/Kannada-MNIST/sample_submission.csv')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Split to Train set and Test set**"},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\nX, y = train.drop(columns='label'), train.label\nX_train,X_val,y_train,y_val = train_test_split(X, y, test_size=0.2, random_state=42)\nX_train.shape, y_train.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D, Flatten\nfrom keras.layers import Activation, Dense, Dropout\nfrom keras.utils import to_categorical, model_to_dot, plot_model\nfrom keras.datasets import mnist\nimport numpy as np\nimport pandas as pd\nfrom IPython.display import SVG\nnp.random.seed(42)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Visualize some Digit**"},{"metadata":{"trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport matplotlib\nsome_digit = np.array(X_train.iloc[44,:])\nsome_digit_image = some_digit.reshape(28,28)\nplt.imshow(some_digit_image, cmap = matplotlib.cm.binary, interpolation = 'nearest')\nplt.axis('off')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"num_labels = len(np.unique(y_train))\nnum_labels","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Convert to one hot vector**\n"},{"metadata":{"trusted":true},"cell_type":"code","source":"y_train = to_categorical(y_train)\ny_val = to_categorical(y_val)\ny_train.shape, y_val.shape","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Calculate Image size**"},{"metadata":{"trusted":true},"cell_type":"code","source":"import math\nimage_size = int(math.sqrt(X_train.shape[1]))\nimage_size","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train = np.array(X_train)\nX_val = np.array(X_val)\nX_test = np.array(test.drop(columns='id'))\nX_train.shape","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Resize and Normalize**"},{"metadata":{"trusted":true},"cell_type":"code","source":"# Resize\nX_train = np.reshape(X_train, [-1, image_size, image_size, 1])\nX_val = np.reshape(X_val, [-1, image_size, image_size, 1])\nX_test = np.reshape(X_test, [-1, image_size, image_size, 1])\n# Normalize\nX_train = X_train.astype('float32') / 255\nX_val = X_val.astype('float32') / 255\nX_test = X_test.astype('float32')/255\nX_train.shape, X_val.shape","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**CNN parameter**"},{"metadata":{"trusted":true},"cell_type":"code","source":"input_shape = (image_size, image_size, 1)\nbatch_size = 128\nkernel_size = 3 \npool_size = 2\nfilters = 64\ndropout = 0.2","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Model stack of CNN => ReLU => Maxpooling**"},{"metadata":{"trusted":true},"cell_type":"code","source":"Model = Sequential()\nModel.add(Conv2D(filters = filters, kernel_size = kernel_size,\n                activation ='relu', input_shape = input_shape))\nModel.add(MaxPooling2D(pool_size))\nModel.add(Conv2D(filters = filters, kernel_size = kernel_size,\n                activation = 'relu'))\nModel.add(MaxPooling2D(pool_size))\nModel.add(Conv2D(filters = filters, kernel_size = kernel_size,\n                activation = 'relu'))\nModel.add(Flatten())\n# Dropout added as regularizer\nModel.add(Dropout(dropout))\n# Output layer is 10-dim one hot vector\nModel.add(Dense(num_labels))\nModel.add(Activation('softmax'))\nModel.summary()\n# loss function for one-hot vector # use of adam optimizer\n# accuracy is good metric for classification tasks \nModel.compile(loss='categorical_crossentropy', \n              optimizer='adam', \n              metrics=['accuracy'])\nModel.fit(X_train, y_train, epochs=40, batch_size=batch_size)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Evaluate Model**"},{"metadata":{"trusted":true},"cell_type":"code","source":"_, acc = Model.evaluate(X_val,\n                        y_val,\n                        batch_size=batch_size,\n                        verbose=0)\nprint(\"\\nTest accuracy: %.1f%%\" % (100.0 * acc))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Predict**"},{"metadata":{"trusted":true},"cell_type":"code","source":"result = Model.predict(X_test)\nresult.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"result = np.argmax(result,axis=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_sub['label'] = result","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_sub.to_csv('submission.csv', index = False)","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}