{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","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":30822,"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","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df = pd.read_csv('/kaggle/input/digit-recognizer/train.csv')","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.head()","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.shape","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nplt.imshow(df.iloc[18306,1: ].values.reshape(28,28))","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plt.imshow(df.iloc[13051,1:].values.reshape(28,28))","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"x = df.iloc[:,1:]\ny = df.iloc[:,0]\n","metadata":{"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":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"X_train.shape","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.neighbors import KNeighborsClassifier\nknn = KNeighborsClassifier()","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"knn.fit(X_train,Y_train)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import time\nstart = time.time()\ny_pred = knn.predict(X_test)\nprint(time.time() - start)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.metrics import accuracy_score\naccuracy_score(Y_test,y_pred)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### PCA","metadata":{}},{"cell_type":"code","source":"from sklearn.preprocessing import StandardScaler\nscaler = StandardScaler()","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"X_train = scaler.fit_transform(X_train)\nX_test = scaler.transform(X_test)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.decomposition import PCA\npca = PCA(n_components=784)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"X_train_trf = pca.fit_transform(X_train)\nX_test_trf = pca.transform(X_test)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"knn = KNeighborsClassifier()","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"knn.fit(X_train,Y_train)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"y_pred = knn.predict(X_test_trf)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"accuracy_score(Y_test,y_pred)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for i in range(1,785):\n    pca = PCA(n_components=2)\n    X_train_trf = pca.fit_transform(X_train)\n    X_test_trf = pca.transform(X_test)\n    \n    knn = KNeighborsClassifier()\n    \n    knn.fit(X_train_trf,Y_train)\n    \n    y_pred = knn.predict(X_test_trf)\n    \n    print(accuracy_score(Y_test,y_pred))","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"pca = PCA(n_components=2)\nX_train_trf = pca.fit_transform(X_train)\nX_test_trf = pca.transform(X_test)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"X_train_trf","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import plotly.express as px\nY_train_trf = Y_train.astype(str)\nfig = px.scatter(x=X_train_trf[:,0],\n                y=X_train_trf[:,1],\n                color=Y_train_trf,\n                color_discrete_sequence=px.colors.qualitative.G10)\nfig.show()","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"pca = PCA(n_components=3)\nX_train_trf = pca.fit_transform(X_train)\nX_test_trf = pca.transform(X_test)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"X_train_trf","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import plotly.express as px\ny_train_trf = Y_train.astype(str)\nfig = px.scatter_3d(df, x=X_train_trf[:,0], y=X_train_trf[:,1], z=X_train_trf[:,2],\n              color=Y_train_trf)\nfig.update_layout(\n    margin=dict(l=20, r=20, t=20, b=20),\n    paper_bgcolor=\"LightSteelBlue\",\n)\nfig.show()","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"pca.explained_variance_","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"pca.components_.shape","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"pca.explained_variance_ratio_","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"pca = PCA(n_components=None)\nX_train_trf = pca.fit_transform(X_train)\nX_test_trf = pca.transform(X_test)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"pca.explained_variance_.shape","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"pca.components_.shape","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"np.cumsum(pca.explained_variance_ratio_)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plt.plot(np.cumsum(pca.explained_variance_ratio_))","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"","metadata":{}}]}