{"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\n# import numpy as np # linear algebra\n# import 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\n# import os\n# for 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","trusted":true},"execution_count":null,"outputs":[]},{"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')\n","metadata":{"execution":{"iopub.status.busy":"2022-11-10T07:43:07.373358Z","iopub.execute_input":"2022-11-10T07:43:07.373778Z","iopub.status.idle":"2022-11-10T07:43:19.241196Z","shell.execute_reply.started":"2022-11-10T07:43:07.373748Z","shell.execute_reply":"2022-11-10T07:43:19.240079Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# data exploration\n\nlibraries used numpy, pandas, matplotlib, seaborn(more expressive way of graphs)\n\nFIRST we read the dataset(diff functions available depends upon the data) suppose we cqa take read_csv()\n\nas the name suggests we have to explore the given data.\nuse funtions like describe() to know the data in that dataframe.\nsorting of the attributes is essential.\nwe then have to find the null values and the duplicate values if present can also plot the data for better representation ,\ngroup the values and can also split them acc to our convinience ","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()\n","metadata":{"scrolled":true,"execution":{"iopub.status.busy":"2022-11-10T07:43:24.866799Z","iopub.execute_input":"2022-11-10T07:43:24.867550Z","iopub.status.idle":"2022-11-10T07:43:32.145547Z","shell.execute_reply.started":"2022-11-10T07:43:24.867509Z","shell.execute_reply":"2022-11-10T07:43:32.144449Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# checking the input image\n\nas the input are 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":{"scrolled":true,"execution":{"iopub.status.busy":"2022-11-10T07:43:40.809899Z","iopub.execute_input":"2022-11-10T07:43:40.810281Z","iopub.status.idle":"2022-11-10T07:43:41.064809Z","shell.execute_reply.started":"2022-11-10T07:43:40.810249Z","shell.execute_reply":"2022-11-10T07:43:41.063843Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x=df[\"label\"].value_counts()\nprint(x)","metadata":{"execution":{"iopub.status.busy":"2022-11-10T07:43:44.616985Z","iopub.execute_input":"2022-11-10T07:43:44.617789Z","iopub.status.idle":"2022-11-10T07:43:44.628084Z","shell.execute_reply.started":"2022-11-10T07:43:44.617751Z","shell.execute_reply":"2022-11-10T07:43:44.626909Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# summary of a particular column\n   ","metadata":{}},{"cell_type":"code","source":"df.value_counts('pixel776')","metadata":{"execution":{"iopub.status.busy":"2022-11-10T07:43:46.520391Z","iopub.execute_input":"2022-11-10T07:43:46.521492Z","iopub.status.idle":"2022-11-10T07:43:46.532512Z","shell.execute_reply.started":"2022-11-10T07:43:46.521406Z","shell.execute_reply":"2022-11-10T07:43:46.531109Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# finding the null data\n\n","metadata":{}},{"cell_type":"code","source":"df.isnull().sum()","metadata":{"execution":{"iopub.status.busy":"2022-11-10T07:43:48.439399Z","iopub.execute_input":"2022-11-10T07:43:48.440596Z","iopub.status.idle":"2022-11-10T07:43:48.540367Z","shell.execute_reply.started":"2022-11-10T07:43:48.440550Z","shell.execute_reply":"2022-11-10T07:43:48.539039Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# finding duplicate data\n\n\nsum of the duplicate data.","metadata":{}},{"cell_type":"code","source":"df.duplicated().sum()","metadata":{"execution":{"iopub.status.busy":"2022-11-10T07:43:50.621947Z","iopub.execute_input":"2022-11-10T07:43:50.622331Z","iopub.status.idle":"2022-11-10T07:43:51.409643Z","shell.execute_reply.started":"2022-11-10T07:43:50.622298Z","shell.execute_reply":"2022-11-10T07:43:51.408331Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# shape of the dataset\n\n(clmn,row)","metadata":{}},{"cell_type":"code","source":"df.shape","metadata":{"execution":{"iopub.status.busy":"2022-11-10T07:43:53.235103Z","iopub.execute_input":"2022-11-10T07:43:53.235540Z","iopub.status.idle":"2022-11-10T07:43:53.243003Z","shell.execute_reply.started":"2022-11-10T07:43:53.235502Z","shell.execute_reply":"2022-11-10T07:43:53.241798Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# class distibution\n\nusing seaborn instead of matplotlib","metadata":{}},{"cell_type":"markdown","source":"the distribution is homogenous so no need to remove extra data or to add new data.","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-11-10T07:43:55.924763Z","iopub.execute_input":"2022-11-10T07:43:55.925136Z","iopub.status.idle":"2022-11-10T07:43:56.185344Z","shell.execute_reply.started":"2022-11-10T07:43:55.925104Z","shell.execute_reply":"2022-11-10T07:43:56.184319Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# data preprossing\n\n**datasets**\n\ntraining sets-\nthe dataset from which we use to fit the model.other terms model learns from this data.\n\n\nvalidation sets- \na 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\n\ntraining set-\na 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 \n","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-11-10T07:44:00.238851Z","iopub.execute_input":"2022-11-10T07:44:00.239257Z","iopub.status.idle":"2022-11-10T07:44:02.893597Z","shell.execute_reply.started":"2022-11-10T07:44:00.239222Z","shell.execute_reply":"2022-11-10T07:44:02.892452Z"},"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-11-10T07:44:07.254676Z","iopub.execute_input":"2022-11-10T07:44:07.255060Z","iopub.status.idle":"2022-11-10T07:44:07.423555Z","shell.execute_reply.started":"2022-11-10T07:44:07.255028Z","shell.execute_reply":"2022-11-10T07:44:07.422453Z"},"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-11-10T07:44:10.279436Z","iopub.execute_input":"2022-11-10T07:44:10.280038Z","iopub.status.idle":"2022-11-10T07:44:10.646819Z","shell.execute_reply.started":"2022-11-10T07:44:10.279994Z","shell.execute_reply":"2022-11-10T07:44:10.645749Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_train.shape","metadata":{"execution":{"iopub.status.busy":"2022-11-10T07:44:13.873259Z","iopub.execute_input":"2022-11-10T07:44:13.873696Z","iopub.status.idle":"2022-11-10T07:44:13.880523Z","shell.execute_reply.started":"2022-11-10T07:44:13.873649Z","shell.execute_reply":"2022-11-10T07:44:13.879470Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-11-10T07:44:16.600476Z","iopub.execute_input":"2022-11-10T07:44:16.601714Z","iopub.status.idle":"2022-11-10T07:44:16.610033Z","shell.execute_reply.started":"2022-11-10T07:44:16.601665Z","shell.execute_reply":"2022-11-10T07:44:16.608793Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# reshape the data\n\nthe data given here is in the form of (42000,784)\nbut the image size to be taken is 28x28\n","metadata":{}},{"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])","metadata":{"execution":{"iopub.status.busy":"2022-11-10T07:44:19.419837Z","iopub.execute_input":"2022-11-10T07:44:19.420373Z","iopub.status.idle":"2022-11-10T07:44:26.204059Z","shell.execute_reply.started":"2022-11-10T07:44:19.420324Z","shell.execute_reply":"2022-11-10T07:44:26.202914Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"execution":{"iopub.status.busy":"2022-11-10T07:44:40.908571Z","iopub.execute_input":"2022-11-10T07:44:40.908969Z","iopub.status.idle":"2022-11-10T07:44:40.917726Z","shell.execute_reply.started":"2022-11-10T07:44:40.908937Z","shell.execute_reply":"2022-11-10T07:44:40.916551Z"},"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-11-10T07:44:53.081262Z","iopub.execute_input":"2022-11-10T07:44:53.081890Z","iopub.status.idle":"2022-11-10T07:44:53.094685Z","shell.execute_reply.started":"2022-11-10T07:44:53.081853Z","shell.execute_reply":"2022-11-10T07:44:53.093545Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_train.shape","metadata":{"execution":{"iopub.status.busy":"2022-11-10T07:44:55.725615Z","iopub.execute_input":"2022-11-10T07:44:55.726685Z","iopub.status.idle":"2022-11-10T07:44:55.733574Z","shell.execute_reply.started":"2022-11-10T07:44:55.726645Z","shell.execute_reply":"2022-11-10T07:44:55.732199Z"},"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))\n","metadata":{"execution":{"iopub.status.busy":"2022-11-10T07:44:59.280215Z","iopub.execute_input":"2022-11-10T07:44:59.280604Z","iopub.status.idle":"2022-11-10T07:46:22.729656Z","shell.execute_reply.started":"2022-11-10T07:44:59.280572Z","shell.execute_reply":"2022-11-10T07:46:22.728498Z"},"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-11-10T07:51:07.989396Z","iopub.execute_input":"2022-11-10T07:51:07.990134Z","iopub.status.idle":"2022-11-10T07:51:08.381721Z","shell.execute_reply.started":"2022-11-10T07:51:07.990097Z","shell.execute_reply":"2022-11-10T07:51:08.380609Z"},"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-11-10T07:51:48.692172Z","iopub.execute_input":"2022-11-10T07:51:48.692803Z","iopub.status.idle":"2022-11-10T07:51:48.734701Z","shell.execute_reply.started":"2022-11-10T07:51:48.692758Z","shell.execute_reply":"2022-11-10T07:51:48.733367Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test.shape","metadata":{"execution":{"iopub.status.busy":"2022-11-10T07:51:51.250609Z","iopub.execute_input":"2022-11-10T07:51:51.251024Z","iopub.status.idle":"2022-11-10T07:51:51.257860Z","shell.execute_reply.started":"2022-11-10T07:51:51.250978Z","shell.execute_reply":"2022-11-10T07:51:51.256702Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# prediction\n\nwe save it to a submission  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-11-10T07:52:36.079993Z","iopub.execute_input":"2022-11-10T07:52:36.080391Z","iopub.status.idle":"2022-11-10T07:52:36.842631Z","shell.execute_reply.started":"2022-11-10T07:52:36.080358Z","shell.execute_reply":"2022-11-10T07:52:36.841367Z"},"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":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample_sub","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test.shape","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n#         print(i)\nimg = np.reshape(np.asarray(test1), (28, 28))\n#     cv2.imwrite('image0.png',img)\nplt.imshow(img)\nplt.show()\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# confusion matrix\n\ngives 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.\n\nthe size of the matrix will depend upon the number of classes present in the model.","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":{"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":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(test.shape)","metadata":{"trusted":true},"execution_count":null,"outputs":[]}]}