{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":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 in \n\nimport 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\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.decomposition import PCA\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"../input\"))\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Load The Data "},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"data = pd.read_csv(\"../input/train.csv\")\n\ndata.head(5)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data.shape","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Seperating labels from original data"},{"metadata":{"trusted":true},"cell_type":"code","source":"label = data['label']\nfinal_data= data.drop('label', axis=1)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Visualising data samples"},{"metadata":{"trusted":true},"cell_type":"code","source":"fig = plt.figure(figsize=(20,15))\n\nfor i in range(1,10,1):\n    \n    plt.subplot(3,3,i)\n    image = final_data.iloc[i].as_matrix().reshape(28,28)\n    plt.imshow(image, cmap='gray')  \n    plt.xlabel(label[i])\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# 2D visualisation of Data using PCA\n\n*  First we will standardise the data.\n*  Then compute the Co-Variance Matrix of the data\n*  Then Compute Eigen values and Eigen Vectors\n*  projecting the original data sample on the plane formed by two principal eigen vectors by vector-vector multiplication."},{"metadata":{"trusted":true},"cell_type":"code","source":"# STEP-1\nstd_data = StandardScaler().fit_transform(final_data)\nprint(std_data.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# STEP-2\nCoVMat = np.matmul(std_data.T , std_data)\nprint(CoVMat.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# STEP-3\nfrom scipy.linalg import eigh\n\n# the parameter 'eigvals' is defined (low value to heigh value) \n# eigh function will return the eigen values in asending order\n# this code generates only the top 2 (782 and 783) eigenvalues.\nvalues, vectors = eigh(CoVMat , eigvals=(782,783)) \n\nprint(\"The shape of Eigen Vectors\", vectors.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#STEP-4\nnew_data = np.matmul(vectors.T , std_data.T)\nprint(\"The shape of new data\", new_data.shape)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Creating new dataframe from new coordinates "},{"metadata":{"trusted":true},"cell_type":"code","source":"stacking = np.vstack((new_data , label)).T\ndataframe = pd.DataFrame(data=stacking , columns=(\"1st component\", \"2nd Component\" , \"Labels\"))\n\ndataframe.head(5)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Plotting the data"},{"metadata":{"trusted":true},"cell_type":"code","source":"import seaborn as sns\nsns.FacetGrid(dataframe , hue='Labels', height=8).map(plt.scatter, '1st component' , '2nd Component').add_legend()\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# PCA using Scikit Learn"},{"metadata":{"trusted":true},"cell_type":"code","source":"pca = PCA(n_components=2).fit_transform(std_data)\nprint(\"The shape of PCA reduced \" ,pca.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"stacking = np.vstack((pca.T , label)).T\ndataframe = pd.DataFrame(data=stacking , columns=(\"1st component\", \"2nd Component\" , \"Labels\"))\ndataframe.head(5)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sns.FacetGrid(dataframe , hue='Labels', height=8).map(plt.scatter, '1st component' , '2nd Component').add_legend()\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# PCA for dimensionality reduction (Not Visualisation)"},{"metadata":{"trusted":true},"cell_type":"code","source":"pca = PCA(n_components=784).fit(std_data)\n#print(\"The shape of PCA reduce\", pca.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pca_variance = pca.explained_variance_ratio_\ncumsum_var = np.cumsum(pca_variance)\n\nplt.figure(figsize=(8,6))\nplt.clf()\nplt.plot(cumsum_var, linewidth=2)\nplt.xlabel('n_components')\nplt.ylabel('Cumulative_explained_pca')\nplt.grid()\nplt.axis('tight')\n","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.4","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}