{"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\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 read-only \"../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# You can write up to 5GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"# Loading Necessary Packages\n\nfrom matplotlib.pyplot import imshow,plot\nfrom matplotlib import pyplot as plt\nimport seaborn as sns\nsns.set(rc={'figure.figsize':(11.7,5.27)})\nimport keras\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Activation, Dropout, BatchNormalization","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Loading Test/train/validation Data\n\ndf_train_raw = pd.read_csv(os.path.join('/kaggle/input/Kannada-MNIST/train.csv'))\ndf_valid_raw = pd.read_csv(os.path.join('/kaggle/input/Kannada-MNIST/Dig-MNIST.csv'))\ndf_test_raw = pd.read_csv(os.path.join('/kaggle/input/Kannada-MNIST/test.csv'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Merging Train & Validation Set\n\ndf_train_raw=pd.concat([df_train_raw,df_valid_raw])\ndf_train_raw.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"imshow(df_train_raw.iloc[255,1:].values.reshape(28,28),cmap='gray')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Splitting Dependent and Independent Variables\n\ndf_train_x=df_train_raw.iloc[:,1:]\ndf_train_y=df_train_raw.iloc[:,0]\nprint(df_train_x.shape)\nprint(df_train_y.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"image_x=28\nimage_y=28","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Resizing Numpy array to Proper shape \n\nx=np.array(df_train_x).reshape(df_train_x.shape[0],image_x,image_y,1)\nx.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#scaling the Images\n\nx = x.astype('float32')\nx/=255.0","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#converting  Target  classes to one hot encoding format\n\nfrom keras.utils import to_categorical\ndf_train_y=to_categorical(df_train_y)\ndf_train_y.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Using ExponentialDecay functionality which will decrease the learning rate exponentially with epocs \n\nfrom keras.optimizers.schedules import ExponentialDecay\ninitial_learning_rate=0.001\ndef exp_decay():\n   lr_schedule = ExponentialDecay(\n        initial_learning_rate,\n        decay_steps=100000,\n        decay_rate=0.96,\n        staircase=True)\n   return lr_schedule","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Function which will help visualize pixels in HUman readable images\n\ndef vis(dataset,samples,label_col,legend=False,cmap='gray_r',cbar=False,transpose=True,prediction=False,dict_name=None):\n    samples=dataset.iloc[samples].reset_index(drop=True) # Picks n random samples from the dataset\n    labels=samples[label_col].values\n    samples.drop(label_col,axis=1,inplace=True)\n    if prediction==True:\n        preds=samples['Prediction'].values\n        samples.drop('Prediction',axis=1,inplace=True)\n    fig, ax = plt.subplots(5,(len(samples)//5)+1,sharey=True,sharex=True)\n    for i in range(len(samples)):\n        pixels=samples.iloc[i].values\n        pixels=pixels.reshape((28,28))\n        if transpose==True:\n            pixels=pixels.transpose()\n        sns.heatmap(pixels,cmap=cmap,cbar=cbar,ax=ax.flatten()[i])\n        ax.flatten()[i].axes.get_xaxis().set_visible(False)\n        ax.flatten()[i].axes.get_yaxis().set_visible(False)\n    plt.tight_layout()\n    plt.show()\n    if legend==True:\n        if dict_name!=None:\n            labels=[dict_name[i] for i in labels]\n        if prediction==True:\n            print('The images represent items with labels {} which were predicted to be {}.'.format(labels,preds))\n        else:\n            print('The images represent items with labels {}.'.format(labels))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"vis(df_train_raw,list(range(0,10)),label_col='label',legend=True)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Using Early stopping functionality for stopping the training where is not much change in validation Loss\n\nfrom keras.callbacks import EarlyStopping\n\ndef early_stopping():\n    return EarlyStopping(monitor=\"val_loss\",patience=10,verbose=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# This will help the network reduce the learning rate as the gradint is  reaching minima \n\nfrom keras.callbacks import ReduceLROnPlateau\n\ndef reduce_lr_platue():\n    return ReduceLROnPlateau(\n        monitor='val_loss', factor=0.1, patience=5, verbose=1,\n    )","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_train_y.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\nseed=7\nnp.random.seed(seed)\nX_train, X_test, y_train, y_test = train_test_split(x, df_train_y, test_size=0.10, random_state=seed, shuffle=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Create custom convnet\n# after multiple architectures this design was giving the best results\n\nfrom keras.layers import Input,maximum\nfrom keras import Model\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D, Dropout, Flatten, Dense,BatchNormalization,AveragePooling2D\nfrom keras.optimizers import Adam,RMSprop\n\ninp_layer = Input(shape=(image_x, image_y, 1))\nconv_1=Conv2D(64, kernel_size=(1, 1), padding='same', activation='relu')(inp_layer)\nmax_1=MaxPooling2D(2,2)(conv_1)\n\nconv_2=Conv2D(64, kernel_size=(2, 2), padding='same', activation='relu')(inp_layer)\nmax_2=MaxPooling2D(2,2)(conv_2)\n\nconv_3=Conv2D(64, kernel_size=(3, 3), padding='same', activation='relu')(inp_layer)\nmax_3=MaxPooling2D(2,2)(conv_3)\n\nmerged = maximum([max_1, max_2, max_3])\nbn=BatchNormalization()(merged)\ndr=Dropout(0.20)(bn)\n\nconv_1=Conv2D(128, kernel_size=(1, 1), padding='same', activation='relu')(dr)\nmax_1=MaxPooling2D(2,2)(conv_1)\n\nconv_2=Conv2D(128, kernel_size=(2, 2), padding='same', activation='relu')(dr)\nmax_2=MaxPooling2D(2,2)(conv_2)\n\nconv_3=Conv2D(128, kernel_size=(3, 3), padding='same', activation='relu')(dr)\nmax_3=MaxPooling2D(2,2)(conv_3)\n\nmerged = maximum([max_1, max_2, max_3])\nbn=BatchNormalization()(merged)\ndr=Dropout(0.20)(bn)\n\nmodel= Model(inp_layer, dr)\n\n# add created model grapg in sequential model\n\nmodel_cnn2 = Sequential()\nmodel_cnn2.add(model)\n\nmodel_cnn2.add(Conv2D(256, kernel_size=3, activation='relu'))\nmodel_cnn2.add(BatchNormalization())\nmodel_cnn2.add(Flatten())\n\nmodel_cnn2.add(Dropout(0.25))\nmodel_cnn2.add(Dense(512,activation='relu'))\nmodel_cnn2.add(BatchNormalization())\nmodel_cnn2.add(Dropout(0.20))\nmodel_cnn2.add(Dense(64,activation='relu'))\nmodel_cnn2.add(BatchNormalization())\nmodel_cnn2.add(Dropout(0.10))\nmodel_cnn2.add(Dense(10,activation='softmax'))\nmodel_cnn2.summary()\noptimizer = RMSprop(lr=0.001)\nmodel_cnn2.compile(loss='categorical_crossentropy',metrics=\"accuracy\"\n                , optimizer=optimizer)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"'''from keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D, Dropout, Flatten, Dense,BatchNormalization,AveragePooling2D\nfrom keras.optimizers import Adam\n\nmodel_cnn1= Sequential()\nmodel_cnn1.add(Conv2D(64, kernel_size=(5, 5),activation='relu',input_shape=(image_x,image_y,1)))\nmodel_cnn1.add(Conv2D(64, kernel_size=(3, 3),padding='same',activation='relu'))\nmodel_cnn1.add(MaxPooling2D(pool_size=(2, 2)))\nmodel_cnn1.add(Dropout(0.20))\nmodel_cnn1.add(Conv2D(128, kernel_size=(5, 5),activation='relu'))\nmodel_cnn1.add(Conv2D(128, kernel_size=(3, 3), padding='same', activation='relu'))\nmodel_cnn1.add(MaxPooling2D(pool_size=(2, 2)))\nmodel_cnn1.add(Flatten())\nmodel_cnn1.add(Dense(128,activation='relu'))\nmodel_cnn1.add(BatchNormalization())\nmodel_cnn1.add(Dropout(0.25))\nmodel_cnn1.add(Dense(32,activation='relu'))\nmodel_cnn1.add(BatchNormalization())\nmodel_cnn1.add(Dropout(0.10))\nmodel_cnn1.add(Dense(10,activation='softmax'))\nmodel_cnn1.summary()\nmodel_cnn1.compile(loss='categorical_crossentropy',metrics=\"accuracy\"\n                , optimizer='rmsprop')'''","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Model Training\nmodel_output_5 = model_cnn2.fit(X_train,y_train,epochs=40,batch_size=128,validation_data=(X_test,y_test),callbacks=[reduce_lr_platue(),early_stopping()])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Plotting Loss and accuracy graph\n\nfig, ax = plt.subplots(1,2)\nax[0].plot(list(range(len(model_output_5.history[\"loss\"]))), model_output_5.history[\"loss\"], 'r--')\nax[0].plot(list(range(len(model_output_5.history[\"loss\"]))),model_output_5.history[\"val_loss\"], 'b-')\nax[0].legend(['test_Loss', 'val_loss'])\nax[0].set_title('Loss')\nax[1].plot(list(range(len(model_output_5.history[\"loss\"]))), model_output_5.history[\"accuracy\"], 'r--')\nax[1].plot(list(range(len(model_output_5.history[\"loss\"]))),model_output_5.history[\"val_accuracy\"], 'b-')\nax[1].legend(['test_accuracy', 'val_accuracy'])\nax[1].set_title('Accuracy')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Validating in validation data set\nx_pred_total=model_cnn2.predict(X_test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Analysing validation set Predictions\n\ny_list=[]\ntrain_results=pd.DataFrame()\nfor i in range(len(x_pred_total)):\n     y_list.append(np.argmax(x_pred_total[i]))\ntrain_results[\"ypred\"] = y_list\ny_list=[]\nfor i in range(len(y_test)):\n     y_list.append(np.argmax(y_test[i]))\ntrain_results[\"yactual\"] = y_list\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"n_match = train_results[train_results[\"ypred\"]!=train_results[\"yactual\"]]\nprint(n_match.shape)\nn_match.groupby(by=\"yactual\").count()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Comparing the Prediction with image\nprint(df_train_raw.iloc[14097,0])\nimshow(df_train_raw.iloc[14097,1:].values.reshape(28,28),cmap='gray')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# converting test set to proper format for prediction\n\ndf_test=df_test_raw.iloc[:,1:] \nx = df_test.astype('float32') \ntest=np.array(x).reshape(x.shape[0],image_x,image_y,1) \ntest/=255.0","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Predicting on test_set\ny_pred=model_cnn2.predict(test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Saving the results for submission\n\ny_list=[]\nfor i in range(len(y_pred)):\n     y_list.append(np.argmax(y_pred[i]))\nresult=df_test_raw[[\"id\"]]\nresult[\"label\"] = y_list\nresult.to_csv(\"submission.csv\",index=False)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"result","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":4}