{"cells":[{"metadata":{"_uuid":"f85776e0866931f0ee3ae777631c520ee9583ff2"},"cell_type":"markdown","source":"I present you my solution using Convolutional Neural Network with keras with which I get a good result.\n"},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd\n\nimport matplotlib.pyplot as plt\n\nfrom keras.utils.np_utils import to_categorical\nfrom keras.models import Sequential, load_model\nfrom keras.layers import Dense, Dropout, Lambda, Flatten, Conv2D, MaxPooling2D, Activation, MaxPool2D\nfrom keras.optimizers import SGD\nfrom keras.preprocessing import image\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom sklearn.model_selection import train_test_split","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"# load training & test datasets\ntrain = pd.read_csv(\"../input/digit-recognizer/train.csv\")\ntest = pd.read_csv(\"../input/digit-recognizer/test.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"fecfa7ae9077fe9d24e0035d8817a70e0c814c20"},"cell_type":"code","source":"# pandas to numpy\ny_train = train[\"label\"]\nX_train = train.drop(labels=[\"label\"], axis=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"e5c323305a8caf0310445148f117e44d089d5f4a"},"cell_type":"code","source":"# normalize\nX_train = np.array(X_train/255.0)\ntest = np.array(test/255.0)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"1ec983c164ac719b3bce150d48f32d991b86670e"},"cell_type":"markdown","source":"Let's have a look at some images"},{"metadata":{"trusted":true,"_uuid":"c0a0edb71a54bec75e82742e6b188fe835479784"},"cell_type":"code","source":"X_train_view = X_train.reshape(X_train.shape[0], 28, 28)\nfor i in range(10, 14):\n    plt.subplot(330 + (i+1))\n    plt.imshow(X_train_view[i], cmap=plt.get_cmap('gray'))\n    plt.title(y_train[i]);","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"41339d824388c2470f6f26f4fbe752f8ae9d09ff"},"cell_type":"code","source":"X_train = X_train.reshape(-1,28,28,1)\ntest = test.reshape(-1,28,28,1)\n\n# one-hot vector as a label (binarize the label)\ny_train = to_categorical(y_train, num_classes=10)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"889d93643d3fad87707dfb1c1d74426e33d48c11"},"cell_type":"markdown","source":"The Architecture is:\n\nConv (32) x 2 > Pool(2x2) > Dropout(0.25) > Conv (64) x 2 > Pool (2x2) > Dropout (0.25) > FC (256) > Dropout(0.25) > Softmax(10)"},{"metadata":{"trusted":true,"_uuid":"28f97a5ebbe20f0df0c9e1fab17a5004507fe94b"},"cell_type":"code","source":"model = Sequential()\n\nmodel.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same', \n                 activation ='relu', input_shape = (28,28,1)))\nmodel.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same', \n                 activation ='relu'))\nmodel.add(MaxPool2D(pool_size=(2,2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same', \n                 activation ='relu'))\nmodel.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same', \n                 activation ='relu'))\nmodel.add(MaxPool2D(pool_size=(2,2), strides=(2,2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Flatten())\nmodel.add(Dense(256, activation = \"relu\"))\nmodel.add(Dropout(0.25))\nmodel.add(Dense(10, activation = \"softmax\"))\n\nmodel.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"2e73d465b00de7095c24d4a62585d7bc17769856"},"cell_type":"code","source":"# check input and output shapes\nprint(\"input shape: \", model.input_shape)\nprint(\"output shape: \", model.output_shape)\nprint(\"X_train shape: \", X_train.shape)\nprint(\"test shape: \", test.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"e8aeb438d25aa841002d5234ab794db1fd8fa683"},"cell_type":"code","source":"# cross validation\nX_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.10, random_state=1)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"ac680cb9ab0eeac9d022bb27109fea1c36122346"},"cell_type":"markdown","source":"With data augmentation, we increase the data sample of interweaving with the rotated and scaled images, which reduces the overfitting and increases the accuracy"},{"metadata":{"trusted":true,"_uuid":"ec0468369c195a32e9b80be6481f9c57f2ab14e3"},"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=15,  # randomly rotate images in the range (degrees, 0 to 180)\n        zoom_range = 0.10, # Randomly zoom image \n        width_shift_range=0.15,  # randomly shift images horizontally (fraction of total width)\n        height_shift_range=0.15,  # randomly shift images vertically (fraction of total height)\n        horizontal_flip=False,  # randomly flip images\n        vertical_flip=False)  # randomly flip images\n\ndatagen.fit(X_train)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"d2ef0838fe0b610e2fd2ec014c8924aff142f93c"},"cell_type":"code","source":"# epochs = 20\nepochs=1\nbatch_size = 512","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"3bcf1da693b0dea93124e575d8e862d8b8040103"},"cell_type":"markdown","source":"**Fine tune with batch_size:**\n\nChanging only the batch_size parameter, I obtain the folowing results:\n\n64    Accuracy:  0.987857142857\n\n128   Accuracy:  0.991904761905\n\n256   Accuracy:  0.992142857143\n\n**512   Accuracy:  0.992857142857**\n\n1024  Accuracy:  0.992380952381\n\nTherefore I choose the 512 for Batch_size"},{"metadata":{"trusted":true,"_uuid":"bad902a1693cd183c9863d992111e37fadc6b128"},"cell_type":"code","source":"history = model.fit_generator(datagen.flow(X_train, y_train, batch_size=batch_size),\n                    steps_per_epoch=len(X_train) // batch_size, epochs=epochs,\n                    validation_data = (X_val,y_val) )","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"09376bfefee93dbba2aca6183a8519ce53e1f573"},"cell_type":"markdown","source":"To simplify the calculation, this kernel has been done with 1 iterations. I'm going to load a file with the weights of this same neural network with 20 interactions"},{"metadata":{"trusted":true,"_uuid":"bb171efe1f58b7c4d11795a4f45211fdf9664fe5"},"cell_type":"code","source":"model.load_weights('../input/digits-weights/digits2_weights.h5')","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"e7cc9dd44427fed6a76b254fa7bd52ba7ac795af"},"cell_type":"markdown","source":"**Accuracy**"},{"metadata":{"_uuid":"c167ffdd944b4bea8e175fcaaf10ccffd9d4f4d2"},"cell_type":"markdown","source":"I got a score of **0,99514** with de test set in the competition"},{"metadata":{"trusted":true,"_uuid":"7d06533fcd14fc876cc4df7e66357c20ddbf05f9"},"cell_type":"code","source":"loss, accuracy = model.evaluate(X_val, y_val)\nprint (\"\\nAccuracy: \", accuracy)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"2fc6798c72889d5f3939052f99a2aa6eac655e6b"},"cell_type":"markdown","source":"Submission"},{"metadata":{"trusted":true,"_uuid":"7559391014c3e7e161b42ab4aec044a678ea84e7"},"cell_type":"code","source":"# model prediction on test data\npredictions = model.predict_classes(test, verbose=0)\n\n# submission\nsubmissions = pd.DataFrame({\"ImageId\": list(range(1,len(predictions)+1)),\n    \"Label\": predictions})\nsubmissions.to_csv(\"DR.csv\", index=False, header=True)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"3f3eac25574f79e3dd0eed1898e1189ad3d34764"},"cell_type":"markdown","source":"**Confusion Matrix**"},{"metadata":{"trusted":true,"_uuid":"0fdd369d7d40eac0ec3e9da1cd9e6b0bf129e8b1"},"cell_type":"code","source":"from sklearn.metrics import confusion_matrix\nimport itertools\n\ndef plot_confusion_matrix(cm, classes,\n                          title='Confusion matrix',\n                          cmap=plt.cm.Blues):\n    plt.figure()\n    plt.imshow(cm, interpolation='nearest', cmap=cmap)\n    plt.title(title)\n    plt.colorbar()\n    tick_marks = np.arange(len(classes))\n    plt.xticks(tick_marks, classes, rotation=45)\n    plt.yticks(tick_marks, classes)\n\n    thresh = cm.max() / 2.\n    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n        plt.text(j, i, cm[i, j],\n                 horizontalalignment=\"center\",\n                 color=\"white\" if cm[i, j] > thresh else \"black\")\n\n    plt.tight_layout()\n    plt.ylabel('True label')\n    plt.xlabel('Predicted label')\n\n# Predict the values from the validation dataset\nY_pred = model.predict(X_val)\n# Convert predictions classes to one hot vectors \nY_pred_classes = np.argmax(Y_pred,axis = 1) \n# Convert validation observations to one hot vectors\nY_true = np.argmax(y_val,axis = 1) \n# compute the confusion matrix\nconfusion_mtx = confusion_matrix(Y_true, Y_pred_classes) \n# plot the confusion matrix\nplot_confusion_matrix(confusion_mtx, classes = range(10)) ","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"bd533177c25e773fd7bfb30e69a23ff2062202e7"},"cell_type":"markdown","source":"**Display some error results**\n\nErrors are the difference between predicted and true labels"},{"metadata":{"trusted":true,"_uuid":"81b3860abc14df0cb7419be501ad50e03c678dff"},"cell_type":"code","source":"errors = (Y_pred_classes - Y_true != 0)\n\nY_pred_classes_errors = Y_pred_classes[errors]\nY_pred_errors = Y_pred[errors]\nY_true_errors = Y_true[errors]\nX_val_errors = X_val[errors]\n\ndef display_errors(errors_index,img_errors,pred_errors, obs_errors):\n    \"\"\" This function shows 6 images with their predicted and real labels\"\"\"\n    n = 0\n    nrows = 2\n    ncols = 3\n    fig, ax = plt.subplots(nrows,ncols,sharex=True,sharey=True)\n    for row in range(nrows):\n        for col in range(ncols):\n            error = errors_index[n]\n            ax[row,col].imshow((img_errors[error]).reshape((28,28)))\n            ax[row,col].set_title(\"Predicted label :{}\\nTrue label :{}\".format(pred_errors[error],obs_errors[error]))\n            n += 1\n\n# Probabilities of the wrong predicted numbers\nY_pred_errors_prob = np.max(Y_pred_errors,axis = 1)\n\n# Predicted probabilities of the true values in the error set\ntrue_prob_errors = np.diagonal(np.take(Y_pred_errors, Y_true_errors, axis=1))\n\n# Difference between the probability of the predicted label and the true label\ndelta_pred_true_errors = Y_pred_errors_prob - true_prob_errors\n\n# Sorted list of the delta prob errors\nsorted_dela_errors = np.argsort(delta_pred_true_errors)\n\n# Top 6 errors \nmost_important_errors = sorted_dela_errors[-6:]\n\n# Show the top 6 errors\ndisplay_errors(most_important_errors, X_val_errors, Y_pred_classes_errors, Y_true_errors)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"ce7d8834324bd1fa6af4900dc65d5c512359c612"},"cell_type":"markdown","source":"The numbers are not well defined. Maybe a human would have also committed these errors."}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.6","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}