{"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_minor":4,"nbformat":4,"cells":[{"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)\n\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 20GB 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","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2021-06-08T00:58:50.564130Z","iopub.execute_input":"2021-06-08T00:58:50.564591Z","iopub.status.idle":"2021-06-08T00:58:50.576724Z","shell.execute_reply.started":"2021-06-08T00:58:50.564550Z","shell.execute_reply":"2021-06-08T00:58:50.574999Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install mglearn","metadata":{"execution":{"iopub.status.busy":"2021-06-08T00:58:50.579293Z","iopub.execute_input":"2021-06-08T00:58:50.579804Z","iopub.status.idle":"2021-06-08T00:59:02.340578Z","shell.execute_reply.started":"2021-06-08T00:58:50.579749Z","shell.execute_reply":"2021-06-08T00:59:02.339668Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import warnings\nwarnings.filterwarnings(\"ignore\")","metadata":{"execution":{"iopub.status.busy":"2021-06-08T00:59:02.343033Z","iopub.execute_input":"2021-06-08T00:59:02.343381Z","iopub.status.idle":"2021-06-08T00:59:02.348518Z","shell.execute_reply.started":"2021-06-08T00:59:02.343344Z","shell.execute_reply":"2021-06-08T00:59:02.347242Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd  # data frame operations  \nimport numpy as np  # arrays and math functions\nimport matplotlib.pyplot as plt  # static plotting\nimport matplotlib.cbook as cbook\nimport seaborn as sns  # pretty plotting, including heat map\nimport re # regular expressions\nimport scipy\nimport os # Operation System\nimport mglearn\nfrom sklearn.preprocessing import StandardScaler, MinMaxScaler\nfrom sklearn.model_selection import train_test_split\nfrom matplotlib.backends.backend_pdf import PdfPages\nfrom sklearn.metrics import roc_auc_score, confusion_matrix, mean_squared_error, r2_score  \nfrom sklearn.naive_bayes import BernoulliNB\nfrom sklearn import linear_model\nfrom sklearn.model_selection import KFold, GridSearchCV, cross_validate, cross_val_score, cross_val_predict\nfrom sklearn.datasets import make_blobs\nfrom sklearn.linear_model import LinearRegression, Ridge, Lasso, ElasticNet\nfrom sklearn.decomposition import PCA\nfrom math import sqrt  # for root mean-squared error calculation\nfrom sklearn.ensemble import RandomForestClassifier,  BaggingClassifier, RandomForestRegressor\nfrom sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor\nimport sklearn\nimport plotly\nimport plotly.graph_objs as go\nimport time\nfrom sklearn.datasets import make_classification\nfrom collections import OrderedDict\nfrom plotly import tools\nfrom sklearn.datasets import fetch_openml\nfrom sklearn.decomposition import PCA\nfrom sklearn.metrics import f1_score\nfrom sklearn import metrics\nimport cProfile","metadata":{"execution":{"iopub.status.busy":"2021-06-08T00:59:02.350120Z","iopub.execute_input":"2021-06-08T00:59:02.350421Z","iopub.status.idle":"2021-06-08T00:59:04.199169Z","shell.execute_reply.started":"2021-06-08T00:59:02.350391Z","shell.execute_reply":"2021-06-08T00:59:04.197954Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"os.getcwd()\n!ls\n!pwd","metadata":{"execution":{"iopub.status.busy":"2021-06-08T00:59:04.201023Z","iopub.execute_input":"2021-06-08T00:59:04.201525Z","iopub.status.idle":"2021-06-08T00:59:05.679736Z","shell.execute_reply.started":"2021-06-08T00:59:04.201476Z","shell.execute_reply":"2021-06-08T00:59:05.678339Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#load the data\nmnist_train = pd.read_csv(\"../input/digit-recognizer/train.csv\")\nmnist_test = pd.read_csv(\"../input/digit-recognizer/test.csv\")\n\nprint(mnist_train.shape)\nprint(mnist_test.shape)\n\nprint(mnist_train.head())\nprint(mnist_test.head())\n\n","metadata":{"execution":{"iopub.status.busy":"2021-06-08T00:59:05.683952Z","iopub.execute_input":"2021-06-08T00:59:05.684315Z","iopub.status.idle":"2021-06-08T00:59:12.136469Z","shell.execute_reply.started":"2021-06-08T00:59:05.684280Z","shell.execute_reply":"2021-06-08T00:59:12.135410Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"max(mnist_test.loc[2])\n#the data need to be normalized to 0 to 1","metadata":{"execution":{"iopub.status.busy":"2021-06-08T00:59:12.138163Z","iopub.execute_input":"2021-06-08T00:59:12.138900Z","iopub.status.idle":"2021-06-08T00:59:12.149448Z","shell.execute_reply.started":"2021-06-08T00:59:12.138852Z","shell.execute_reply":"2021-06-08T00:59:12.148319Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#use a regular random forest classifier to train the full set of 784 explanary variables\n\n\nshuffle = np.random.permutation(len(mnist_train))\nx_train = mnist_train.iloc[:,1:].iloc[shuffle]\ny_train = mnist_train.iloc[:,0].iloc[shuffle]","metadata":{"execution":{"iopub.status.busy":"2021-06-08T00:59:12.151948Z","iopub.execute_input":"2021-06-08T00:59:12.152283Z","iopub.status.idle":"2021-06-08T00:59:12.380074Z","shell.execute_reply.started":"2021-06-08T00:59:12.152253Z","shell.execute_reply":"2021-06-08T00:59:12.378851Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#data visualization to explore the class distribution of both training \nmn_plt =sns.countplot(mnist_train[\"label\"], palette=\"Blues\").set_title('Total Digit')\nfig1 = mn_plt.get_figure()\n#fig1.show()\nfig1.savefig('TotalDistMNIST.png', \n        bbox_inches = 'tight', dpi=None, facecolor='w', edgecolor='b', \n        orientation='portrait', papertype=None, format=None, \n        #transparent=True, pad_inches=0.25, frameon=None)\n         transparent=True, pad_inches=0.25)","metadata":{"execution":{"iopub.status.busy":"2021-06-08T00:59:12.381482Z","iopub.execute_input":"2021-06-08T00:59:12.381772Z","iopub.status.idle":"2021-06-08T00:59:12.698103Z","shell.execute_reply.started":"2021-06-08T00:59:12.381744Z","shell.execute_reply":"2021-06-08T00:59:12.696954Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"random_seed = 42\n\n#hereby will split the training datasets into sub_train data with 36000 instances and validation dataset with 6000 instances\n\nx_trn, x_val, y_trn, y_val = train_test_split(x_train, y_train, train_size=36000, random_state=1)\n\nprint(x_trn.shape)\nprint(y_trn.shape)\nprint(x_val.shape)\nprint(y_val.shape)","metadata":{"execution":{"iopub.status.busy":"2021-06-08T00:59:12.699496Z","iopub.execute_input":"2021-06-08T00:59:12.699843Z","iopub.status.idle":"2021-06-08T00:59:12.995511Z","shell.execute_reply.started":"2021-06-08T00:59:12.699787Z","shell.execute_reply":"2021-06-08T00:59:12.994508Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"mn_plt =sns.countplot(y_trn, palette=\"Blues\").set_title('Total Digit')\nfig1 = mn_plt.get_figure()\n#fig1.show()\nfig1.savefig('TotalDistMNIST.png', \n        bbox_inches = 'tight', dpi=None, facecolor='w', edgecolor='b', \n        orientation='portrait', papertype=None, format=None, \n        #transparent=True, pad_inches=0.25, frameon=None)\n         transparent=True, pad_inches=0.25)","metadata":{"execution":{"iopub.status.busy":"2021-06-08T00:59:12.996782Z","iopub.execute_input":"2021-06-08T00:59:12.997120Z","iopub.status.idle":"2021-06-08T00:59:13.444753Z","shell.execute_reply.started":"2021-06-08T00:59:12.997090Z","shell.execute_reply":"2021-06-08T00:59:13.443632Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Prepare data","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras.layers import Dense, Input, Flatten,\\\n                                    Reshape, LeakyReLU as LR,\\\n                                    Activation, Dropout\nfrom tensorflow.keras.models import Model, Sequential\nfrom matplotlib import pyplot as plt\nfrom IPython import display # If using IPython, Colab or Jupyter\nimport numpy as np","metadata":{"execution":{"iopub.status.busy":"2021-06-08T00:59:13.446080Z","iopub.execute_input":"2021-06-08T00:59:13.446404Z","iopub.status.idle":"2021-06-08T00:59:20.010098Z","shell.execute_reply.started":"2021-06-08T00:59:13.446370Z","shell.execute_reply":"2021-06-08T00:59:20.008761Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#normalize the data by dividing 255, and covert to 28 * 28 shape\nx_test = mnist_test\n\nx_trn = x_trn.astype('float32') / 255.0\nx_val = x_val.astype('float32') / 255.0\nx_test = x_test.astype('float32') / 255.0\n\nx_train = x_train.astype('float32') / 255.0\n\nnp.asarray(x_trn).shape","metadata":{"execution":{"iopub.status.busy":"2021-06-08T01:00:54.283944Z","iopub.execute_input":"2021-06-08T01:00:54.284387Z","iopub.status.idle":"2021-06-08T01:00:54.731364Z","shell.execute_reply.started":"2021-06-08T01:00:54.284352Z","shell.execute_reply":"2021-06-08T01:00:54.729977Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# validate to show first image\nplot_trn = np.asarray(x_trn).reshape((-1, 28, 28, 1))\n\nplt.figure(1)\nplt.subplot(221)\nplt.imshow(plot_trn[13][:,:,0])\n\nplt.subplot(222)\nplt.imshow(plot_trn[690][:,:,0])\n\nplt.subplot(223)\nplt.imshow(plot_trn[2375][:,:,0])\n\nplt.subplot(224)\nplt.imshow(plot_trn[5000][:,:,0])\n","metadata":{"execution":{"iopub.status.busy":"2021-06-08T01:03:01.748948Z","iopub.execute_input":"2021-06-08T01:03:01.749408Z","iopub.status.idle":"2021-06-08T01:03:02.152155Z","shell.execute_reply.started":"2021-06-08T01:03:01.749370Z","shell.execute_reply":"2021-06-08T01:03:02.151106Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Model Construction\n\n1. build encoder","metadata":{}},{"cell_type":"code","source":"import tensorflow.keras.layers\nimport tensorflow.keras.models\n\nlatent_dim = 2\n\n#encoder structure: \nx = tensorflow.keras.layers.Input(shape=(784), name=\"encoder_input\")\n\nencoder_dense_layer1 = tensorflow.keras.layers.Dense(units=300, name=\"encoder_dense_1\")(x)\nencoder_activ_layer1 = tensorflow.keras.layers.LeakyReLU(name=\"encoder_leakyrelu_1\")(encoder_dense_layer1)\n\nencoder_dense_layer2 = tensorflow.keras.layers.Dense(units=latent_dim, name=\"encoder_dense_2\")(encoder_activ_layer1)\nencoder_output = tensorflow.keras.layers.LeakyReLU(name=\"encoder_output\")(encoder_dense_layer2)\n\nencoder = tensorflow.keras.models.Model(x, encoder_output, name=\"encoder_model\")","metadata":{"execution":{"iopub.status.busy":"2021-06-08T01:05:48.677863Z","iopub.execute_input":"2021-06-08T01:05:48.678322Z","iopub.status.idle":"2021-06-08T01:05:48.717565Z","shell.execute_reply.started":"2021-06-08T01:05:48.678286Z","shell.execute_reply":"2021-06-08T01:05:48.716032Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"encoder.summary()","metadata":{"execution":{"iopub.status.busy":"2021-06-08T01:05:58.462528Z","iopub.execute_input":"2021-06-08T01:05:58.462997Z","iopub.status.idle":"2021-06-08T01:05:58.472527Z","shell.execute_reply.started":"2021-06-08T01:05:58.462948Z","shell.execute_reply":"2021-06-08T01:05:58.469862Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"2. build Decoder","metadata":{}},{"cell_type":"code","source":"#decoder developed to reconstruct the image - 784 pixels\n\ndecoder_input = tensorflow.keras.layers.Input(shape=(2), name=\"decoder_input\")\n\ndecoder_dense_layer1 = tensorflow.keras.layers.Dense(units=300, name=\"decoder_dense_1\")(decoder_input)\ndecoder_activ_layer1 = tensorflow.keras.layers.LeakyReLU(name=\"decoder_leakyrelu_1\")(decoder_dense_layer1)\n\ndecoder_dense_layer2 = tensorflow.keras.layers.Dense(units=784, name=\"decoder_dense_2\")(decoder_activ_layer1)\ndecoder_output = tensorflow.keras.layers.LeakyReLU(name=\"decoder_output\")(decoder_dense_layer2)\n\ndecoder = tensorflow.keras.models.Model(decoder_input, decoder_output, name=\"decoder_model\")","metadata":{"execution":{"iopub.status.busy":"2021-06-08T01:08:14.893892Z","iopub.execute_input":"2021-06-08T01:08:14.894586Z","iopub.status.idle":"2021-06-08T01:08:14.931196Z","shell.execute_reply.started":"2021-06-08T01:08:14.894546Z","shell.execute_reply":"2021-06-08T01:08:14.929967Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Samping function - \n\ndef sampling(args):\n    z_mu, z_log_sigma = args\n    epsilon = K.random_normal(shape=(K.shape(z_mu)[0], latent_dim),\n                              mean=0., stddev=1.)\n    return z_mu + K.exp(z_log_sigma) * epsilon\n\n# sample vector from the latent distribution\nz = layers.Lambda(sampling)([z_mu, z_log_sigma])","metadata":{"execution":{"iopub.status.busy":"2021-06-07T22:24:04.966557Z","iopub.execute_input":"2021-06-07T22:24:04.966986Z","iopub.status.idle":"2021-06-07T22:24:04.991390Z","shell.execute_reply.started":"2021-06-07T22:24:04.966949Z","shell.execute_reply":"2021-06-07T22:24:04.990249Z"},"jupyter":{"source_hidden":true},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"decoder.summary()","metadata":{"execution":{"iopub.status.busy":"2021-06-08T01:08:23.479167Z","iopub.execute_input":"2021-06-08T01:08:23.479579Z","iopub.status.idle":"2021-06-08T01:08:23.488988Z","shell.execute_reply.started":"2021-06-08T01:08:23.479543Z","shell.execute_reply":"2021-06-08T01:08:23.487721Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#compile the autocoder\n\nae_input = tensorflow.keras.layers.Input(shape=(784), name=\"ae_input\")\nae_encoder_output = encoder(ae_input)\nae_decoder_output = decoder(ae_encoder_output)\n\nautoencoder = tensorflow.keras.models.Model(ae_input, ae_decoder_output, name=\"AE\")","metadata":{"execution":{"iopub.status.busy":"2021-06-08T01:11:01.254735Z","iopub.execute_input":"2021-06-08T01:11:01.255405Z","iopub.status.idle":"2021-06-08T01:11:01.294099Z","shell.execute_reply.started":"2021-06-08T01:11:01.255359Z","shell.execute_reply":"2021-06-08T01:11:01.292736Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"autoencoder.summary()","metadata":{"execution":{"iopub.status.busy":"2021-06-08T01:11:02.949301Z","iopub.execute_input":"2021-06-08T01:11:02.949920Z","iopub.status.idle":"2021-06-08T01:11:02.961218Z","shell.execute_reply.started":"2021-06-08T01:11:02.949885Z","shell.execute_reply":"2021-06-08T01:11:02.959622Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#compile the model with optimizer and loss function\n\nimport tensorflow.keras.optimizers  \nautoencoder.compile(loss=\"mse\", optimizer=tensorflow.keras.optimizers.Adam(lr=0.0005))","metadata":{"execution":{"iopub.status.busy":"2021-06-08T01:15:20.177007Z","iopub.execute_input":"2021-06-08T01:15:20.177785Z","iopub.status.idle":"2021-06-08T01:15:20.193859Z","shell.execute_reply.started":"2021-06-08T01:15:20.177744Z","shell.execute_reply":"2021-06-08T01:15:20.192494Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#train the model with whole training dataset and evaluate with validation dataset\nhistory = autoencoder.fit(x_trn, x_trn, epochs = 50, batch_size = 256, shuffle=True, validation_data = (x_val, x_val))","metadata":{"execution":{"iopub.status.busy":"2021-06-08T02:02:32.962139Z","iopub.execute_input":"2021-06-08T02:02:32.962612Z","iopub.status.idle":"2021-06-08T02:04:11.031552Z","shell.execute_reply.started":"2021-06-08T02:02:32.962577Z","shell.execute_reply":"2021-06-08T02:04:11.030421Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"h_2 = history.history['val_loss']\nh_1 = history.history['loss']\n\nplt.plot(h_1, \"r\", h_2, \"g\")","metadata":{"execution":{"iopub.status.busy":"2021-06-08T02:05:25.192815Z","iopub.execute_input":"2021-06-08T02:05:25.193218Z","iopub.status.idle":"2021-06-08T02:05:25.335732Z","shell.execute_reply.started":"2021-06-08T02:05:25.193183Z","shell.execute_reply":"2021-06-08T02:05:25.334710Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"from the result above, we can tell that the loss is below 5%, which suggest good amount of information has been preserved after the encoding - decoding process","metadata":{}},{"cell_type":"code","source":"\n#predict on training dataset and compare the results with actual\nencoded_images = encoder.predict(x_trn)\ndecoded_images = decoder.predict(encoded_images)\n\ndecoded_images_np = np.reshape(decoded_images, newshape=(decoded_images.shape[0], 28, 28))","metadata":{"execution":{"iopub.status.busy":"2021-06-08T01:22:40.225140Z","iopub.execute_input":"2021-06-08T01:22:40.225647Z","iopub.status.idle":"2021-06-08T01:22:43.354226Z","shell.execute_reply.started":"2021-06-08T01:22:40.225604Z","shell.execute_reply":"2021-06-08T01:22:43.353386Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n \n#need to convert x_trn shape as well\nx_trn_plot = np.asarray(x_trn).reshape(-1, 28, 28)\n\n\nimage_to_test = 6\nfor im_ind in range(image_to_test):\n    plot_ind = im_ind*2 + 1\n    rand_ind = np.random.randint(low=0, high=x_trn_plot.shape[0])\n    plt.subplot(image_to_test, 2, plot_ind)\n    plt.imshow(x_trn_plot[rand_ind, :, :], cmap=\"gray\")\n    plt.subplot(image_to_test, 2, plot_ind+1)\n    plt.imshow(decoded_images_np[rand_ind, :, :], cmap=\"gray\")","metadata":{"execution":{"iopub.status.busy":"2021-06-08T01:27:11.375648Z","iopub.execute_input":"2021-06-08T01:27:11.376260Z","iopub.status.idle":"2021-06-08T01:27:12.850896Z","shell.execute_reply.started":"2021-06-08T01:27:11.376220Z","shell.execute_reply":"2021-06-08T01:27:12.850097Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"The reconstructed images are a little bit fuzzy, but it is pretty close to original images with minor loss of data","metadata":{}},{"cell_type":"code","source":"#we can also see how autoencoder learn from the data, and categorize different images to catogories\n\nplt.figure(figsize = (15, 10))\nplt.scatter(encoded_images[:, 0], encoded_images[:, 1], c=y_trn) \nplt.colorbar()","metadata":{"execution":{"iopub.status.busy":"2021-06-08T01:30:37.426861Z","iopub.execute_input":"2021-06-08T01:30:37.427243Z","iopub.status.idle":"2021-06-08T01:30:38.362171Z","shell.execute_reply.started":"2021-06-08T01:30:37.427208Z","shell.execute_reply":"2021-06-08T01:30:38.361117Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#build classifier based on encoder","metadata":{}},{"cell_type":"code","source":"#build classifier layer\n\nclf_input = tensorflow.keras.layers.Input(shape=(2), name=\"classifier_input\") \n\nclf_intermediate = tensorflow.keras.layers.Dense(32, activation='relu')(clf_input)\nclf = tensorflow.keras.layers.Dense(10, activation='softmax')(clf_intermediate)\n# this model classifies encoding vectors\nencoding_clf_model = Model(clf_input, clf, name=\"encoder_classifier\")\n\n# this model classifies images\nclassifier_model = Model(clf_input, encoding_clf_model(clf_input), name=\"image_classifier\")\nclassifier_model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['categorical_accuracy'])","metadata":{"execution":{"iopub.status.busy":"2021-06-08T02:29:22.095009Z","iopub.execute_input":"2021-06-08T02:29:22.095453Z","iopub.status.idle":"2021-06-08T02:29:22.148482Z","shell.execute_reply.started":"2021-06-08T02:29:22.095418Z","shell.execute_reply":"2021-06-08T02:29:22.147423Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#compile encoder_classifier model\n\neclf_input = tensorflow.keras.layers.Input(shape=(784), name=\"ae_input\")\neclf_encoder_output = encoder(eclf_input)\neclf_classify_output = classifier_model(eclf_encoder_output)\n\nencoder_classifier = tensorflow.keras.models.Model(eclf_input, eclf_classify_output, name=\"eclf\")\nencoder_classifier.summary()","metadata":{"execution":{"iopub.status.busy":"2021-06-08T02:32:18.874565Z","iopub.execute_input":"2021-06-08T02:32:18.875070Z","iopub.status.idle":"2021-06-08T02:32:18.913702Z","shell.execute_reply.started":"2021-06-08T02:32:18.875028Z","shell.execute_reply":"2021-06-08T02:32:18.912654Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"encoder_classifier.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2021-06-08T02:39:15.650459Z","iopub.execute_input":"2021-06-08T02:39:15.650958Z","iopub.status.idle":"2021-06-08T02:39:15.669795Z","shell.execute_reply.started":"2021-06-08T02:39:15.650903Z","shell.execute_reply":"2021-06-08T02:39:15.668355Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nencoder_classifier.fit(\n    x_trn, y_trn,\n    epochs=50,\n    batch_size=128,\n    shuffle=True,\n    validation_data=(x_val, y_val)\n)","metadata":{"execution":{"iopub.status.busy":"2021-06-08T02:39:34.400916Z","iopub.execute_input":"2021-06-08T02:39:34.401326Z","iopub.status.idle":"2021-06-08T02:40:44.576504Z","shell.execute_reply.started":"2021-06-08T02:39:34.401294Z","shell.execute_reply":"2021-06-08T02:40:44.575543Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_test.shape","metadata":{"execution":{"iopub.status.busy":"2021-06-08T02:52:19.810577Z","iopub.execute_input":"2021-06-08T02:52:19.811015Z","iopub.status.idle":"2021-06-08T02:52:19.816394Z","shell.execute_reply.started":"2021-06-08T02:52:19.810981Z","shell.execute_reply":"2021-06-08T02:52:19.815570Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_pred_10 = encoder_classifier.predict(x_test)\ny_test_pred = np.argmax(y_pred_10, axis=1)\n\ny_test_pred[0:10]\n","metadata":{"execution":{"iopub.status.busy":"2021-06-08T02:56:50.025051Z","iopub.execute_input":"2021-06-08T02:56:50.025480Z","iopub.status.idle":"2021-06-08T02:56:51.440789Z","shell.execute_reply.started":"2021-06-08T02:56:50.025448Z","shell.execute_reply":"2021-06-08T02:56:51.439878Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def plot_images(x, y=None):\n    \"\"\"Plot all images in x, with optional labels given by y.\n\n    Expect x.shape == (n, h, w), where n = number images, h = image height, w = image width\n    \"\"\"\n    plt.figure(figsize=(20, 4))\n    n = x.shape[0]\n    for i in range(n):\n        image = x[i]\n        ax = plt.subplot(2, n, i + 1)\n        plt.imshow(x[i])\n        plt.gray()\n        if y is not None:\n            label = y[i]\n            plt.title(label)\n        ax.get_xaxis().set_visible(False)\n        ax.get_yaxis().set_visible(False)\n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2021-06-08T03:00:47.946524Z","iopub.execute_input":"2021-06-08T03:00:47.946988Z","iopub.status.idle":"2021-06-08T03:00:47.955386Z","shell.execute_reply.started":"2021-06-08T03:00:47.946950Z","shell.execute_reply":"2021-06-08T03:00:47.954233Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#let's test the result\nn = 20\nidx = np.random.choice(len(x_test), size=n, replace=False)\nplot_test = np.asarray(x_test).reshape(-1, 28, 28, 1)\n\nprint(\"Predicted labels: \")\nplot_images(plot_test[idx], y_test_pred[idx])","metadata":{"execution":{"iopub.status.busy":"2021-06-08T03:00:48.524575Z","iopub.execute_input":"2021-06-08T03:00:48.525235Z","iopub.status.idle":"2021-06-08T03:00:50.103373Z","shell.execute_reply.started":"2021-06-08T03:00:48.525195Z","shell.execute_reply":"2021-06-08T03:00:50.102512Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"We can see the encoder classifer achieves pretty accurate result","metadata":{}},{"cell_type":"code","source":"#save the result to submission file\nimageid = np.arange(1,len(y_test_pred)+1)\n\nresult_eclf = pd.DataFrame({'imageid':imageid, 'Label':y_test_pred})\n\nresult_eclf.to_csv('result_eclf', index=False)","metadata":{"execution":{"iopub.status.busy":"2021-06-08T03:03:19.804305Z","iopub.execute_input":"2021-06-08T03:03:19.804929Z","iopub.status.idle":"2021-06-08T03:03:19.867591Z","shell.execute_reply.started":"2021-06-08T03:03:19.804891Z","shell.execute_reply":"2021-06-08T03:03:19.866733Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#screenshot of submission to Kaggle\n\n#link to the notebook on Kaggle\n#https://www.kaggle.com/cuihua2020/simple-autoencoder-digit-recognizer","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}