{"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","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd\nfrom matplotlib import pyplot\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom numpy import asarray, unique, argmax\nfrom tensorflow.keras import Sequential\nfrom tensorflow.keras.layers import Dense, Conv2D, MaxPool2D, Flatten, Dropout\nfrom keras.optimizers import RMSprop","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Reading the train dataset\ndata = pd.read_csv('/kaggle/input/digit-recognizer/train.csv')\ndata.head()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#checking the shape of provided train dataset\ndata.shape","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#checking unique numbers in train label column\nunique = data['label'].unique()\nprint(\"Unique Numbers :\",unique)\n\n#countine the unique number of digits for classification\nn_classes = len(unique)\nprint(\"Number of classes :\",n_classes)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Filtering the dataset between X and Y\nx = data.drop(labels = [\"label\"], axis=1)\nprint(\"X= \",x)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Filtering the target variable from the train data\ny = data['label']\nprint(\"Target Variable: \",y)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Splitting the dataset in train and test\nx_train, x_test, y_train, y_test = train_test_split(x,y, test_size=0.20, random_state=42)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Priting the Splitted dataset\nprint(\"X_train: \", x_train)\nprint(\"X_test: \", y_test)\nprint(\"Y_train: \", y_train)\nprint(\"Y_test: \", y_test)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Reshaping the Dataset\nx_train = x_train.values.reshape(-1,28,28,1)\nx_test = x_test.values.reshape(-1,28,28,1)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#determine the shape of input images\nin_shape = x_train.shape[1:]\nprint(in_shape)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.imshow(x_train[0].reshape([28,28]))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# normalize pixel values\nx_train = x_train.astype('float32') / 255.0\nx_test = x_test.astype('float32') / 255.0","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = Sequential()\n\nmodel.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same', \n                 activation ='relu', input_shape = in_shape))\nmodel.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same', \n                 activation ='relu'))\nmodel.add(MaxPool2D(pool_size=(2,2)))\nmodel.add(Dropout(0.25))\n\n\nmodel.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same', \n                 activation ='relu'))\nmodel.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same', \n                 activation ='relu'))\nmodel.add(MaxPool2D(pool_size=(2,2), strides=(2,2)))\nmodel.add(Dropout(0.25))\n\n\nmodel.add(Flatten())\nmodel.add(Dense(256, activation = \"relu\"))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(10, activation = \"softmax\"))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"optimizer = RMSprop(lr=0.001, rho=0.9, epsilon=1e-08, decay=0.0)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# define loss and optimizer\nmodel.compile(optimizer= 'adam', loss = 'sparse_categorical_crossentropy', metrics=['accuracy'])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# fit the model\nmodel.fit(x_train, y_train, validation_split=0.2, epochs=100, batch_size=128, verbose= 1)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Evaluate the model\nloss, accuracy = model.evaluate(x_test, y_test, verbose=1)\nprint('Accuracy: %.3f' %accuracy)\nprint('Loss: ',loss)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#make a pridiction\nimage = x_test[2]\nypred = model.predict(asarray([image]))\nprint('Prediction: Class =%d' %argmax(ypred))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.imshow(x_test[2].reshape([28,28]))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Reading the test Data\ntest_data = pd.read_csv('/kaggle/input/digit-recognizer/test.csv')\ntest_data.head()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Normalize the test data\ntest = test_data/255.0","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Reshaping the test data\ntest_final_Data = test.values.reshape(-1,28,28,1)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#pridicting the model\nlabel = model.predict(test_final_Data)\nprint(label)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#shape of the labels\nlabel.shape","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"label = np.argmax(label, axis=1)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(label)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(label.shape)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Reading the Given sample file for just checking the submission file format\nsample_submission = pd.read_csv('/kaggle/input/digit-recognizer/sample_submission.csv')\nsample_submission.head()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Creating the file ready with rows and Columns feild\nindex = test_data.index.values + 1\ndata = {'ImageId' : index, \"Label\" : label}\ndf = pd.DataFrame(data=data)\ndf.head()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submit_file = pd.DataFrame({'ImageId' : index, \"Label\" : label.astype(int).ravel()})\nsubmit_file.to_csv(\"submission.csv\",index = False)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submit_file","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}