{"cells":[{"metadata":{},"cell_type":"markdown","source":"Continuing on the [discussion](https://www.kaggle.com/c/digit-recognizer/discussion/61480). Will be trying the following on this post\n* 99%: Convolutional neural networks are the champions in image classification. If you simply add one layer of conv filters to your fully connected NN (before the dense layers), you'll beat 99%. \nFor example in Keras: model.add(Conv2D(filters=32,kernel_size=5,activation='relu')) The simple network 784-32C5-500-10 with dropout achieves 99% after 30 epochs. (Add a pooling layer and it gets there in 15 epochs.)\n* 99.5%: If you design a good CNN architecture and then add special features like pooling layers, data augmentation, dropout, batch normalization, decaying learning rate, advanced optimization; You'll have no problem breaking the landmark 99.5% in only 20 epochs! Example [here](https://www.kaggle.com/cdeotte/how-to-choose-cnn-architecture-mnist)\n* Best Design: The best design is to start with convolution layer(s), then add a pooling layer. Then add convolution layer(s), then another pooling. Then add dense layer(s). Finish with softmax. There are many wonderful tutorials on Kaggle."},{"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 in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nfrom sklearn.model_selection import train_test_split\nfrom keras.models import Sequential\nfrom keras import layers\nfrom keras import optimizers\nfrom keras import callbacks\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.utils.np_utils import to_categorical\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"../input\"))\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"train = pd.read_csv(\"../input/train.csv\")\ntest = pd.read_csv(\"../input/test.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"Y_train = train[\"label\"]\nX_train = train.drop(labels=[\"label\"], axis=1) \n# free some space\ndel train ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Normalize the data\nX_train = X_train / 255.0\ntest = test / 255.0","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Reshape image in 3 dimensions (height = 28px, width = 28px , canal = 1)\nX_train = X_train.values.reshape(-1, 28, 28, 1)\ntest = test.values.reshape(-1, 28, 28, 1)\nY_train = to_categorical(Y_train, num_classes=10)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def predict(model, test):\n    results = model.predict(test)\n    # select the indix with the maximum probability\n    results = np.argmax(results, axis = 1)\n    results = pd.Series(results, name=\"Label\")\n    return results","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"random_seed = 2\n# Split the train and the validation set for the fitting\nX_train, X_val, Y_train, Y_val = train_test_split(X_train, Y_train, test_size = 0.1, random_state=random_seed)\nepochs = 30\nbatch_size = 86\noptimizer = optimizers.RMSprop(lr=0.001, rho=0.9, epsilon=1e-08, decay=0.0)\nlearning_rate_reduction = callbacks.ReduceLROnPlateau(monitor='val_acc', \n                                            patience=3, \n                                            verbose=1, \n                                            factor=0.5, \n                                            min_lr=0.00001)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"simple_model = Sequential()\nsimple_model.add(layers.Conv2D(filters=32, kernel_size=(5, 5), padding='Same', activation='relu',\n        input_shape = (28, 28, 1)))\nsimple_model.add(layers.MaxPool2D(pool_size=(2, 2), strides=(2, 2)))\nsimple_model.add(layers.Conv2D(filters=32, kernel_size=(5,5),padding = 'Same', activation ='relu'))\nsimple_model.add(layers.Conv2D(filters=32, kernel_size = (5,5),padding = 'Same', activation ='relu'))\nsimple_model.add(layers.MaxPool2D(pool_size=(2, 2)))\nsimple_model.add(layers.Conv2D(filters=32, kernel_size = (5,5),padding = 'Same', activation ='relu'))\nsimple_model.add(layers.Conv2D(filters=32, kernel_size = (5,5),padding = 'Same', activation ='relu'))\nsimple_model.add(layers.MaxPool2D(pool_size=(2, 2)))\nsimple_model.add(layers.Dropout(0.25))\nsimple_model.add(layers.Flatten())\nsimple_model.add(layers.Dense(500, activation=\"relu\"))\nsimple_model.add(layers.Dropout(0.5))\nsimple_model.add(layers.Dense(10, activation=\"softmax\"))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = Sequential()\nmodel.add(layers.Conv2D(filters=32, kernel_size=(5, 5),padding='Same', activation ='relu',\n        input_shape=(28, 28, 1)))\nmodel.add(layers.Conv2D(filters=32, kernel_size=(5, 5),padding = 'Same', activation ='relu'))\nmodel.add(layers.MaxPool2D(pool_size=(2, 2)))\nmodel.add(layers.Dropout(0.25))\n\nmodel.add(layers.Conv2D(filters=64, kernel_size=(3, 3), padding='Same', activation='relu'))\nmodel.add(layers.Conv2D(filters=64, kernel_size=(3, 3), padding='Same', activation='relu'))\nmodel.add(layers.MaxPool2D(pool_size=(2, 2), strides=(2, 2)))\nmodel.add(layers.Dropout(0.25))\n\nmodel.add(layers.Flatten())\nmodel.add(layers.Dense(256, activation=\"relu\"))\nmodel.add(layers.Dropout(0.5))\nmodel.add(layers.Dense(10, activation=\"softmax\"))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"lenet = Sequential()\nlenet.add(layers.Conv2D(filters=6, kernel_size=(5, 5), padding='Same', activation ='tanh',\n        input_shape=(28,28,1), strides=(1, 1)))\nlenet.add(layers.AveragePooling2D(pool_size=(2, 2), padding='Valid', strides=(1, 1)))\nlenet.add(layers.Conv2D(filters=16, kernel_size=(5, 5), padding='Valid', strides=(1, 1), activation='tanh'))\nlenet.add(layers.AveragePooling2D(pool_size=(2, 2), padding='Valid', strides=(2, 2)))\nlenet.add(layers.Conv2D(filters=120, kernel_size = (5, 5),padding = 'Valid', activation ='tanh', strides=(1, 1)))\nlenet.add(layers.Flatten())\nlenet.add(layers.Dense(84, activation = \"tanh\"))\nlenet.add(layers.Dense(10, activation = \"softmax\"))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(optimizer=optimizer, loss=\"categorical_crossentropy\", metrics=[\"accuracy\"])\nsimple_model.compile(optimizer=optimizer, loss=\"categorical_crossentropy\", metrics=[\"accuracy\"])\nlenet.compile(optimizer='SGD', loss=\"categorical_crossentropy\", metrics=[\"accuracy\"])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"datagen = ImageDataGenerator(\n        featurewise_center=False,  # set input mean to 0 over the dataset\n        samplewise_center=False,  # set each sample mean to 0\n        featurewise_std_normalization=False,  # divide inputs by std of the dataset\n        samplewise_std_normalization=False,  # divide each input by its std\n        zca_whitening=False,  # apply ZCA whitening\n        rotation_range=10,  # randomly rotate images in the range (degrees, 0 to 180)\n        zoom_range = 0.1, # Randomly zoom image \n        width_shift_range=0.1,  # randomly shift images horizontally (fraction of total width)\n        height_shift_range=0.1,  # randomly shift images vertically (fraction of total height)\n        horizontal_flip=False,  # randomly flip images\n        vertical_flip=False)  # randomly flip images\n\n\ndatagen.fit(X_train)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model.fit_generator(datagen.flow(X_train,Y_train, batch_size=batch_size),\n                              epochs = epochs, validation_data = (X_val,Y_val),\n                              verbose = 2, steps_per_epoch=X_train.shape[0] // batch_size\n                              , callbacks=[learning_rate_reduction])\nsm_history = simple_model.fit_generator(datagen.flow(X_train,Y_train, batch_size=batch_size),\n                              epochs = epochs, validation_data = (X_val,Y_val),\n                              verbose = 2, steps_per_epoch=X_train.shape[0] // batch_size\n                              , callbacks=[learning_rate_reduction])\nln_history = lenet.fit_generator(datagen.flow(X_train,Y_train, batch_size=batch_size),\n                              epochs = epochs, validation_data = (X_val,Y_val),\n                              verbose = 2, steps_per_epoch=X_train.shape[0] // batch_size\n                              , callbacks=[learning_rate_reduction])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"simple_submission = pd.concat([pd.Series(range(1,28001),name = \"ImageId\"), predict(simple_model, test)],axis=1)\nsubmission = pd.concat([pd.Series(range(1,28001),name = \"ImageId\"), predict(model, test)], axis=1)\nlenet_submission = pd.concat([pd.Series(range(1,28001),name = \"ImageId\"), predict(lenet, test)], axis=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission.to_csv(\"cnn_digit.csv\",index=False)\nsimple_submission.to_csv(\"cnn_digit_simple.csv\",index=False)\nlenet_submission.to_csv(\"cnn_digit_lenet.csv\",index=False)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"The results are close to what was suggested. I was able to get 98.10% on the simple conv architecture, 99.50% on the other conv architecture."},{"metadata":{},"cell_type":"markdown","source":"vote if you liked it, fork if you loved it"}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.4","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}