{"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_minor":4,"nbformat":4,"cells":[{"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 20GB 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","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-12-08T03:33:10.257686Z","iopub.execute_input":"2022-12-08T03:33:10.258145Z","iopub.status.idle":"2022-12-08T03:33:10.275828Z","shell.execute_reply.started":"2022-12-08T03:33:10.258105Z","shell.execute_reply":"2022-12-08T03:33:10.274588Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# DATA EXPLORATION\n\nlibraries used are numpy, pandas, matplotlib, seaborn(more expressive way of graphs).\n\nFirst we read the dataset(different functions are available depending on the data) suppose we cqa take read_csv()\n\nAs the name suggests we have to explore the given data. use funtions like describe() to know the data in that dataframe. sorting of the attributes is essential. we then have to find the null values and the duplicate values if present can also plot the data for better representation , group the values and can also split them according to our convinience.","metadata":{}},{"cell_type":"code","source":"import numpy as np \nimport pandas as pd \nimport matplotlib.pyplot as plt \nimport seaborn as sns \n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix\nfrom keras.utils.np_utils import to_categorical\n\nimport tensorflow as tf\nfrom tensorflow.keras import Sequential\nfrom tensorflow.keras.layers import Conv2D, Dropout, Dense, Flatten, BatchNormalization, MaxPooling2D,LeakyReLU\nfrom tensorflow.keras.optimizers import RMSprop,Adam,Adadelta\n# from tensorflow.keras.preprocessing.image import ImageDataGenerator\n# from tensorflow.keras.callbacks import ReduceLROnPlateau, EarlyStopping\nfrom tensorflow.keras.utils import to_categorical\n# from tensorflow.keras.regularizers import l2\n\nimport warnings\nwarnings.filterwarnings('ignore')","metadata":{"execution":{"iopub.status.busy":"2022-12-08T03:33:10.277536Z","iopub.execute_input":"2022-12-08T03:33:10.278719Z","iopub.status.idle":"2022-12-08T03:33:10.287483Z","shell.execute_reply.started":"2022-12-08T03:33:10.278618Z","shell.execute_reply":"2022-12-08T03:33:10.285794Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport cv2\n\ndf=pd.read_csv('../input/Kannada-MNIST/train.csv')\nprint(df)\ndf.describe()","metadata":{"execution":{"iopub.status.busy":"2022-12-08T03:33:10.288973Z","iopub.execute_input":"2022-12-08T03:33:10.290078Z","iopub.status.idle":"2022-12-08T03:33:14.792731Z","shell.execute_reply.started":"2022-12-08T03:33:10.289974Z","shell.execute_reply":"2022-12-08T03:33:14.791094Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Checking the input image\n\nthe input is given in pixel values format, we have to convert it into an image.\n\nwe take the csv input convert it into a numpy array and the reshape it into a two dimentional array (img are 2d arrays).and then use opencv or matplotlib to plot the array into an image.(and also save it if we like to)","metadata":{}},{"cell_type":"code","source":"df0=df.iloc[:1,1:]\nprint(type(df0))\nimg = np.reshape(np.asarray(df0), (28, 28))\ncv2.imwrite('image0.png',img)\nplt.imshow(img)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-12-08T03:33:14.795280Z","iopub.execute_input":"2022-12-08T03:33:14.795707Z","iopub.status.idle":"2022-12-08T03:33:14.936468Z","shell.execute_reply.started":"2022-12-08T03:33:14.795671Z","shell.execute_reply":"2022-12-08T03:33:14.934930Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x=df[\"label\"].value_counts()\nprint(x)","metadata":{"execution":{"iopub.status.busy":"2022-12-08T03:33:14.940421Z","iopub.execute_input":"2022-12-08T03:33:14.940881Z","iopub.status.idle":"2022-12-08T03:33:14.953037Z","shell.execute_reply.started":"2022-12-08T03:33:14.940844Z","shell.execute_reply":"2022-12-08T03:33:14.950950Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.value_counts('pixel776')","metadata":{"execution":{"iopub.status.busy":"2022-12-08T03:33:14.957655Z","iopub.execute_input":"2022-12-08T03:33:14.958072Z","iopub.status.idle":"2022-12-08T03:33:14.975205Z","shell.execute_reply.started":"2022-12-08T03:33:14.958040Z","shell.execute_reply":"2022-12-08T03:33:14.974191Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Finding sum of NULL data\n","metadata":{}},{"cell_type":"code","source":"df.isnull().sum()","metadata":{"execution":{"iopub.status.busy":"2022-12-08T03:33:14.976736Z","iopub.execute_input":"2022-12-08T03:33:14.977335Z","iopub.status.idle":"2022-12-08T03:33:15.022362Z","shell.execute_reply.started":"2022-12-08T03:33:14.977301Z","shell.execute_reply":"2022-12-08T03:33:15.021227Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Finding sum of duplicated data","metadata":{}},{"cell_type":"code","source":"df.duplicated().sum()","metadata":{"execution":{"iopub.status.busy":"2022-12-08T03:33:15.023321Z","iopub.execute_input":"2022-12-08T03:33:15.023679Z","iopub.status.idle":"2022-12-08T03:33:15.790169Z","shell.execute_reply.started":"2022-12-08T03:33:15.023649Z","shell.execute_reply":"2022-12-08T03:33:15.788824Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.shape","metadata":{"execution":{"iopub.status.busy":"2022-12-08T03:33:15.792107Z","iopub.execute_input":"2022-12-08T03:33:15.792459Z","iopub.status.idle":"2022-12-08T03:33:15.799821Z","shell.execute_reply.started":"2022-12-08T03:33:15.792425Z","shell.execute_reply":"2022-12-08T03:33:15.798668Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Class distibution\nusing seaborn instead of matplotlib","metadata":{}},{"cell_type":"code","source":"# df0=df.iloc[:1,:]\nimport seaborn as sns\n# print(df0)\nsns.barplot(x.index,x)","metadata":{"execution":{"iopub.status.busy":"2022-12-08T03:33:15.804025Z","iopub.execute_input":"2022-12-08T03:33:15.804407Z","iopub.status.idle":"2022-12-08T03:33:15.996851Z","shell.execute_reply.started":"2022-12-08T03:33:15.804371Z","shell.execute_reply":"2022-12-08T03:33:15.995495Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Data preprocessing\n**Datasets**\n\ntraining sets- the dataset from which we use to fit the model.other terms model learns from this data.\n\nvalidation sets- a small part of data used to improve the quality of the model in simple terms,like it improves the hyperparameters.model wont learn fromt his dataset.(also called dev set , development set)\n\ntraining set- a fraction of data compared to training set. it is used to know how the model is performing.(test the fit of the model),is unbiased.\n\n**Data preparation**\n\ndeclaring training and testing variables.....and can also normalise them","metadata":{}},{"cell_type":"code","source":"raw_train=pd.read_csv('../input/Kannada-MNIST/train.csv')\n# raw_test=pd.read_csv('../input/Kannada-MNIST/test.csv')","metadata":{"execution":{"iopub.status.busy":"2022-12-08T03:33:15.998067Z","iopub.execute_input":"2022-12-08T03:33:15.998405Z","iopub.status.idle":"2022-12-08T03:33:18.353323Z","shell.execute_reply.started":"2022-12-08T03:33:15.998378Z","shell.execute_reply":"2022-12-08T03:33:18.352253Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x=raw_train.iloc[:,1:]/255\ny=raw_train.iloc[:,0]","metadata":{"execution":{"iopub.status.busy":"2022-12-08T03:33:18.354665Z","iopub.execute_input":"2022-12-08T03:33:18.354929Z","iopub.status.idle":"2022-12-08T03:33:18.421916Z","shell.execute_reply.started":"2022-12-08T03:33:18.354905Z","shell.execute_reply":"2022-12-08T03:33:18.421142Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_train,x_val,y_train,y_val=train_test_split(x,y,test_size=0.3,random_state=42)","metadata":{"execution":{"iopub.status.busy":"2022-12-08T03:33:18.423696Z","iopub.execute_input":"2022-12-08T03:33:18.424072Z","iopub.status.idle":"2022-12-08T03:33:18.788378Z","shell.execute_reply.started":"2022-12-08T03:33:18.424040Z","shell.execute_reply":"2022-12-08T03:33:18.787078Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_train.shape","metadata":{"execution":{"iopub.status.busy":"2022-12-08T03:33:18.790117Z","iopub.execute_input":"2022-12-08T03:33:18.790758Z","iopub.status.idle":"2022-12-08T03:33:18.798123Z","shell.execute_reply.started":"2022-12-08T03:33:18.790724Z","shell.execute_reply":"2022-12-08T03:33:18.796316Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Reshape the data\nthe data given here is in the form of (42000,784) but the image size to be taken is 28x28","metadata":{}},{"cell_type":"code","source":"x_train=x_train.values.reshape(-1,28,28,1)\nx_val=x_val.values.reshape(-1,28,28,1)\ny_train=to_categorical(y_train)#the labels will be in the same fromat as the reshaped x_train \ny_val=to_categorical(y_val)","metadata":{"execution":{"iopub.status.busy":"2022-12-08T03:33:18.800672Z","iopub.execute_input":"2022-12-08T03:33:18.801244Z","iopub.status.idle":"2022-12-08T03:33:18.813325Z","shell.execute_reply.started":"2022-12-08T03:33:18.801200Z","shell.execute_reply":"2022-12-08T03:33:18.811609Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model=tf.keras.models.Sequential([\n    tf.keras.layers.Conv2D(filters=32,kernel_size=(5,5),padding='same',activation='relu',input_shape=(28,28,1)),\n    tf.keras.layers.Conv2D(filters=32,kernel_size=(5,5),padding='same',activation='relu',input_shape=(28,28,1)),\n    tf.keras.layers.BatchNormalization(momentum=.15),\n    tf.keras.layers.MaxPool2D(pool_size=(2,2)),\n    tf.keras.layers.Dropout(0.25),\n    tf.keras.layers.Conv2D(filters=64,kernel_size=(5,5),padding='same',activation='relu',input_shape=(28,28,1)),\n    tf.keras.layers.Conv2D(filters=64,kernel_size=(5,5),padding='same',activation='relu',input_shape=(28,28,1)),\n    tf.keras.layers.BatchNormalization(momentum=.15),\n    tf.keras.layers.MaxPool2D(pool_size=(2,2),strides=(2,2)),\n    tf.keras.layers.Dropout(0.25),\n    tf.keras.layers.Conv2D(filters=32,kernel_size=(5,5),padding='same',activation='relu',input_shape=(28,28,1)),\n    tf.keras.layers.Conv2D(filters=32,kernel_size=(5,5),padding='same',activation='relu',input_shape=(28,28,1)),\n    tf.keras.layers.BatchNormalization(momentum=.15),\n    tf.keras.layers.MaxPool2D(pool_size=(2,2)),\n    tf.keras.layers.Dropout(0.25),\n    tf.keras.layers.Flatten(),\n    tf.keras.layers.Dense(256,activation=\"relu\"),\n    tf.keras.layers.Dropout(0.4),\n    tf.keras.layers.Dense(10,activation=\"softmax\") \n    \n])\n","metadata":{"execution":{"iopub.status.busy":"2022-12-08T03:33:18.816784Z","iopub.execute_input":"2022-12-08T03:33:18.817267Z","iopub.status.idle":"2022-12-08T03:33:18.959198Z","shell.execute_reply.started":"2022-12-08T03:33:18.817231Z","shell.execute_reply":"2022-12-08T03:33:18.957098Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"execution":{"iopub.status.busy":"2022-12-08T03:33:18.961232Z","iopub.execute_input":"2022-12-08T03:33:18.961683Z","iopub.status.idle":"2022-12-08T03:33:18.970024Z","shell.execute_reply.started":"2022-12-08T03:33:18.961649Z","shell.execute_reply":"2022-12-08T03:33:18.968919Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"optimizer=Adam(learning_rate=0.001,beta_1=0.9,beta_2=0.999)\nmodel.compile(optimizer=optimizer,loss=['categorical_crossentropy'],metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2022-12-08T03:33:18.971640Z","iopub.execute_input":"2022-12-08T03:33:18.972078Z","iopub.status.idle":"2022-12-08T03:33:18.991677Z","shell.execute_reply.started":"2022-12-08T03:33:18.971998Z","shell.execute_reply":"2022-12-08T03:33:18.990608Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_train.shape","metadata":{"execution":{"iopub.status.busy":"2022-12-08T03:33:18.993030Z","iopub.execute_input":"2022-12-08T03:33:18.994977Z","iopub.status.idle":"2022-12-08T03:33:19.010091Z","shell.execute_reply.started":"2022-12-08T03:33:18.994945Z","shell.execute_reply":"2022-12-08T03:33:19.008733Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"epochs=5\nbatch_size=64\nhistory=model.fit(x_train,y_train,epochs=epochs,validation_data=(x_val,y_val))","metadata":{"execution":{"iopub.status.busy":"2022-12-08T03:33:19.011449Z","iopub.execute_input":"2022-12-08T03:33:19.011932Z","iopub.status.idle":"2022-12-08T03:44:26.488959Z","shell.execute_reply.started":"2022-12-08T03:33:19.011899Z","shell.execute_reply":"2022-12-08T03:44:26.488033Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# print(raw_test)\n# test=raw_test\ntest=pd.read_csv('../input/Kannada-MNIST/test.csv')\ntest1=test.iloc[2:3,1:]\nprint(test1)","metadata":{"execution":{"iopub.status.busy":"2022-12-08T03:44:26.490260Z","iopub.execute_input":"2022-12-08T03:44:26.490588Z","iopub.status.idle":"2022-12-08T03:44:26.792278Z","shell.execute_reply.started":"2022-12-08T03:44:26.490562Z","shell.execute_reply":"2022-12-08T03:44:26.791550Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# test_id=test.id\n\ntest=test.drop(['id'],axis=1)/255\ntest=test.values.reshape(-1,28,28,1)","metadata":{"execution":{"iopub.status.busy":"2022-12-08T03:44:26.793307Z","iopub.execute_input":"2022-12-08T03:44:26.794757Z","iopub.status.idle":"2022-12-08T03:44:26.812007Z","shell.execute_reply.started":"2022-12-08T03:44:26.794701Z","shell.execute_reply":"2022-12-08T03:44:26.810920Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test.shape","metadata":{"execution":{"iopub.status.busy":"2022-12-08T03:44:26.813057Z","iopub.execute_input":"2022-12-08T03:44:26.813666Z","iopub.status.idle":"2022-12-08T03:44:26.821539Z","shell.execute_reply.started":"2022-12-08T03:44:26.813636Z","shell.execute_reply":"2022-12-08T03:44:26.820024Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Prediction\nSave onto a csv file","metadata":{}},{"cell_type":"code","source":"Yp=model.predict(test)\nYp=np.argmax(Yp,axis=1)\nprint(Yp)\nmodel.save('model1.h5')\n# Yp.head()\n# sample_sub['label']=Yp\n# sample_sub.to_csv('submission.csv',index=False)\n# sample_sub.head()\n# np.savetxt('submission.csv',Yp.astype('int32'),delimiter=',')","metadata":{"execution":{"iopub.status.busy":"2022-12-08T03:44:26.822900Z","iopub.execute_input":"2022-12-08T03:44:26.823215Z","iopub.status.idle":"2022-12-08T03:44:30.934854Z","shell.execute_reply.started":"2022-12-08T03:44:26.823164Z","shell.execute_reply":"2022-12-08T03:44:30.933205Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample_sub=pd.read_csv('../input/Kannada-MNIST/sample_submission.csv')\nsample_sub['label']=Yp\nsample_sub.to_csv('submission.csv',index=False)","metadata":{"execution":{"iopub.status.busy":"2022-12-08T03:44:30.936210Z","iopub.execute_input":"2022-12-08T03:44:30.936442Z","iopub.status.idle":"2022-12-08T03:44:30.955580Z","shell.execute_reply.started":"2022-12-08T03:44:30.936418Z","shell.execute_reply":"2022-12-08T03:44:30.954183Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample_sub","metadata":{"execution":{"iopub.status.busy":"2022-12-08T03:44:30.957161Z","iopub.execute_input":"2022-12-08T03:44:30.957411Z","iopub.status.idle":"2022-12-08T03:44:30.969365Z","shell.execute_reply.started":"2022-12-08T03:44:30.957388Z","shell.execute_reply":"2022-12-08T03:44:30.967538Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test.shape","metadata":{"execution":{"iopub.status.busy":"2022-12-08T03:44:30.970947Z","iopub.execute_input":"2022-12-08T03:44:30.971205Z","iopub.status.idle":"2022-12-08T03:44:30.981780Z","shell.execute_reply.started":"2022-12-08T03:44:30.971183Z","shell.execute_reply":"2022-12-08T03:44:30.980566Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#         print(i)\nimg = np.reshape(np.asarray(test1), (28, 28))\n#     cv2.imwrite('image0.png',img)\nplt.imshow(img)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-12-08T03:44:30.987714Z","iopub.execute_input":"2022-12-08T03:44:30.988268Z","iopub.status.idle":"2022-12-08T03:44:31.102322Z","shell.execute_reply.started":"2022-12-08T03:44:30.988233Z","shell.execute_reply":"2022-12-08T03:44:31.101633Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Confusion matrix\n   Gives the performance of the matrix,has two dimensions predictions and actual\n\nit basically shows the wrong prediction and the right prediction, also know as error matrix.","metadata":{}},{"cell_type":"code","source":"plt.figure(figsize=(10,5))\nfor i in range(10):  \n    plt.subplot(2,5, i+1)\n    plt.imshow(test[i].reshape((28,28)),cmap=plt.cm.binary)\n    plt.title(\"predicted=%d\" % Yp[i],y=0.9)\n    plt.axis('off')\nplt.subplots_adjust(wspace=0.3, hspace=-0.1)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-12-08T03:44:31.103240Z","iopub.execute_input":"2022-12-08T03:44:31.103571Z","iopub.status.idle":"2022-12-08T03:44:31.449706Z","shell.execute_reply.started":"2022-12-08T03:44:31.103545Z","shell.execute_reply":"2022-12-08T03:44:31.448354Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"Yp2=model.predict(x_val)\nYp2=np.argmax(Yp2,axis=1)\nYp1=np.argmax(y_val,axis=1)\n# print(test0)\nCmtx=confusion_matrix(Yp1,Yp2)\nCmtx=pd.DataFrame(Cmtx,index=range(0,10),columns=range(0,10))\nCmtx","metadata":{"execution":{"iopub.status.busy":"2022-12-08T03:44:31.451721Z","iopub.execute_input":"2022-12-08T03:44:31.452070Z","iopub.status.idle":"2022-12-08T03:44:45.884641Z","shell.execute_reply.started":"2022-12-08T03:44:31.452037Z","shell.execute_reply":"2022-12-08T03:44:45.883457Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(test.shape)","metadata":{"execution":{"iopub.status.busy":"2022-12-08T03:44:45.887466Z","iopub.execute_input":"2022-12-08T03:44:45.887898Z","iopub.status.idle":"2022-12-08T03:44:45.893730Z","shell.execute_reply.started":"2022-12-08T03:44:45.887859Z","shell.execute_reply":"2022-12-08T03:44:45.892563Z"},"trusted":true},"execution_count":null,"outputs":[]}]}