{"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 \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":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport seaborn as sns\n\nimport tensorflow as tf\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix\nfrom tensorflow.keras.callbacks import ReduceLROnPlateau\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense,Conv2D,Flatten,MaxPool2D,Dropout,BatchNormalization,AveragePooling2D,BatchNormalization\nfrom sklearn.utils import shuffle\nfrom tensorflow.keras.optimizers import Adam\nimport random","execution_count":null,"outputs":[]},{"metadata":{"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')\nvalidation=pd.read_csv('/kaggle/input/Kannada-MNIST/Dig-MNIST.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def prepare_data(features,target=None):\n    '''\n        here is a helper function to resize training data to (28,28,1)\n        and to categorize the target variable\n    '''\n    #shuffle data first \n    features,target = shuffle(features,target)\n    x = features.values.reshape((len(features),28,28,1))\n    y = to_categorical(target)\n    print(y.shape)\n    # normalize\n    x = x/255.0\n    return (x,y)\n   \n    ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X,y = train.loc[:,train.columns!='label'],train.label\nX_val,y_val = validation.loc[:,validation.columns!='label'],validation.label","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"We have {} training examples and {} validation examples.\".format(X.shape[0],X_val.shape[0]))\nprint(\"X_train: {} | y_train: {} |\\nX_val: {} | y_val: {}\".format(X.shape,y.shape,X_val.shape,y_val.shape))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_train,y_train = prepare_data(X,y)\nx_val,y_val = prepare_data(X_val,y_val)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"X_train: {} | y_train: {} |\\nX_val: {} | y_val: {}\".format(x_train.shape,y_train.shape,x_val.shape,y_val.shape))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = Sequential()\n\n# LeNet\n# Input Image Dimensionns : 28x28x1\n\n# 1. Conv2D - kernel : 11x11x96. strides=4,4;padding-valid\nmodel.add(Conv2D(filters = 6, kernel_size = (5,5),strides=(1, 1),padding = 'valid', \n                 activation ='relu', input_shape = (28,28,1)))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.5))\n\n# 2. Average Pool  -  kernel - 2x2, strides = 2,2\nmodel.add(MaxPool2D(pool_size=(2, 2), strides=(2,2), padding='valid'))\n\n# 3. Conv2d  -  kernel - 5x5x16, strides = 1,1\nmodel.add(Conv2D(filters=16,kernel_size=(5,5),strides=(1,1),padding='valid',activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.5))\n\n# 4. Average Pool  -  kernel - 2x2, strides = 2,2\nmodel.add(MaxPool2D(pool_size=(2, 2), strides=(2,2), padding='valid'))\n\n# # 5. Convolution - kernel - 5x5x120 ,strides = 1,1\n# model.add(Conv2D(filters=120,kernel_size=(4,4),strides=(1,1),padding='valid',activation='relu'))\n# model.add(BatchNormalization())\n\nmodel.add(Flatten())\n# 6. Fully connected layer - 84 nodes\nmodel.add(Dense(84,activation='relu'))\nmodel.add(BatchNormalization())\n\n# 7. Output layer - 10 nodes\nmodel.add(Dense(10,activation='softmax'))\n\n# Compile \noptimizer=Adam(learning_rate=0.001,beta_1=0.9,beta_2=0.999)\nmodel.compile(optimizer=optimizer,loss=['categorical_crossentropy'],metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Train"},{"metadata":{"trusted":true},"cell_type":"code","source":"#model.fit(x_train,y_train,epochs=10,validation_data=(x_val,y_val))\nh  = model.fit(x_val,y_val,epochs=10,validation_data=(x_train,y_train),batch_size=64)\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test = pd.read_csv('/kaggle/input/Kannada-MNIST/test.csv')\ntest_features = test.iloc[0:,test.columns!='id']\ntest_features = test_features.values.reshape((len(test_features),28,28,1))\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_features = test_features.astype('float')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_features = test_features/255.0","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predictions = model.predict(test_features)\npredictions = np.argmax(predictions,axis=1)\npredictions.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"final_df = pd.DataFrame({'id':test['id'],'label':predictions})\nfinal_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"final_df.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}