{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import classification_report\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# To enable the autocomplete\n%config Completer.use_jedi = False","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# About the dataset\n\n- The images are organized in line vectors and each sample (image) of the dataset occupies one line of the set. Each line of the dataset has 784 columns(28*28) in order to represent each pixel value of the image.\n- The image's pixels are value in [0,255]"},{"metadata":{"trusted":true},"cell_type":"code","source":"train_ds_path = \"/kaggle/input/digit-recognizer/train.csv\"\ntest_ds_path  = \"/kaggle/input/digit-recognizer/test.csv\"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Load the dataset\ndf_train = pd.read_csv(train_ds_path)\ny = df_train.iloc[:,0]\nx = df_train.iloc[:,1:]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y.hist()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def view_images(flat_images, labels, show_n_imgs = 10):\n    images = np.array(flat_images, dtype=\"uint8\").reshape(-1, 28, 28,1)\n    \n    plt.figure(figsize=(20,20))\n    plt.subplots_adjust(hspace=1)\n    for i, img in enumerate(images[:show_n_imgs]):\n        plt.subplot(10,5,i+1)\n#         plt.axis('off')\n        plt.imshow(img, cmap = 'gray')\n        plt.title(labels[i])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"view_images(x, y, 20)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x = x / 255.0","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Splitting the dataset into train and validation"},{"metadata":{"trusted":true},"cell_type":"code","source":"x_train , x_valid ,y_train , y_valid = train_test_split(x,y,test_size = 0.25)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow import keras","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# The model"},{"metadata":{"trusted":true},"cell_type":"code","source":"def fcModel(input_shape):\n    \n    X_input = keras.layers.Input(shape = input_shape, name='input')\n    \n    X = keras.layers.Dense(units=64, name='layer-1')(X_input)\n    X = keras.layers.BatchNormalization(name='b-1')(X)\n    X = keras.layers.Activation('relu')(X)\n    \n    X = keras.layers.Dropout(0.2)(X)\n    X = keras.layers.Dense(units=64, name='layer-2')(X)\n    X = keras.layers.BatchNormalization(name='b-2')(X)\n    X = keras.layers.Activation('relu')(X)\n    \n    X = keras.layers.Dropout(0.1)(X)\n    X = keras.layers.Dense(units=128, name='layer-3')(X)\n    X = keras.layers.BatchNormalization(name='b-3')(X)\n    X = keras.layers.Activation('relu')(X)\n    \n    X = keras.layers.Dropout(0.1)(X)\n    X = keras.layers.Dense(units=32, name='layer-4')(X)\n    X = keras.layers.BatchNormalization(name='b-4')(X)\n    X = keras.layers.Activation('relu')(X)\n    \n    X = keras.layers.Dense(units=10, activation='softmax', name='output')(X)\n    \n    model = keras.Model(inputs = X_input, outputs = X, name = \"Simple_Model\")\n    \n    return model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = fcModel(x_train.values.shape[1])\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(optimizer=\"adam\", loss=\"sparse_categorical_crossentropy\", metrics=[\"accuracy\"])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Training"},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model.fit(x_train, y_train, epochs=30, batch_size= 128, validation_data=(x_valid, y_valid))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history_dic = history.history\nhistory_dic.keys()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"loss_values = history_dic['loss']\nval_loss_values = history_dic['val_loss']\nepochs = range(1, len(loss_values)+1)\n\nplt.plot(epochs, loss_values, 'b-', label='Train')\nplt.plot(epochs, val_loss_values, 'y-', label='Validation')\n\nplt.ylim([-0.01, 0.5])\nplt.legend()\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"accuracy_values = history_dic['accuracy']\nval_accuracy_values = history_dic['val_accuracy']\nepochs = range(1, len(accuracy_values)+1)\n\nplt.plot(epochs, accuracy_values, 'b-', label='Train')\nplt.plot(epochs, val_accuracy_values, 'y-', label='Validation')\n\nplt.legend()\nplt.xlabel('Epochs')\nplt.ylabel('Accuracy')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"preds = model.evaluate(x = x_valid, y = y_valid)\nprint(\"Loss\", preds[0])\nprint(\"Accuracy\", preds[1])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_pred = model.predict(x_valid)\ny_pred = np.argmax(y_pred, axis=1)\n\nprint(classification_report(y_true = y_valid, y_pred = y_pred))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Submit"},{"metadata":{"trusted":true},"cell_type":"code","source":"df_test = pd.read_csv(test_ds_path)\nx_test = df_test.iloc[:,:] / 255.0","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_pred = model.predict(x_test)\ny_pred = np.argmax(y_pred, axis=1)\nsubmit = pd.DataFrame({\"Label\":y_pred}, index=np.arange(1,len(y_pred)+1))\nsubmit.index.name = \"ImageId\"\n\nsubmit.to_csv('submission.csv')\n\nsubmit.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"start = 30\nview_images((x_test*255.0)[start:], y_pred[start:], 10)","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}