{"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":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D, BatchNormalization\nfrom tensorflow.keras.optimizers import RMSprop\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom sklearn.model_selection import train_test_split\nfrom keras.callbacks import Callback\ntf.__version__","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Data Exploratory Analysis"},{"metadata":{"trusted":true},"cell_type":"code","source":"train = pd.read_csv(\"/kaggle/input/digit-recognizer/train.csv\")\ntest = pd.read_csv(\"/kaggle/input/digit-recognizer/test.csv\")\nsample = pd.read_csv(\"/kaggle/input/digit-recognizer/sample_submission.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":"train.describe()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train['label'].value_counts()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"Y = train[\"label\"].values\nX = train.drop(labels = [\"label\"],axis = 1).values \nX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.33, random_state=42)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(X_train.shape)\nprint(Y_train.shape)\nprint(X_test.shape)\nprint(Y_test.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Reshape image in 3 dimensions (height = 28px, width = 28px , channel = 1)\nX_train = X_train.reshape(-1,28,28,1)\nX_test = X_test.reshape(-1,28,28,1)\n# Final testing\nX_final = test.values.reshape(-1,28,28,1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"g = plt.imshow(X_train[0][:,:,0])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.imshow(X_test[3][:,:,0])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Defining Model"},{"metadata":{"trusted":true},"cell_type":"code","source":"# Defining a sequential model\nmodel = Sequential()\nmodel.add(Conv2D(16, (3,3), padding='same', activation='relu', input_shape = (28, 28, 1)))\nmodel.add(MaxPooling2D(2,2))\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(32, (3,3), padding='same', activation='relu'))\nmodel.add(MaxPooling2D(2,2))\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(64, (3,3), padding='same', activation='relu'))\nmodel.add(MaxPooling2D(2,2))\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(128, (3,3), padding='same', activation='relu'))\nmodel.add(MaxPooling2D(2,2))\nmodel.add(BatchNormalization())\nmodel.add(Flatten())\nmodel.add(Dense(512, activation=\"relu\"))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(10, activation=\"softmax\"))\n\n# Using RMSprop optimizer, sparse categorical cross entropy loss\nmodel.compile(\n    optimizer=RMSprop(lr=0.0001), \n    loss=\"sparse_categorical_crossentropy\", \n    metrics=[\"acc\"]\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_datagen = ImageDataGenerator(\n    rescale=1./255,\n#     rotation_range=40,\n#     width_shift_range=0.2,\n#     height_shift_range=0.2,\n#     shear_range=0.2,\n#     zoom_range=0.2,\n#     horizontal_flip=True,\n#     fill_mode='nearest'\n)\ntest_datagen = ImageDataGenerator(\n    rescale=1./255\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Hyperparameters\nepochs = 50\nmax_accuracy = 0.9999999\nbatch_size = 64\nsteps_per_epoch=len(X_train)//64\nvalidation_steps=len(X_test)//64","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class myCallback(Callback):\n    def on_epoch_end(self, epoch, logs={}):\n        if logs.get(\"acc\")>=max_accuracy:\n            print(\"\\nReached {}% accuracy!\".format(max_accuracy*100))\n            self.model.stop_training = True \n            \ncallback = myCallback()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model.fit_generator(\n    train_datagen.flow(X_train, Y_train, batch_size=batch_size),\n    epochs = epochs,\n    steps_per_epoch=steps_per_epoch,\n    callbacks=[callback],\n    validation_data=test_datagen.flow(X_test, Y_test),\n    validation_steps=validation_steps,\n    verbose=1\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Plot history\nacc = history.history['acc']\nval_acc = history.history['val_acc']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs = range(len(acc))\n\nplt.plot(epochs, acc, 'r', label='Training accuracy')\nplt.plot(epochs, val_acc, 'b', label='Validation accuracy')\nplt.title('Training and validation accuracy')\nplt.legend(loc=0)\nplt.figure()\n\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"score = model.evaluate(X_test, Y_test, verbose=0)\nprint('Test loss:', score[0])\nprint('Test accuracy:', score[1])\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"results = model.predict(X_final)\n\n# select the indix with the maximum probability\nresults = np.argmax(results,axis = 1)\n\n\nresults = pd.Series(results,name=\"Label\")\n\nsubmission = pd.concat([pd.Series(range(1,28001),name = \"ImageId\"),results],axis = 1)\n\nsubmission.to_csv(\"cnn_mnist.csv\",index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission.describe()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission['Label'].value_counts()","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}