{"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 tensorflow as tf\nfrom tensorflow import keras\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\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\n%matplotlib inline","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Load the data\nLoad data from CSV files and split into training and validation sets of 80% and 20% each.","execution_count":null},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"training_set = pd.read_csv('/kaggle/input/digit-recognizer/train.csv')\ntesting_set = pd.read_csv('/kaggle/input/digit-recognizer/test.csv')\nsubmissions = pd.read_csv('/kaggle/input/digit-recognizer/sample_submission.csv')\n\nnrows, ncols, channels = 28, 28, 1","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Cleaning and preparing the data\nDrop all missing values and normalize the dataset so that all pixel values are between 0 to 1.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"training_set.dropna(axis = 0, inplace = True)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Split training data into training set and testing set.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"seed = 20\n\nX_train, X_val, y_train, y_val = train_test_split(training_set.drop(['label'], axis=1), training_set[['label']],\n                                                    random_state = seed, test_size=0.2)\n\nprint(\"Training set size = {}, Validation set size = {}\".format(len(X_train), len(X_val)))\nprint(\"Number of images in testing set = {}\".format(training_set.shape[0]))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Normalize the training set and testing set data.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train = X_train / 255\nX_val = X_val / 255\ntesting_set = testing_set / 255\n\n# reshape the entire data to images of size 28x28\nX_train = X_train.values.reshape(-1, nrows, ncols, channels)\nX_val = X_val.values.reshape(-1, nrows, ncols, channels)\ntesting_set = testing_set.values.reshape(-1, nrows, ncols, channels)\n\n# convert numerical classes into categorical classes\ny_train = keras.utils.to_categorical(y_train, num_classes = 10)\ny_val = keras.utils.to_categorical(y_val, num_classes = 10)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Visualize the training set\nLet's visualize the 1st 100 images in the dataset.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"def visualize_data(rows, cols, data, predictions=None):\n    img = 0\n    \n    plt.rcParams['figure.figsize'] = (15, 15)\n    fig, axes = plt.subplots(rows, cols)\n\n    for i in range(0, rows):\n        for j in range(0, cols):\n            axes[i, j].imshow(data[img, :, :, 0], cmap='gray')\n            axes[i, j].grid(False)\n            axes[i, j].set_xticks([])\n            axes[i, j].set_yticks([])\n            if predictions is not None:\n                axes[i, j].set_xlabel('Predcited = {}'.format(predictions[img]))\n            img += 1\n            \nvisualize_data(10, 10, X_train)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Data Augmentation\nAdd similar images or create augmented data. Augmentations that can be applied includes:\n* Rotation.\n* Translation about each axis.\n* Scaling.\n* Croping.\n* Adding a bit of Gaussian noise.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.preprocessing.image import ImageDataGenerator\n\ndatagen = ImageDataGenerator(rotation_range=5, width_shift_range=3,\n                            height_shift_range=3, shear_range=0.3, zoom_range=0.08)\n\ntrain = datagen.flow(X_train, y_train, batch_size=64)\nval = datagen.flow(X_val, y_val, batch_size=64)\n\ntrain.n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Create and train the CNN model","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"model = keras.models.Sequential([\n    keras.layers.Conv2D(64, (3, 3), activation='relu', input_shape=(nrows, ncols, channels)),\n    keras.layers.MaxPool2D(2, 2),\n    keras.layers.Conv2D(128, (3, 3), activation='relu'),\n    keras.layers.MaxPool2D(2, 2),\n    keras.layers.Flatten(),\n    keras.layers.Dense(1024, activation='relu'),\n    keras.layers.Dense(10, activation='softmax')\n])\n\nmodel.compile(loss = 'categorical_crossentropy',\n             optimizer = 'adam', metrics = ['accuracy'])\n\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model.fit(x=train, epochs=5, validation_data=val)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Let's try to make predictions on the testing dataset.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"Shape of testing dataset:\", testing_set.shape)\narr_probabilities = model.predict(testing_set, batch_size=500)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predictions = []\n\nfor probabilities in arr_probabilities:\n    predictions.append(np.argmax(probabilities))\n    \npredictions[:10]","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"It seems the 1st 10 predictions are 2, 0, 9, 9, 3, 7, 0, 3, 0, 3. Lets verify this by visualizing the first 10 testing set images.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"visualize_data(2, 5, testing_set, predictions)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submissions['Label'] = predictions\nsubmissions.head()","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}