{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"_kg_hide-output":true,"_kg_hide-input":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\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","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"_kg_hide-output":true,"trusted":true},"cell_type":"code","source":"!pip install seaborn --upgrade \n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"markdown","source":"<h1 style='background:lightblue; border:0; color:black'><center>UMAP for classification problems</center></h1>"},{"metadata":{},"cell_type":"markdown","source":"The objective of this notebook is to give an introduction to classification problems using an alternative dimension reduction technique to PCA, the  Uniform Manifold\nApproximation and Projection for Dimension Reduction (UMAP). The notebook will focus on analyzing the MNIST classification problem, using the classical methods with UMAP and comparing with the methods based on neural network like ANN, CNN. First of all, we do not expect that this methodology can have a better score than the ANN and the CNN, especially of the last one, which has been prove be one of the best methods for image analysis, but we can expect to have a really good score with a much lower time.\n\nWe will start by comparing the first PC components with the UMAP component. We will use a supervised version of the UMAP, usually known as SUMAP. More information in the [link](https://arxiv.org/pdf/1802.03426.pdf).\n"},{"metadata":{},"cell_type":"markdown","source":"<h1 style='background:lightblue; border:0; color:black'><center>UMAP vs PCA</center></h1>"},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport umap\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom sklearn.decomposition import PCA\nfrom sklearn import svm, datasets\nimport tensorflow as tf\nfrom sklearn.svm import SVC\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.ensemble import RandomForestClassifier","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"MNIST=pd.read_csv('../input/digit-recognizer/train.csv')\nMNIST_df=MNIST.drop(['label'],axis=1)\nMNIST_df/255\nMNIST_label=MNIST['label']","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Generally, I use the sklearn function train_test_split to create our train and test set, however in this case, as it is an illustrative notebook, we will split our data set as follows."},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train, y_train=MNIST_df[0:29000].values,MNIST_label[0:29000].values\nX_test, y_test=MNIST_df[29000:42000].values,MNIST_label[29000:42000].values\nUn_component=5 #Nº of UMAP components","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\nmapper=umap.UMAP(n_neighbors=5,n_components=Un_component,random_state=12345).fit(X_train,y=y_train)\numap_component= mapper.transform(X_train)\numap_df = pd.DataFrame(data=umap_component,columns=['component_%i' % i for i in range(Un_component)])\numap_df=umap_df.join(pd.DataFrame(y_train,columns=['label']))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"As we can see, calculating the UMAP components is computationally more expensive than PCA. We  calculate  the UMAP components for the test set for future sections. "},{"metadata":{"trusted":true},"cell_type":"code","source":"umap_component_test= mapper.transform(X_test)\numap_df_test = pd.DataFrame(data=umap_component_test,columns=['component_%i' % i for i in range(Un_component)])\numap_df_test=umap_df_test.join(pd.DataFrame(y_test,columns=['label']))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Our goal in this section is to compare the UMAP component and the PCA, so the next step is calculate the PCA."},{"metadata":{"trusted":true},"cell_type":"code","source":"# Run The PCA\nPCn_components=3\npca = PCA(n_components=PCn_components)\npca.fit(X_train)\n \n# Store results of PCA in a data frame\npca_df=pd.DataFrame(pca.transform(MNIST_df), columns=['component_%i' % i for i in range(PCn_components)])\npca_df=pca_df.join(pd.DataFrame(y_train,columns=['label']))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"To look if there is any difference between the two methods, we make the scatter plot of the first two components."},{"metadata":{"trusted":true},"cell_type":"code","source":"sns.relplot(x=\"component_0\", y=\"component_1\", hue=\"label\", data=umap_df[300:3000], palette=\"Paired\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\nsns.relplot(x=\"component_0\", y=\"component_1\", hue=\"label\", data=pca_df[300:3000], palette=\"Paired\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"It is obvious that there is a big difference between both case, but what happens if we use one more component?"},{"metadata":{"trusted":true},"cell_type":"code","source":"# define the colormap\ncmap = plt.cm.jet\n# extract all colors from the .jet map\ncmaplist = [cmap(i) for i in range(cmap.N)]\n# create the new map\ncmap = cmap.from_list('Custom cmap', cmaplist, cmap.N)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%matplotlib notebook\n%matplotlib inline\n\n\nfrom mpl_toolkits.mplot3d import axes3d    \n\n\n\nfig = plt.figure(figsize=(12,10))\nax = fig.add_subplot(111, projection='3d')\n\n\n# For each set of style and range settings, plot n random points in the box\n# defined by x in [23, 32], y in [0, 100], z in [zlow, zhigh].\nxs = umap_df['component_0']\nys = umap_df['component_1']\nzs = umap_df['component_2']\nm=umap_df['label']\n\n\nax.scatter(xs[0:300], ys[0:300], zs[0:300], c=m[0:300],cmap=cmap)\n\nax.set_xlabel('X Label')\nax.set_ylabel('Y Label')\nax.set_zlabel('Z Label')\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%matplotlib notebook\n%matplotlib inline\n\nfrom mpl_toolkits.mplot3d import axes3d    \n\nfig = plt.figure(figsize=(12,10))\nax = fig.add_subplot(111, projection='3d')\n\n\n# For each set of style and range settings, plot n random points in the box\n# defined by x in [23, 32], y in [0, 100], z in [zlow, zhigh].\nxs = pca_df['component_0']\nys = pca_df['component_1']\nzs = pca_df['component_2']\nm=pca_df['label']\nax.scatter(xs[0:300], ys[0:300], zs[0:300], c=m[0:300],cmap=cmap)\n\nax.set_xlabel('X Label')\nax.set_ylabel('Y Label')\nax.set_zlabel('Z Label')\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Things get even more interesting. The separation between labels is even bigger in this case. It is obvious that using the UMAP component will be a great improvement over using PCA."},{"metadata":{},"cell_type":"markdown","source":"<h1 style='background:lightblue; border:0; color:black'><center>Clasic Clasiffication</center></h1>"},{"metadata":{},"cell_type":"markdown","source":"## SVM"},{"metadata":{"trusted":true},"cell_type":"code","source":"X,y=umap_component,umap_df['label']\nX_test_umap, y_test_umap=umap_component_test,umap_df_test['label']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"svm = SVC(kernel='linear', random_state=1, gamma=0.10, C=10.0)\nsvm.fit(X, y)\ny_pred=svm.predict(X_test_umap)\naccuracy_score(y_pred,y_test)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## KNN"},{"metadata":{"trusted":true},"cell_type":"code","source":"\nknn = KNeighborsClassifier(n_neighbors=5, p=2, metric='minkowski')\nknn.fit(X, y)\ny_pred=knn.predict(X_test_umap)\naccuracy_score(y_pred,y_test)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# LR"},{"metadata":{"trusted":true},"cell_type":"code","source":"lr = LogisticRegression(C=1000.0, random_state=0)\nlr.fit(X, y)\ny_pred=lr.predict(X_test_umap)\naccuracy_score(y_pred,y_test)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Random forest"},{"metadata":{"trusted":true},"cell_type":"code","source":"forest = RandomForestClassifier(criterion='entropy',n_estimators=25,random_state=1,n_jobs=2)\nforest.fit(X, y)\ny_pred=forest.predict(X_test_umap)\naccuracy_score(y_pred,y_test)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# ANN"},{"metadata":{},"cell_type":"markdown","source":"Creating the dataset"},{"metadata":{"trusted":true},"cell_type":"code","source":"batch_size = 2\nds_x = tf.data.Dataset.from_tensor_slices(X)\nds_y = tf.data.Dataset.from_tensor_slices(y)\nds_joint=tf.data.Dataset.zip((ds_x, ds_y))\nds=ds_joint.shuffle(buffer_size=29000)\nds = ds.repeat()\nds = ds.batch(batch_size=batch_size)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ann_model = tf.keras.Sequential([tf.keras.layers.Dense(16, activation='sigmoid',name='fc1', input_shape=(None,5)),\n                                  tf.keras.layers.Dense(10, name='fc2',activation='softmax')])\nann_model.compile(optimizer='adam',loss='sparse_categorical_crossentropy',metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true},"cell_type":"code","source":"%%time\nsteps_per_epoch=29000/2\nhistory=ann_model.fit(ds, epochs=1,steps_per_epoch=steps_per_epoch)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"hist = history.history\nfig = plt.figure(figsize=(12, 5))\nax = fig.add_subplot(1, 2, 1)\nax.plot(hist['loss'], lw=3)\nax.set_title('Training loss', size=15)\nax.set_xlabel('Epoch', size=15)\nax.tick_params(axis='both', which='major', labelsize=15)\nax = fig.add_subplot(1, 2, 2)\nax.plot(hist['accuracy'], lw=3)\nax.set_title('Training accuracy', size=15)\nax.set_xlabel('Epoch', size=15)\nax.tick_params(axis='both', which='major', labelsize=15)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_pred_probs=ann_model.predict(X_test_umap)\ny_pred_ann=np.empty(13000)\nfor i in range(13000):\n    y_pred_ann[i]=np.where(y_pred_probs[i]==np.amax(y_pred_probs[i]))[0]\n\naccuracy_score(y_pred_ann,y_test)","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}