{"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)\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":{"trusted":true},"cell_type":"code","source":"#Load the files \nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix\nimport itertools\n\nfrom keras.utils.np_utils import to_categorical # convert to one-hot-encoding\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D\nfrom keras.optimizers import RMSprop\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import ReduceLROnPlateau\nfrom keras.layers.core import Dense, Dropout, Activation\n\n\n\ntrain = pd.read_csv('/kaggle/input/digit-recognizer/train.csv')\n#training data\nX_train  = train.drop(['label'], axis=1)\n#training labels\nY_target = train['label']\n\n#testing data\ntest  = pd.read_csv('/kaggle/input/digit-recognizer/test.csv')\n\n#to free up some space\ndel train\n\n\n#print out the first 5 columns of train and test sets and their shapes\nprint(X_train.head())\nprint(np.shape(X_train))\nprint(test.head()) \nprint(np.shape(test))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# normalizing the data (between 0 and 1) to help the CNN with the training\nX_train /= 255.0\ntest /= 255.0\n\n# Reshape image in 3 dimensions (height = 28px, width = 28px , canal = 1) \n#chanal is 1 for grey scale images\nX_train = X_train.values.reshape(-1,28,28,1)\ntest = test.values.reshape(-1,28,28,1)\n\n#Lets see the shape of X_train set and test set after normalizaing and reshaping\nprint(\"shape of training data after reshaping :-\" ,np.shape(X_train))\nprint(\"shape of testing data after reshaping :-\"  ,np.shape(test))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# one-hot encoding using keras (ex : 3 -> [0,0,0,1,0,0,0,0,0,0])\nprint(\"Labels Shape before one-hot encoding: \", Y_target.shape)\nY_target = to_categorical(Y_target, 10)\nprint(\"Labels Shape after one-hot encoding: \", Y_target.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Split the train and the testing set for the fitting\nX_train, X_test, Y_target, Y_test = train_test_split(X_train, Y_target, test_size = 0.1, random_state=0)\ng = plt.imshow(X_train[9][:,:,0])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Set the CNN model \n\nmodel = Sequential()\n\n\nmodel.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same', activation ='relu',\n                input_shape=(28,28,1)))\nmodel.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same', activation ='relu'))\nmodel.add(MaxPool2D(pool_size=(2,2)))\n#Dropout to avoid overfitting\nmodel.add(Dropout(0.25))\n\nmodel.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same', activation ='relu'))\nmodel.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same', activation ='relu'))\nmodel.add(MaxPool2D(pool_size=(2,2),strides=(2,2)))\nmodel.add(Dropout(0.25))\n\n\n#Flatten output of conv\nmodel.add(Flatten())\n\n#Fully Connected layer\nmodel.add(Dense(256, activation = \"relu\"))\nmodel.add(Dropout(0.5))\n\n#Output layer\nmodel.add(Dense(10, activation = \"softmax\"))\n\n\n# compiling the sequential model\nmodel.compile(loss='categorical_crossentropy', metrics=['accuracy'], optimizer='adam')\n\n#print model architurch\nprint(model.summary())\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\n# training the model and saving metrics in history\nhistory = model.fit(X_train, Y_target,\n          batch_size=86, epochs=25,\n          verbose=2,\n          validation_data=(X_test, Y_test))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# plotting the metrics\nfig = plt.figure()\nplt.subplot(2,1,1)\nplt.plot(history.history['accuracy'])\nplt.plot(history.history['val_accuracy'])\nplt.title('model accuracy')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'], loc='lower right')\n\n\nplt.subplot(2,1,2)\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('model loss')\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'], loc='upper right')\n\nplt.tight_layout()","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"# predict results\nresults = model.predict(test)\n\n# select the indix with the maximum probability\nresults = np.argmax(results,axis = 1)\n\nresults = pd.Series(results,name=\"Label\")\nsubmission = pd.concat([pd.Series(range(1,28001),name = \"ImageId\"),results],axis = 1)\n\nsubmission.to_csv(\"cnn_mnist_datagen.csv\",index=False)","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}