{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":3004,"databundleVersionId":861823,"sourceType":"competition"}],"dockerImageVersionId":30715,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"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":"2024-06-02T08:50:21.920559Z","iopub.execute_input":"2024-06-02T08:50:21.920948Z","iopub.status.idle":"2024-06-02T08:50:22.288103Z","shell.execute_reply.started":"2024-06-02T08:50:21.920918Z","shell.execute_reply":"2024-06-02T08:50:22.286958Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df = pd.read_csv(\"/kaggle/input/digit-recognizer/train.csv\")\ndf.sample(3)","metadata":{"execution":{"iopub.status.busy":"2024-06-02T08:50:22.289968Z","iopub.execute_input":"2024-06-02T08:50:22.290420Z","iopub.status.idle":"2024-06-02T08:50:25.821026Z","shell.execute_reply.started":"2024-06-02T08:50:22.290391Z","shell.execute_reply":"2024-06-02T08:50:25.819838Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.shape","metadata":{"execution":{"iopub.status.busy":"2024-06-02T08:50:25.822925Z","iopub.execute_input":"2024-06-02T08:50:25.823700Z","iopub.status.idle":"2024-06-02T08:50:25.831868Z","shell.execute_reply.started":"2024-06-02T08:50:25.823660Z","shell.execute_reply":"2024-06-02T08:50:25.830748Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n","metadata":{"execution":{"iopub.status.busy":"2024-06-02T08:50:25.835085Z","iopub.execute_input":"2024-06-02T08:50:25.836262Z","iopub.status.idle":"2024-06-02T08:50:25.843857Z","shell.execute_reply.started":"2024-06-02T08:50:25.836202Z","shell.execute_reply":"2024-06-02T08:50:25.842638Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plt.imshow(df.iloc[41283,1:].values.reshape(28,28))  #Check a random sample","metadata":{"execution":{"iopub.status.busy":"2024-06-02T08:50:25.845668Z","iopub.execute_input":"2024-06-02T08:50:25.846077Z","iopub.status.idle":"2024-06-02T08:50:26.136673Z","shell.execute_reply.started":"2024-06-02T08:50:25.846039Z","shell.execute_reply":"2024-06-02T08:50:26.135312Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#deviding data into training and test\nX = df.iloc[:,1:]\ny = df.iloc[:,0]","metadata":{"execution":{"iopub.status.busy":"2024-06-02T08:50:26.138943Z","iopub.execute_input":"2024-06-02T08:50:26.139701Z","iopub.status.idle":"2024-06-02T08:50:26.145512Z","shell.execute_reply.started":"2024-06-02T08:50:26.139661Z","shell.execute_reply":"2024-06-02T08:50:26.144466Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state =42)","metadata":{"execution":{"iopub.status.busy":"2024-06-02T08:50:26.147168Z","iopub.execute_input":"2024-06-02T08:50:26.148045Z","iopub.status.idle":"2024-06-02T08:50:27.130972Z","shell.execute_reply.started":"2024-06-02T08:50:26.148009Z","shell.execute_reply":"2024-06-02T08:50:27.129775Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.metrics import accuracy_score","metadata":{"execution":{"iopub.status.busy":"2024-06-02T08:50:27.132270Z","iopub.execute_input":"2024-06-02T08:50:27.132603Z","iopub.status.idle":"2024-06-02T08:50:27.305786Z","shell.execute_reply.started":"2024-06-02T08:50:27.132574Z","shell.execute_reply":"2024-06-02T08:50:27.304686Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"knn = KNeighborsClassifier()\nknn.fit(X_train, y_train)","metadata":{"execution":{"iopub.status.busy":"2024-06-02T08:50:27.306955Z","iopub.execute_input":"2024-06-02T08:50:27.307267Z","iopub.status.idle":"2024-06-02T08:50:27.485937Z","shell.execute_reply.started":"2024-06-02T08:50:27.307237Z","shell.execute_reply":"2024-06-02T08:50:27.484478Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"y_pred = knn.predict(X_test)","metadata":{"execution":{"iopub.status.busy":"2024-06-02T08:50:27.490075Z","iopub.execute_input":"2024-06-02T08:50:27.490457Z","iopub.status.idle":"2024-06-02T08:50:39.836161Z","shell.execute_reply.started":"2024-06-02T08:50:27.490426Z","shell.execute_reply":"2024-06-02T08:50:39.835052Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"score = accuracy_score(y_pred, y_test)\nscore","metadata":{"execution":{"iopub.status.busy":"2024-06-02T08:50:39.837701Z","iopub.execute_input":"2024-06-02T08:50:39.838111Z","iopub.status.idle":"2024-06-02T08:50:39.847396Z","shell.execute_reply.started":"2024-06-02T08:50:39.838074Z","shell.execute_reply":"2024-06-02T08:50:39.846145Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"In above steps, we get a good accuracy scores with 784 feature.\nNow with the help of PCA, we'll try to reduce the features and match the accuracy score.","metadata":{}},{"cell_type":"code","source":"#In PCA, 1st step is data standarization or mean cenerization\nfrom sklearn.preprocessing import StandardScaler\nscaler = StandardScaler()","metadata":{"execution":{"iopub.status.busy":"2024-06-02T08:50:39.848309Z","iopub.execute_input":"2024-06-02T08:50:39.848593Z","iopub.status.idle":"2024-06-02T08:50:39.857741Z","shell.execute_reply.started":"2024-06-02T08:50:39.848569Z","shell.execute_reply":"2024-06-02T08:50:39.856739Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"X_train = scaler.fit_transform(X_train)\nX_test = scaler.transform(X_test)","metadata":{"execution":{"iopub.status.busy":"2024-06-02T08:50:39.859065Z","iopub.execute_input":"2024-06-02T08:50:39.859654Z","iopub.status.idle":"2024-06-02T08:50:40.356116Z","shell.execute_reply.started":"2024-06-02T08:50:39.859546Z","shell.execute_reply":"2024-06-02T08:50:40.354743Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.decomposition import PCA\npca = PCA(n_components = 100)\n#n_components is the number of featured requreired,here \"None\" will result in 784 PCA\n#If we take 100 in n_components, it reasults in the Top 100 principle components\n\nX_train_withPCA = pca.fit_transform(X_train)\nX_test_withPCA = pca.transform(X_test)\n\nX_train_withPCA.shape","metadata":{"execution":{"iopub.status.busy":"2024-06-02T08:50:40.357448Z","iopub.execute_input":"2024-06-02T08:50:40.357761Z","iopub.status.idle":"2024-06-02T08:50:43.898952Z","shell.execute_reply.started":"2024-06-02T08:50:40.357735Z","shell.execute_reply":"2024-06-02T08:50:43.897744Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#We'll again train a KNN model and check accuracy\nknn = KNeighborsClassifier()\n\nknn.fit(X_train_withPCA, y_train)","metadata":{"execution":{"iopub.status.busy":"2024-06-02T08:50:43.900590Z","iopub.execute_input":"2024-06-02T08:50:43.901281Z","iopub.status.idle":"2024-06-02T08:50:43.942082Z","shell.execute_reply.started":"2024-06-02T08:50:43.901221Z","shell.execute_reply":"2024-06-02T08:50:43.941169Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"y_pred_withPCA = knn.predict(X_test_withPCA)\nscore = accuracy_score(y_pred_withPCA, y_test)\nscore","metadata":{"execution":{"iopub.status.busy":"2024-06-02T08:50:43.943740Z","iopub.execute_input":"2024-06-02T08:50:43.944477Z","iopub.status.idle":"2024-06-02T08:50:46.027594Z","shell.execute_reply.started":"2024-06-02T08:50:43.944436Z","shell.execute_reply":"2024-06-02T08:50:46.026360Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"We got almost same accuracy with 100 Principle components, instead of 784 feature.\n\n","metadata":{}},{"cell_type":"code","source":"pca.explained_variance_\n#explained_variance_ are the eigen values \n#Since,we've taken n_components = 100, it wil result in 100 eigen values","metadata":{"execution":{"iopub.status.busy":"2024-06-02T08:50:46.028908Z","iopub.execute_input":"2024-06-02T08:50:46.029242Z","iopub.status.idle":"2024-06-02T08:50:46.038870Z","shell.execute_reply.started":"2024-06-02T08:50:46.029200Z","shell.execute_reply":"2024-06-02T08:50:46.037720Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"pca.components_\n\n#components_ will show the eigen vectors\n#Since,we've taken n_components = 100, it wil result in 100 eigen vectors","metadata":{"execution":{"iopub.status.busy":"2024-06-02T08:53:40.201572Z","iopub.execute_input":"2024-06-02T08:53:40.201975Z","iopub.status.idle":"2024-06-02T08:53:40.210101Z","shell.execute_reply.started":"2024-06-02T08:53:40.201936Z","shell.execute_reply":"2024-06-02T08:53:40.209178Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"pca.components_.shape","metadata":{"execution":{"iopub.status.busy":"2024-06-02T08:55:13.680419Z","iopub.execute_input":"2024-06-02T08:55:13.680789Z","iopub.status.idle":"2024-06-02T08:55:13.688195Z","shell.execute_reply.started":"2024-06-02T08:55:13.680762Z","shell.execute_reply":"2024-06-02T08:55:13.686963Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"**Let's find out the optimum number of principle components:**\n\nFor this, we have to convert eigen values in percentage to undertand, how much variance in the data is explained by each eigen value. Now, we add the percentage of each eigen values unless we reach atleast 90%.","metadata":{}},{"cell_type":"code","source":"pca.explained_variance_ratio_ * 100","metadata":{"execution":{"iopub.status.busy":"2024-06-02T09:05:54.821160Z","iopub.execute_input":"2024-06-02T09:05:54.821538Z","iopub.status.idle":"2024-06-02T09:05:54.828876Z","shell.execute_reply.started":"2024-06-02T09:05:54.821512Z","shell.execute_reply":"2024-06-02T09:05:54.827918Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"First Eigen value explains 5.78519225% variance in the data, Second  Eigen value explains 4.14926968% variance and so on.\n**np.cumsum** can be used to find the cumulative sum.","metadata":{}},{"cell_type":"code","source":"np.cumsum(pca.explained_variance_ratio_ * 100)","metadata":{"execution":{"iopub.status.busy":"2024-06-02T09:11:53.280891Z","iopub.execute_input":"2024-06-02T09:11:53.281285Z","iopub.status.idle":"2024-06-02T09:11:53.290197Z","shell.execute_reply.started":"2024-06-02T09:11:53.281256Z","shell.execute_reply":"2024-06-02T09:11:53.289251Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#We can plot the data to see which is the optimal point\nplt.plot(np.cumsum(pca.explained_variance_ratio_ * 100))","metadata":{"execution":{"iopub.status.busy":"2024-06-02T09:15:30.701608Z","iopub.execute_input":"2024-06-02T09:15:30.702014Z","iopub.status.idle":"2024-06-02T09:15:30.967294Z","shell.execute_reply.started":"2024-06-02T09:15:30.701956Z","shell.execute_reply":"2024-06-02T09:15:30.966060Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Since we have taken n_components = 100, it's explaining max 71.82042267% variance.","metadata":{}}]}