{"cells":[{"metadata":{},"cell_type":"markdown","source":"Hello everyone! This is my first notebook here I hope it can help anyone. I would really appreciate some tips and advices considering structure of the notebook as well as the code. \nPart with evaulation and visualization of a model was copied from this kernel:\nhttps://www.kaggle.com/adityaecdrid/mnist-with-keras-for-beginners-99457\nIt is really nice kernel for those who wants to start with MNIST dataset. \n"},{"metadata":{},"cell_type":"markdown","source":"**Import necessary modules**"},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import os\nimport pandas as pd\nimport numpy as np\n\nfrom datetime import datetime\n\nimport matplotlib.pyplot as plt\n\nfrom keras.utils.np_utils import to_categorical\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D, Dense, Dropout, Flatten, MaxPool2D, BatchNormalization, Activation\nfrom keras.callbacks import ModelCheckpoint, EarlyStopping, ReduceLROnPlateau, TensorBoard\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.utils import plot_model\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix\n\nimport itertools\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Creating directories**"},{"metadata":{"trusted":true},"cell_type":"code","source":"path_main = '/kaggle/input/Kannada-MNIST'\npath_train = os.path.join(path_main, 'train.csv')\npath_test = os.path.join(path_main, 'test.csv')\npath_sample_sub = os.path.join(path_main, 'sample_submission.csv')\npath_dig_mnist = os.path.join(path_main, 'Dig-MNIST.csv')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Creating dataframes**"},{"metadata":{"trusted":true},"cell_type":"code","source":"train_dane = pd.read_csv(path_train)\ntest_dane = pd.read_csv(path_test)\nsample_dane = pd.read_csv(path_sample_sub)\ndig_mnist_dane = pd.read_csv(path_dig_mnist)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Converting data to types accepted by Keras**"},{"metadata":{"trusted":true},"cell_type":"code","source":"#\nX_train = train_dane.iloc[:,1:].values.astype('float32') # all pixel values\ny_train = train_dane.iloc[:,0].values.astype('int32') # only labels i.e targets digits\nX_test = test_dane.iloc[:,1:].values.astype('float32')\nDig_mnist_im = dig_mnist_dane.iloc[:,1:].values.astype('float32')\n\nX_train = X_train.reshape(X_train.shape[0], 28, 28)   \nX_test = X_test.reshape(X_test.shape[0], 28, 28)   \nDig_mnist_im = Dig_mnist_im.reshape(Dig_mnist_im.shape[0], 28, 28)   ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(10, 10))\nfor idx in range(0, 9):\n    plt.subplot(330 + (idx+1))\n    plt.imshow(X_train[idx], cmap=plt.get_cmap('gray'))\n    plt.title(y_train[idx])\n    \n    plt.tight_layout","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Preparing data**"},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train = X_train.reshape(X_train.shape[0], 28, 28, 1)    \nX_test = X_test.reshape(X_test.shape[0], 28, 28,1)\n\nmean_px = X_train.mean().astype(np.float32)\nstd_px = X_train.std().astype(np.float32)\n\nmean_px = X_train.mean().astype(np.float32)\nstd_px = X_train.std().astype(np.float32)\n\ndef standardize(x): \n    return (x-mean_px)/std_px\n\ny_train= to_categorical(y_train)\nnum_classes = y_train.shape\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Spliting data into train and validation sets **"},{"metadata":{"trusted":true},"cell_type":"code","source":"X = X_train\ny = y_train\nX_traine, X_val, y_traine, y_val = train_test_split(X_train, y_train, test_size=0.20, random_state=42)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Defining input shape for the model**"},{"metadata":{"trusted":true},"cell_type":"code","source":"input_shape=(28,28,1)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Definig convolutional model**"},{"metadata":{"trusted":true},"cell_type":"code","source":"model = Sequential([\n    Conv2D(32, (3,3), input_shape=input_shape, padding='same', activation='relu'),\n    Conv2D(32, (3,3), padding='same', activation='relu'),\n    BatchNormalization(momentum=0.15),\n    MaxPool2D((2,2)),\n    BatchNormalization(momentum=0.15),\n    Conv2D(64, (5,5), padding='same', activation='relu'),\n    Dropout(0.3),\n    \n    Conv2D(32, (3,3), padding='same', activation='relu'),\n    Conv2D(32, (3,3), padding='same', activation='relu'),\n    BatchNormalization(momentum=0.15),\n    MaxPool2D((2,2)),\n    BatchNormalization(momentum=0.15),\n    Conv2D(64, (5,5), padding='same', activation='relu'),\n    Dropout(0.3),\n\n    \n    Flatten(),\n    \n    Dense(128, activation='relu'),\n    Dropout(0.4),\n    Dense(10, activation='softmax')\n])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Callbacks**"},{"metadata":{"trusted":true},"cell_type":"code","source":"earlystopper = EarlyStopping(monitor='val_accuracy', min_delta=0.0001, patience=5, verbose=0, mode='max', baseline=0.995, restore_best_weights=False)\n\nlearning_rate_reduction = ReduceLROnPlateau(monitor='val_accuracy', \n                                            patience=3, \n                                            verbose=1, \n                                            factor=0.5, \n                                            min_lr=0.00001) #0.00001\ncallback = [learning_rate_reduction]","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Training model**"},{"metadata":{"trusted":true},"cell_type":"code","source":"# I discovered when playing around with MNIST dataset that batch size = 256 is sufficient is the best for it and I think here it is also true.\nhistory = model.fit(\n    X_traine, y_traine,\n    batch_size=512,\n    epochs=50,\n    validation_data=(X_val, y_val),\n    callbacks=callback\n)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Activation visualization**"},{"metadata":{},"cell_type":"markdown","source":"This is the part I straightforward copied from Aditya Soni to see activations in this Kannada set. I only left out visualizations of activations of dorpout layers because I don't need it right now and I think they don't add any new informations. "},{"metadata":{"trusted":true},"cell_type":"code","source":"test_im = X_train[6]\nplt.imshow(test_im.reshape(28,28), cmap='viridis', interpolation='none')\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.models import Model\nlayer_outputs = [layer.output for layer in model.layers[:len(model.layers)]] #I added here len(model.layers) so I will always get proper numbeer of layers which will be checked later. \nactivation_model = Model(input=model.input, output=layer_outputs)\nactivations = activation_model.predict(test_im.reshape(1,28,28,1))\n\nfirst_layer_activation = activations[0]\nplt.matshow(first_layer_activation[0, :, :, 4], cmap='viridis')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(model.input)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.layers[:-1]# Droping The Last Dense Layer","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"layer_names = []\nfor layer in model.layers[:-1]:\n    layer_names.append(layer.name) \nimages_per_row = 16\nzipped_layers = zip(layer_names, activations)\nfor layer_name, layer_activation in zipped_layers: #this loop     \n    if layer_name.startswith('conv'):\n        n_features = layer_activation.shape[-1]\n        size = layer_activation.shape[1]\n        n_cols = n_features // images_per_row\n        display_grid = np.zeros((size * n_cols, images_per_row * size))\n        for col in range(n_cols):\n            for row in range(images_per_row):\n                channel_image = layer_activation[0,:, :, col * images_per_row + row]\n                channel_image -= channel_image.mean()\n                channel_image /= channel_image.std()\n                channel_image *= 64\n                channel_image += 128\n                channel_image = np.clip(channel_image, 0, 255).astype('uint8')\n                display_grid[col * size : (col + 1) * size,\n                             row * size : (row + 1) * size] = channel_image\n        scale = 1. / size\n        plt.figure(figsize=(scale * display_grid.shape[1],\n                            scale * display_grid.shape[0]))\n        plt.title(layer_name)\n        plt.grid(False)\n        plt.imshow(display_grid, aspect='auto', cmap='viridis')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"layer_names = []\nfor layer in model.layers[:-1]:\n    layer_names.append(layer.name) \nimages_per_row = 16\nfor layer_name, layer_activation in zip(layer_names, activations):\n    if layer_name.startswith('max'):\n        n_features = layer_activation.shape[-1]\n        size = layer_activation.shape[1]\n        n_cols = n_features // images_per_row\n        display_grid = np.zeros((size * n_cols, images_per_row * size))\n        for col in range(n_cols):\n            for row in range(images_per_row):\n                channel_image = layer_activation[0,:, :, col * images_per_row + row]\n                channel_image -= channel_image.mean()\n                channel_image /= channel_image.std()\n                channel_image *= 64\n                channel_image += 128\n                channel_image = np.clip(channel_image, 0, 255).astype('uint8')\n                display_grid[col * size : (col + 1) * size,\n                             row * size : (row + 1) * size] = channel_image\n        scale = 1. / size\n        plt.figure(figsize=(scale * display_grid.shape[1],\n                            scale * display_grid.shape[0]))\n        plt.title(layer_name)\n        plt.grid(False)\n        plt.imshow(display_grid, aspect='auto', cmap='viridis')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Model evalution **"},{"metadata":{"trusted":true},"cell_type":"code","source":"final_loss, final_acc = model.evaluate(X_val, y_val, verbose=0)\nprint(\"Final loss: {0:.6f}, final accuracy: {1:.6f}\".format(final_loss, final_acc))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Look at confusion matrix \n#Note, this code is taken straight from the SKLEARN website, an nice way of viewing confusion matrix.\ndef plot_confusion_matrix(cm, classes,\n                          normalize=False,\n                          title='Confusion matrix',\n                          cmap=plt.cm.Blues):\n    \"\"\"\n    This function prints and plots the confusion matrix.\n    Normalization can be applied by setting `normalize=True`.\n    \"\"\"\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    if normalize:\n        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\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":{"trusted":true},"cell_type":"code","source":"print(history.history.keys())\naccuracy = history.history['accuracy']\nval_accuracy = history.history['val_accuracy']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\nepochs = range(len(accuracy))\nplt.plot(epochs, accuracy, 'bo', label='Training accuracy')\nplt.plot(epochs, val_accuracy, 'b', label='Validation accuracy')\nplt.title('Training and validation accuracy')\nplt.legend()\nplt.show()\nplt.figure()\nplt.plot(epochs, loss, 'bo', label='Training loss')\nplt.plot(epochs, val_loss, 'b', label='Validation loss')\nplt.title('Training and validation loss')\nplt.legend()\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Errors are difference between predicted labels and true labels\nerrors = (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":{},"cell_type":"markdown","source":"**Prediction and submission** "},{"metadata":{"trusted":true},"cell_type":"code","source":"predictions = model.predict_classes(X_test, verbose=0)\n\n\npredictions = model.predict_classes(X_test, verbose=0)\n\nsubmission = pd.read_csv(path_sample_sub)\nsubmission['label'] = predictions\n\nsubmission.to_csv('submission.csv', index=False)","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":1}