{"cells":[{"metadata":{},"cell_type":"markdown","source":"This notebook was inspired by (https://www.kaggle.com/shaygu/kannada-mnist-simple-cnn). "},{"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\nimport tensorflow as tf\n\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_df=pd.read_csv(\"../input/Kannada-MNIST/train.csv\")\ntest_df=pd.read_csv(\"../input/Kannada-MNIST/test.csv\")\n\nx_train=train_df.drop([\"label\"], axis=1).values.astype('float32')\ny_train=train_df[\"label\"].values.astype(\"int32\")\n\nx_test=test_df.drop([\"id\"],axis=1).values.astype('float32')\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df.columns","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_train=x_train.reshape(x_train.shape[0], 28, 28)/255.0\nx_test=x_test.reshape(x_test.shape[0], 28, 28)/255.0","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from 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.2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(x_train.shape)\nprint(y_train.shape)\nprint(x_val.shape)\nprint(y_val.shape)\nprint(x_test.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_train=x_train.reshape(x_train.shape[0], 28,28,1)\nx_test=x_test.reshape(x_test.shape[0],28,28,1)\nx_val=x_val.reshape(x_val.shape[0],28,28,1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.layers import Conv2D, MaxPooling2D, Input, Dense, Activation, ReLU, Flatten, Dropout, BatchNormalization\nfrom keras.models import Model\n\nX=Input(shape=[28,28,1])\nx=Conv2D(16, (3,3), strides=1, padding=\"same\", name=\"conv1\")(X)\nx=BatchNormalization(momentum=0.1, epsilon=1e-5, gamma_initializer=\"uniform\", name=\"batch1\")(x)\nx=Activation('relu',name='relu1')(x)\nx=Dropout(0.1)(x)\n\nx=Conv2D(32, (3,3), strides=1, padding=\"same\", name=\"conv2\")(x)\nx=BatchNormalization(momentum=0.15, epsilon=1e-5, gamma_initializer=\"uniform\", name=\"batch2\")(x)\nx=Activation('relu',name='relu2')(x)\nx=Dropout(0.15)(x)\nx=MaxPooling2D(pool_size=2, strides=2, padding=\"same\", name=\"max2\")(x)\n\nx=Conv2D(64, (5,5), strides=1, padding =\"same\", name=\"conv3\")(x)\nx=BatchNormalization(momentum=0.17, epsilon=1e-5, gamma_initializer=\"uniform\", name=\"batch3\")(x)\nx=Activation('relu', name=\"relu3\")(x)\nx=MaxPooling2D(pool_size=2, strides=2, padding=\"same\", name=\"max3\")(x)\n\nx=Conv2D(128, (5,5), strides=1, padding=\"same\", name=\"conv4\")(x)\nx=BatchNormalization(momentum=0.15, epsilon=1e-5, gamma_initializer=\"uniform\", name=\"batch4\")(x)\nx=Activation('relu', name=\"relu4\")(x)\nx=Dropout(0.17)(x)\n\nx=Conv2D(64, (3,3), strides=1, padding=\"same\", name=\"conv5\")(x)\nx=BatchNormalization(momentum=0.15, epsilon=1e-5, gamma_initializer=\"uniform\", name=\"batch5\")(x)\nx=Activation('relu', name='relu5')(x)\n#x=MaxPooling2D(pool_size=2, strides=2, padding=\"same\", name=\"max5\")(x)\nx=Dropout(0.2)(x)\n\nx=Conv2D(32, (3,3), strides=1, padding=\"same\", name=\"conv6\")(x)\nx=BatchNormalization(momentum=0.15, epsilon=1e-5, gamma_initializer=\"uniform\", name=\"batch6\" )(x)\nx=Activation('relu', name=\"relu6\")(x)\nx=Dropout(0.05)(x)\n#x=MaxPooling2D(pool_size=2, strides=2, padding=\"same\", name=\"max6\")(x)\n\nx=Flatten()(x)\nx=Dense(50, name=\"Dense1\")(x)\nx=Activation('relu', name='relu7')(x)\nx=Dropout(0.05)(x)\nx=Dense(25, name=\"Dense2\")(x)\nx=Activation('relu', name='relu8')(x)\nx=Dropout(0.03)(x)\nx=Dense(10, name=\"Dense3\")(x)\nx=Activation('softmax')(x)\n\nmodel=Model(inputs=X, outputs=x)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(model.summary())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.preprocessing. image import ImageDataGenerator\nfrom keras.callbacks import ModelCheckpoint\nfrom keras.optimizers import Adam\n\ncheckpoint=ModelCheckpoint('bestweights.hdf5', monitor='val_acc', verbose=1, save_best_only=True, mode=\"max\")\n\nepochs=80\nlr=0.002\noptimizer=Adam(lr=lr, decay=lr/(epochs*1.5))\n\nmodel.compile(optimizer=optimizer, loss=\"sparse_categorical_crossentropy\",metrics=[\"accuracy\"])\n\ndatagenerator=ImageDataGenerator( rotation_range=9, zoom_range=0.25, width_shift_range=0.25, height_shift_range=0.25)\n\ndatagenerator.fit(x_train)\nbatch_size=64\nhistory=model.fit_generator(datagenerator.flow(x_train, y_train, batch_size=batch_size), epochs=epochs, validation_data=(x_val, y_val), verbose=2,steps_per_epoch=x_train.shape[0]//batch_size, callbacks=[checkpoint])\nmodel.load_weights(\"bestweights.hdf5\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"results=model.predict(x_test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"results=np.argmax(results, axis=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"results","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"dg=pd.DataFrame()\ndg['id']=list(test_df.values[0:,0])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"dg['label']=results","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"dg","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"dg.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}