{"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":"\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom keras.datasets import mnist\nfrom keras import Sequential,layers\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.layers.experimental import preprocessing\nfrom sklearn.model_selection import train_test_split","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train = pd.read_csv('../input/digit-recognizer/train.csv')\ntrain.head()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.shape","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#label  = train['label']\n#att= train.drop('label',axis=1)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#att = att/255","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#x_train ,x_test,y_train,y_test = train_test_split(att,label)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#from sklearn.svm import SVC ","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n#svc = SVC(kernel='rbf', C=1).fit(x_train, y_train)    #training the data\n#y_pred = svc.predict(x_test) ","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"''''\n#importing confusion matrix\nfrom sklearn.metrics import confusion_matrix\nconfusion = confusion_matrix(y_test, y_pred)\nprint('Confusion Matrix\\n')\nprint(confusion)'''","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#import seaborn as sns\n#import matplotlib.pyplot as plt\n#plt.figure(figsize=(15,8))\n#sns.heatmap(confusion, annot=True, \n #            cmap='Blues')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test  =pd.read_csv('../input/digit-recognizer/test.csv')\ntest.shape","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#test =test/255","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#svc = SVC(kernel='rbf', C=1).fit(att, label)    #training the data\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#y_pred = svc.predict(test)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#imgid=range(1,len(y_pred)+1)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#submission=pd.DataFrame({'ImageId':imgid,'Label':y_pred})\n#submission.to_csv('submission.csv',index=False)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#submission.shape","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#submission","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#y_pred.shape","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#att.shape","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#att = att.values.reshape(42000,28,28,1)\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#att = att/255","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#import matplotlib.pyplot as plt\n#plt.imshow(att[5])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.head()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"label = train.label\natt = train.drop('label',axis=1)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"att = att.values.reshape(42000,28,28,1)\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"att =att/255","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_train ,x_test,y_train,y_test = train_test_split(att,label)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"num_classes =10\nY_train = keras.utils.to_categorical(y_train ,num_classes)\nY_test  =keras.utils.to_categorical(y_test,num_classes)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print('X_train Shape :' + str(x_train.shape))   #shape of Data\nprint('Y_train Shape :' + str(Y_train.shape))\nprint('X_test Shape :' + str(x_test.shape))\nprint('Y_test Shape :' + str(Y_test.shape))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = keras.Sequential([\n    layers.InputLayer(input_shape=(28,28,1)),\n    \n    #Data Augmentation\n    preprocessing.RandomContrast(factor = 0.10),\n    preprocessing.RandomFlip(mode ='horizontal'),\n    preprocessing.RandomRotation(factor =0.10),\n    \n    #Block One\n    layers.BatchNormalization(renorm =True),\n    layers.Conv2D(filters=32,kernel_size =3,activation ='relu',padding='same'),\n    layers.MaxPool2D(),\n    \n    #Block Two\n    layers.BatchNormalization(renorm=True),\n    layers.Conv2D(filters=64,kernel_size=3,activation='relu',padding='same'),\n    \n                  #head\n    layers.BatchNormalization(renorm=True),\n    layers.Flatten(),\n    \n    layers.Dense(10,activation ='sigmoid'),\n                  \n    ])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(optimizer='rmsprop',\n              loss = 'binary_crossentropy',\n              metrics = ['binary_accuracy'],\n                )\nhistory = model.fit(x_train, Y_train,\n              batch_size=32,\n              epochs=20,\n              validation_data=(x_test, Y_test),\n              shuffle=True)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history_frame = pd.DataFrame(history.history)\nhistory_frame.loc[:, ['loss', 'val_loss']].plot()\nhistory_frame.loc[:, ['binary_accuracy', 'val_binary_accuracy']].plot();","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"Y_pred = model.predict(x_test)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.metrics import classification_report, confusion_matrix\ny_pred = np.argmax(Y_pred, axis=1)\nprint('Confusion Matrix')\nprint(confusion_matrix(y_test, y_pred))\nprint('Classification Report')\ntarget_names = ['0','1','2','3','4','5','6','7','8','9']\nprint(classification_report(y_test, y_pred, target_names=target_names))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import seaborn as sns\nplt.figure(figsize=(15,8))\nsns.heatmap(confusion_matrix(y_test,y_pred), annot=True, \n             cmap='Blues')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.evaluate(x_test,Y_test)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"Y = keras.utils.to_categorical(label ,num_classes)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = model.fit(att,Y,\n              batch_size=32,\n              epochs=20,\n              \n              shuffle=True)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test  =pd.read_csv('../input/digit-recognizer/test.csv')\ntest.shape","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test =test/255","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test.shape","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test = test.values.reshape(28000,28,28,1)\ntest.shape","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test.shape","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"Y_pred = model.predict(test)\ny_pred = np.argmax(Y_pred, axis=1)\ny_pred","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"imgid=range(1,len(y_pred)+1)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission=pd.DataFrame({'ImageId':imgid,'Label':y_pred})\nsubmission.to_csv('submission.csv',index=False)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}