{"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+98999\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 5GB 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":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n%matplotlib inline","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train = pd.read_csv('../input/digit-recognizer/train.csv')\ntest = pd.read_csv('../input/digit-recognizer/test.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X = train.drop('label', axis = 1)\ny = train['label']\ndel train","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sns.countplot(y)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Visualizing the Data","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"some_value = X.values[27]\nsome_value = some_value.reshape(28,28)\nsns.heatmap(some_value, cmap= 'binary', yticklabels=False, xticklabels= False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"display(y.values[27])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Normalization","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"np.unique(X.values)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X = X / 255.0\ntest = test / 255.0","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Reshape the training and test images\n\nKeras required images to be order 3 tensors. Thus, we require an additional dimension in our data. Apart from this, the images needs to go inside in batches and thus requires another dimension to specify that","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"X = X.values.reshape(-1,28,28,1)\ntest = test.values.reshape(-1,28,28,1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#converting y into one hot encoding\nlabels = pd.get_dummies(y)\nlabels = labels.values","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Training and Validation Set","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\n\nX_train, X_val, y_train, y_val = train_test_split(X, labels, test_size = 0.1,random_state=42)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"display(X_train.shape)\ndisplay(y_train.shape)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Data Augmentation","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.preprocessing.image import ImageDataGenerator","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"datagen = ImageDataGenerator(shear_range= 0.2, zoom_range= 0.2)\ndatagen.fit(X_train)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Creating a CNN Model","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"#import the required libraries\n\nfrom keras.layers import Dropout, Conv2D, MaxPool2D, Dense, Flatten\nfrom keras.models import Sequential","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = Sequential()\n\n#First Layer\n#Convolutional Layers\nmodel.add(Conv2D(filters = 64, kernel_size = 5,activation ='relu', input_shape = (28,28,1)))\nmodel.add(Conv2D(filters = 64, kernel_size = 5,activation ='relu'))\n#Pooling\nmodel.add(MaxPool2D(pool_size=(2,2)))\n#Dropout\nmodel.add(Dropout(0.2))\n\n#Second Layer\n#Convolutional Layers\nmodel.add(Conv2D(filters = 32, kernel_size = 3,activation ='relu'))\nmodel.add(Conv2D(filters = 32, kernel_size = 3,activation ='relu'))\n#Pooling\nmodel.add(MaxPool2D(pool_size=(2,2)))\n#Dropout\nmodel.add(Dropout(0.2))\n\nmodel.add(Flatten())\nmodel.add(Dense(256, activation = \"relu\"))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(10, activation = \"softmax\"))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#compile the model\nmodel.compile(optimizer= 'adam', loss= 'categorical_crossentropy', metrics= ['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Fit the Model","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"performance = model.fit_generator(datagen.flow(X_train,y_train, batch_size=64), epochs = 30, \n                                  validation_data = (X_val,y_val), verbose = 3)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"loss = pd.DataFrame(performance.history)\n#plotting\nfig, axes = plt.subplots(2,1, figsize = (10,12))\naxes[0].plot(loss['loss'], \"r\", label = 'Training loss')\naxes[0].plot(loss['val_loss'], \"b\", label = 'Validation loss')\nlegend = axes[0].legend()\n\naxes[1].plot(loss['accuracy'], \"r\", label = 'Training Accuracy')\naxes[1].plot(loss['val_accuracy'], \"b\", label = 'Validation Accuracy')\nlegend = axes[1].legend()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.metrics import confusion_matrix, classification_report","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#creating confusion matrix\npred = model.predict(X_val)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Convert predictions classes to one hot vectors \npred_classes = np.argmax(pred,axis = 1) \n# Convert validation observations to one hot vectors\ny_true = np.argmax(y_val,axis = 1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"conf = confusion_matrix(y_true, pred_classes)\nplt.figure(figsize= (10,8))\nsns.heatmap(conf, annot= True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(classification_report(y_true, pred_classes))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Submissions","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"test_preds = model.predict(test)\ntest_preds = np.argmax(test_preds,axis = 1)\ntest_preds = pd.Series(test_preds,name=\"Label\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission = pd.concat([pd.Series(range(1,28001),name = \"ImageId\"),test_preds],axis = 1)\nsubmission.to_csv(\"cnn_mnist.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}