{"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 tensorflow as tf\nfrom tensorflow import keras\nimport matplotlib.pyplot as plt\nprint(tf.__version__)\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":"train=pd.read_csv(\"/kaggle/input/Kannada-MNIST/train.csv\")\ntest=pd.read_csv(\"/kaggle/input/Kannada-MNIST/test.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ids=test.id\ntest=test.drop([\"id\"],axis=1)\ntrain_result=train.label\ntrain=train.drop([\"label\"],axis=1)\ntest=test.iloc[:,:].values\ntest=test.reshape(-1,28,28,1)\ny=train_result.iloc[:].values\nx=train.iloc[:,:].values\nx=x.reshape(-1,28,28,1)\nx, test= x/255.0,test/255.0","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator\n#Considering to do data augumentation\ndatagen = ImageDataGenerator(\n        rotation_range=10,  \n        zoom_range = 0.25,  \n        width_shift_range=0.25, \n        height_shift_range=0.25)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#The whole \"building\" of neuronetwork\nSequential=keras.Sequential\n#Now we choose \"who will be moved into\" each layer\n#possible Candidates are:\n#Use different filters to get different channels.\nConv2D=keras.layers.Conv2D\n#Pooling, select Maximum value from a certain pool.\nMaxPool2D=keras.layers.MaxPool2D\n#a flat ANN layer\nDense=keras.layers.Dense\n#as it suggests, flatten: \\mathbb{R}^2 \\to \\mathbb{R}\nFlatten=keras.layers.Flatten\n#Randomly select a chosen percentage of neurons and remove them temporarily\nDropout=keras.layers.Dropout\n#BarchNormalization, \"Centralize\" the batch.(randomly chose a noise on sigma is available)\nBatchNormalization=keras.layers.BatchNormalization","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def generate_model():\n\n    model=Sequential()\n    model.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'same', \n                 activation ='relu', input_shape = (28,28,1)))\n    model.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'same', \n                 activation ='relu', input_shape = (28,28,1)))\n    model.add(BatchNormalization())\n    model.add(MaxPool2D(pool_size=(2,2),strides=(2,2)))\n    model.add(Dropout(0.3))\n    model.add(Conv2D(filters = 128, kernel_size = (3,3),padding = 'same', \n                 activation ='relu'))\n    model.add(Conv2D(filters = 128, kernel_size = (3,3),padding = 'same', \n                 activation ='relu'))\n    model.add(Conv2D(filters = 128, 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.3))\n    model.add(Flatten())\n    model.add(Dense(256, activation = \"relu\"))\n    model.add(Dropout(0.3))\n    model.add(Dense(10, activation = \"softmax\"))\n    model.compile(keras.optimizers.Adam(0.0001), \n             loss=\"sparse_categorical_crossentropy\",\n              metrics=[\"accuracy\"]\n             )\n    \n    return model","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(x,y,test_size=0.2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#See how many epochs should be reasonable\nmodel=generate_model()\n# Fit the model\nhistory = model.fit_generator(datagen.flow(x_train,y_train, batch_size=40),\n                              epochs = 45, \n                              validation_data=(x_test,y_test),\n                              validation_steps=int(x_test.shape[0]/40),\n                              verbose = 1, steps_per_epoch=x_train.shape[0] / 40)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Plot training & validation accuracy values\nplt.plot(history.history['acc'])\nplt.plot(history.history['val_acc'])\nplt.title('Model accuracy')\nplt.ylabel('Accuracy')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Test'], 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', 'Test'], loc='upper left')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predictions=model.predict_classes(test)\noutput=pd.DataFrame({\"id\":ids, \"label\":predictions})\noutput.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}