{"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)\nimport matplotlib.pyplot as plt\nimport seaborn as sns # for data visualization\n%matplotlib inline\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","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Import Dataset"},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"train_df= pd.read_csv('../input/digit-recognizer/train.csv')\ntest_df= pd.read_csv('../input/digit-recognizer/test.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.sample(5)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.iloc[8672,0]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# converting dataframe to numpy array\ntrain_df.iloc[4,1:].to_numpy().reshape(28,28)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Data Visualization"},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.imshow(train_df.iloc[4,1:].to_numpy().reshape(28,28)) # plot training sample data using reshape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# digit visualization\nplt.figure(figsize=(10,10))\nfor i in range(20):\n    plt.subplot(5,5,i+1) # creating subplot\n    plt.xticks([])\n    plt.yticks([])\n    plt.grid(False)\n    plt.imshow(train_df.iloc[i,1:].to_numpy().reshape(28,28))\n    plt.xlabel([train_df.iloc[i,0]])\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Data Preprocessing"},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.dtypes","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X= train_df.drop(['label'], axis='columns')\ny= train_df['label']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X.shape","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Train Test Split"},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\nX_train, x_test, y_train, y_test = train_test_split(X,y, test_size=0.2, random_state= 32)\nX_train.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train= X_train/255\nx_test= x_test/255","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train = X_train.to_numpy().reshape(-1,28,28,1)\nX_train.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_test = x_test.to_numpy().reshape(-1,28,28,1)\nx_test.shape","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Convolutional  Neural Network Model"},{"metadata":{"trusted":true},"cell_type":"code","source":"# import tensorflow and keras \nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = keras.Sequential([\n    #cnn\n    layers.Conv2D(56, (3,3), padding='same',activation='relu', input_shape=(28,28, 1)),\n    layers.MaxPooling2D((2,2)),\n    layers.Conv2D(28, (3,3),padding='same', activation='relu', input_shape=(28,128, 1)),\n    layers.MaxPooling2D((2,2)),\n    layers.Conv2D(14, (3,3),padding='same', activation='relu', input_shape=(28,128, 1)),\n    layers.MaxPooling2D((2,2)),\n    \n    #dense\n    layers.Flatten(),\n    layers.Dense(256, activation='relu'),\n    layers.Dense(128, activation='relu'),\n    layers.Dense(64, activation='relu'),\n    layers.Dense(32, activation='relu'),\n    keras.layers.Dense(10, activation='sigmoid')\n])\nmodel.summary() ","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"#### 3 layer neyral network is used."},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(\n     optimizer='adam',\n     loss='sparse_categorical_crossentropy',\n     metrics=[\"accuracy\"]\n)\nhistory= model.fit(X_train, y_train, epochs=50)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Prediction and Evaluation"},{"metadata":{"trusted":true},"cell_type":"code","source":"model.evaluate(x_test,y_test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_pred= model.predict(x_test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_pred[:10]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_pred= np.argmax(y_pred, axis=1)\ny_pred[:10]","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Classification report & Confusion Matrix"},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.metrics import classification_report\nprint(classification_report(y_test, y_pred))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data= tf.math.confusion_matrix(labels=y_test,predictions=y_pred)\nplt.figure(figsize=(8,6))\nsns.heatmap(data, fmt='d',annot=True)\nplt.xlabel('Predicred')\nplt.ylabel('True')\nplt.title('Confusion Matrix')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(8,6))\nplt.plot(history.history['accuracy'], label='accuracy')\nplt.plot(history.history['loss'], label='loss')\nplt.legend()\nplt.xlabel('Epoch')\nplt.ylabel('Accuracy')\nplt.grid('on')      ","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Test dataframe"},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df=test_df.to_numpy().reshape(-1,28,28,1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_testdata= test_df\ny_prediction= model.predict(x_testdata)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_prediction= np.argmax(y_prediction, axis=1)\ny_prediction[:10]","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Submission"},{"metadata":{"trusted":true},"cell_type":"code","source":"submit_ann = pd.DataFrame({'ImageId':range(1,len(y_prediction)+1),'Label':y_prediction})\n\nsubmit_ann.to_csv('submission_ann.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":4}