{"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":30698,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# Môi trường Python 3 này được cài đặt sẵn nhiều thư viện phân tích hữu ích\n# Nó được xác định bởi hình ảnh Docker kaggle/python: https://github.com/kaggle/docker-python\n# Ví dụ: đây là một số gói hữu ích để tải\n\nimport numpy as np # đại số tuyến tính\nimport pandas as pd # xử lý dữ liệu, I/O tệp CSV (ví dụ: pd.read_csv)\n\n# Tệp dữ liệu đầu vào có sẵn trong thư mục \"../input/\" chỉ đọc\n# Ví dụ: chạy cái này (bằng cách nhấp vào chạy hoặc nhấn Shift + Enter) sẽ liệt kê tất cả các tệp trong thư mục đầu vào\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# Bạn có thể ghi tối đa 20GB vào thư mục hiện tại (/kaggle/working/) được giữ nguyên làm đầu ra khi bạn tạo phiên bản bằng cách sử dụng \"Save & Run All\"\n# Bạn cũng có thể ghi các tệp tạm thời vào /kaggle/temp/, nhưng chúng sẽ không được lưu bên ngoài phiên hiện tại","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-06-10T16:15:12.466462Z","iopub.execute_input":"2024-06-10T16:15:12.467063Z","iopub.status.idle":"2024-06-10T16:15:12.979841Z","shell.execute_reply.started":"2024-06-10T16:15:12.466987Z","shell.execute_reply":"2024-06-10T16:15:12.978810Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 1. Nhập các thư viện cần thiết","metadata":{}},{"cell_type":"code","source":"## NHẬP THƯ VIỆN PYTHON CẦN THIẾT\n\n# Đọc & Khám phá dữ liệu\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import MinMaxScaler\n\n# Phân tích thành phần chính (PCA)\nfrom sklearn.decomposition import PCA\nfrom sklearn.pipeline import Pipeline\nimport plotly.express as px\n\n# K-Bộ phân loại hàng xóm gần nhất (KNN)\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.metrics import classification_report, \\\n    confusion_matrix, ConfusionMatrixDisplay \n\n# VHT\nfrom scipy.ndimage import rotate","metadata":{"execution":{"iopub.status.busy":"2024-06-10T16:15:12.982094Z","iopub.execute_input":"2024-06-10T16:15:12.982539Z","iopub.status.idle":"2024-06-10T16:15:14.916693Z","shell.execute_reply.started":"2024-06-10T16:15:12.982507Z","shell.execute_reply":"2024-06-10T16:15:14.915594Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def func_array1d_rotate2d(Narray1d,rotate_angle,sizePixel):\n\n    N = Narray1d.shape[0]\n\n    Narray1d_rotate = np.zeros(Narray1d.shape)\n    \n    for i in range(N):\n        image = np.reshape(Narray1d[i,:],(sizePixel,sizePixel))\n        rotated_image = rotate(image,rotate_angle, reshape=False)\n        rotated_array1d = np.reshape(rotated_image,(1,-1))\n        Narray1d_rotate[i,:] = rotated_array1d\n        \n    return Narray1d_rotate","metadata":{"execution":{"iopub.status.busy":"2024-06-10T16:15:14.918033Z","iopub.execute_input":"2024-06-10T16:15:14.918454Z","iopub.status.idle":"2024-06-10T16:15:14.927296Z","shell.execute_reply.started":"2024-06-10T16:15:14.918421Z","shell.execute_reply":"2024-06-10T16:15:14.926162Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 2. Đọc dữ liệu và khai thác dữ liệu","metadata":{}},{"cell_type":"code","source":"# Đọc file dữ liệu bằng Pandas\ndf_train = pd.read_csv('/kaggle/input/digit-recognizer/train.csv')\ndf_test =  pd.read_csv('/kaggle/input/digit-recognizer/test.csv')","metadata":{"execution":{"iopub.status.busy":"2024-06-10T16:15:14.928732Z","iopub.execute_input":"2024-06-10T16:15:14.929097Z","iopub.status.idle":"2024-06-10T16:15:21.851531Z","shell.execute_reply.started":"2024-06-10T16:15:14.929063Z","shell.execute_reply":"2024-06-10T16:15:21.850331Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Kiểm tra kích thước của tàu và kiểm tra DataFrames\nprint(\"df_train shape:\", df_train.shape)  # 70%\nprint(\"df_test shape: \", df_test.shape)  # 30%","metadata":{"execution":{"iopub.status.busy":"2024-06-10T16:15:21.855641Z","iopub.execute_input":"2024-06-10T16:15:21.856123Z","iopub.status.idle":"2024-06-10T16:15:21.862106Z","shell.execute_reply.started":"2024-06-10T16:15:21.856088Z","shell.execute_reply":"2024-06-10T16:15:21.861025Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# May mắn thay không có giá trị nào bị thiếu trong dữ liệu của chúng tôi\nprint(\n    \"Missing values in df_train: \", \\\n    df_train.isna().sum().sum()\n)\nprint(\n    \"Missing values in df_test: \", \\\n    df_test.isna().sum().sum()\n)","metadata":{"execution":{"iopub.status.busy":"2024-06-10T16:15:21.863685Z","iopub.execute_input":"2024-06-10T16:15:21.864126Z","iopub.status.idle":"2024-06-10T16:15:21.923360Z","shell.execute_reply.started":"2024-06-10T16:15:21.864087Z","shell.execute_reply":"2024-06-10T16:15:21.921940Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Cùng nhìn lại năm hàng huấn luyện đầu tiên\ndf_train.head()","metadata":{"execution":{"iopub.status.busy":"2024-06-10T16:15:21.924751Z","iopub.execute_input":"2024-06-10T16:15:21.925097Z","iopub.status.idle":"2024-06-10T16:15:21.956479Z","shell.execute_reply.started":"2024-06-10T16:15:21.925068Z","shell.execute_reply":"2024-06-10T16:15:21.955358Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Ta thấy cột đầu tiên là nhãn,\n# và các cột còn lại là 784 pixel\n# đại diện cho hình ảnh thang độ xám 28x28.\n# Hãy tách X và Y\n\nX_train = df_train.drop(columns=['label']).values\ny_train = df_train['label'].values","metadata":{"execution":{"iopub.status.busy":"2024-06-10T16:15:21.958323Z","iopub.execute_input":"2024-06-10T16:15:21.958688Z","iopub.status.idle":"2024-06-10T16:15:22.073029Z","shell.execute_reply.started":"2024-06-10T16:15:21.958657Z","shell.execute_reply":"2024-06-10T16:15:22.072055Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Hãy hình dung sự phân bố của các giá trị pixel\n\nax = sns.histplot(x=X_train.flatten(), color='#4895EE')\n_ = ax.set(title='Pixel Value Histogram', xlabel='Pixel Value')\n\n# Như chúng ta có thể thấy, giá trị 0 đại diện cho nền Giá trị \n# và >0 đại diện cho các chữ số trong hình ảnh","metadata":{"execution":{"iopub.status.busy":"2024-06-10T16:15:22.074329Z","iopub.execute_input":"2024-06-10T16:15:22.074676Z","iopub.status.idle":"2024-06-10T16:15:40.037230Z","shell.execute_reply.started":"2024-06-10T16:15:22.074647Z","shell.execute_reply":"2024-06-10T16:15:40.036067Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Hãy kiểm tra xem mục tiêu có cân bằng không.\n# Nó có nghĩa là mười danh mục trong mục tiêu\n# có sự biểu diễn gần giống nhau trong dữ liệu.\nax = sns.countplot(x=y_train, color='#4895EE')\nax.set(\n    title='Target distribution is balanced? Yes!',\n    xlabel='Label'\n)\n# Số lượng mẫu dự kiến ​​cho cân\n# phân bổ lớp là 42000/10 = 4200\n_ = ax.axhline(y=4200, color='#12086F', linestyle='--')\n\n# Vì các lớp mục tiêu là số dư nên chúng ta không có\n# lo lắng về các phương pháp lấy mẫu và thành kiến trong các mô hình của chúng tôi.","metadata":{"execution":{"iopub.status.busy":"2024-06-10T16:15:40.039321Z","iopub.execute_input":"2024-06-10T16:15:40.039759Z","iopub.status.idle":"2024-06-10T16:15:40.331830Z","shell.execute_reply.started":"2024-06-10T16:15:40.039725Z","shell.execute_reply":"2024-06-10T16:15:40.330246Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Tiếp theo, hãy hình dung một hình ảnh từ mỗi lớp.\n# Chúng ta sẽ sử dụng hàm 'imshow' của matplotlib.\n\nfig, axs = plt.subplots(nrows=2, ncols=5, figsize=(10,5))\n\nfor i in range(10):\n    idx = np.where(y_train==i)[0][2]\n    img = axs[int(i >= 5), i%5].imshow(\n        X=X_train[idx].reshape(28, 28),\n        cmap='Blues'\n    )\n    img.axes.get_yaxis().set_visible(False)\n    img.axes.get_xaxis().set_visible(False)\n    img.axes.set_title(f'Label: {i}')","metadata":{"execution":{"iopub.status.busy":"2024-06-10T16:15:40.333501Z","iopub.execute_input":"2024-06-10T16:15:40.334070Z","iopub.status.idle":"2024-06-10T16:15:40.875330Z","shell.execute_reply.started":"2024-06-10T16:15:40.334022Z","shell.execute_reply":"2024-06-10T16:15:40.874164Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"transform data","metadata":{}},{"cell_type":"code","source":"### -------------------------------------------------- declare\nnumRotate_prior = 10\n\nangleOffset_prior = -20\nangleRange_prior = 40\n\n\n#900-999\nX_train_pick2rotate = {\n    'index': np.array([900, 901, 902, 903, 904, 905, 906, 907, 908, 909,\n910, 911, 912, 913, 914, 915, 916, 917, 918, 919,\n920, 921, 922, 923, 924, 925, 926, 927, 928, 929,\n930, 931, 932, 933, 934, 935, 936, 937, 938, 939,\n940, 941, 942, 943, 944, 945, 946, 947, 948, 949,\n950, 951, 952, 953, 954, 955, 956, 957, 958, 959,\n960, 961, 962, 963, 964, 965, 966, 967, 968, 969,\n970, 971, 972, 973, 974, 975, 976, 977, 978, 979,\n980, 981, 982, 983, 984, 985, 986, 987, 988, 989,\n990, 991, 992, 993, 994, 995, 996, 997, 998, 999]),\n    'offset': np.array([\n        #0\n        [35,0,0,2,0, \n         30,33,20,0,20],\n        #1\n        [0,10,10,-5,5, \n         50,-10,0,18,20],\n        #2\n        [25,25,0,-20,15, \n         0,-55,-15,10,10],\n        #3\n        [0,-10,10,0,10, \n         15,-25,0,0,27],\n        #4\n        [-125,18,5,-10,25, \n         15,40,-4,15,-10],\n        #5\n        [42,2,8,-12,8, \n         28,-20,0,-5,20],\n        #6\n        [0,12,15,5,10, \n         20,-10,20,10,-15],\n        #7\n        [0,10,0,0,18, \n         15,-10,10,0,5],\n        #8\n        [0,-5,0,0,2, \n         25,30,8,0,20],\n        #9\n        [30,30,5,0,18, \n        7,20,0,8,0],\n        #10\n        [53,10,5,15,20, \n        30,10,-4,12,25],\n        #11\n        [20,18,-5,-5,15, \n         -10,-20,0,0,20],\n        #12\n        [35,20,15,20,35, \n        23,-60,2,10,2],\n        #13\n        [20,5,0,10,20, \n        24,-5,5,2,23],\n        #14\n        [45,20,5,3,24, \n        10,-30,0,15,13],\n        #15\n        [30,25,5,5,15, \n        5,-20,-5,10,25],\n        #16\n        [38,15,10,-8,15, \n        5,-30,0,-5,5],\n        #17\n        [10,30,-5,0,-5, \n        20,15,15,10,18],\n        #18\n        [10,25,0,0,5, \n        20,10,0,-5,13],\n        #19\n        [10,40,0,10,15, \n        30,0,-5,5,4],\n        #20\n        [23,5,0,-8,23, \n        0,20,20,-10,-5],\n        #21\n        [20,25,-3,0,25, \n        25,-20,0,0,-13],\n        #22\n        [10,-12,20,0,-5, \n        0,-10,-7,20,12],\n        #23\n        [60,35,10,2,-13, \n        -2,0,-15,20,28],\n        #24\n        [0,8,12,3,30, \n        0,15,20,15,20],\n        #25\n        [24,20,0,-12,-10, \n        15,0,12,8,0],\n        #26\n        [75,-10,-12,-15,20, \n        20,-10,0,15,5],\n        #27\n        [15,2,4,-5,24, \n        15,2,4,-5,10],\n        #28\n        [55,20,0,-5,0, \n        25,-15,0,-20,5],\n        #29\n        [20,35,-10,5,5, \n        19,-50,2,0,5],\n        #30\n        [25,23,0,0,8, \n        7,-5,20,-5,10],\n        #31\n        [20,25,0,5,10, \n        10,10,30,50,15,],\n        #32\n        [10,10,0,0,10, \n        15,15,0,5,15,],\n        #33\n        [-10,27,0,10,10, \n        25,0,0,10,-5,],\n        #34\n        [30,22,-5,5,40, \n        0,25,0,-5,-10,],\n        #35\n        [0,10,10,0,20, \n        10,-10,5,0,0,],\n        #36\n        [0,5,20,-10,10, \n        0,0,-5,0,0,],\n        #37\n        [30,0,0,0,0, \n        10,10,0,15,27,],\n        #38\n        [5,23,0,17,5, \n        15,-20,-2,32,15,],\n        #39\n        [40,5,-10,-10,8, \n        10,-60,30,0,15,],\n        #40\n        [35,7,10,-5,17, \n        20,-5,8,8,18,],\n        #41\n        [13,-5,-4,0,22, \n        34,15,-5,20,18,],\n        #42\n        [-15,10,-5,-17,20, \n        -7,0,0,-5,30,],\n        #43\n        [40,38,0,10,28, \n        -5,0,-10,0,4,],\n        #44\n        [-110,23,0,-3,15, \n        17,-10,10,-10,35],\n        #45\n        [15,12,-12,-10,30, \n        10,-10,-10,25,-2,],\n        #46\n        [50,20,0,0,-7, \n        0,10,0,-5,30,],\n        #47\n        [30,30,-5,10,10, \n        0,0,0,0,15,],\n        #48\n        [30,30,0,5,17, \n        13,-20,0,-10,15,],\n        #49\n        [20,-8,-10,-5,0, \n        20,-55,7,5,5,],\n        #50\n        [-130,22,23,20,47, \n        20,10,13,10,27,],\n        #51\n        [-100,50,10,10,30, \n        30,30,10,25,25,],\n        #52\n        [10,43,20,15,45, \n        39,0,30,26,30,],\n        #53\n        [50,35,-4,-3,55, \n        23,4,10,34,45,],\n        #54\n        [25,50,-5,25,38, \n        26,37,21,24,30],\n        #55\n        [50,15,15,25,40, \n        30,30,30,55,48,],\n        #56\n        [60,48,10,16,40, \n        20,20,20,50,53,],\n        #57\n        [18,20,20,15,19, \n        25,30,0,14,20,],\n        #58\n        [50,30,17,20,45, \n        20,0,10,15,10,],\n        #59\n        [15,30,0,0,45, \n        20,0,20,28,13,],\n        #60\n        [-40,15,10,-3,50, \n        20,30,20,20,30,],\n        #61\n        [20,30,-5,15,20, \n        -3,-10,0,-4,20,],\n        #62\n        [4,10,10,10,20, \n        0,10,0,17,0,],\n        #63\n        [20,30,10,-10,0, \n        10,-5,0,-10,20,],\n        #64\n        [0,30,0,0,20, \n        10,0,0,0,15,],\n        #65\n        [0,20,0,0,0, \n        0,0,0,-5,10,],\n        #66\n        [0,25,10,-10,5, \n        4,5,0,10,0,],\n        #67\n        [5,15,0,7,10, \n        0,0,5,5,0,],\n        #68\n        [13,2,-3,0,20, \n        10,5,5,10,0,],\n        #69\n        [10,7,0,5,15, \n        0,30,-5,5,10,],\n        #70\n        [0,5,10,0,20, \n        13,0,0,5,-3,],\n        #71\n        [20,3,2,-4,-10, \n        0,0,0,5,0,],\n        #72\n        [20,15,8,0,10, \n        7,5,-3,0,5,],\n        #73\n        [0,0,20,5,10, \n        0,0,0,5,25,],\n        #74\n        [10,5,0,3,0, \n        10,0,0,5,0,],\n        #75\n        [10,-10,3,0,30, \n        0,-20,10,10,-5,],\n        #76\n        [25,-3,4,-5,20, \n        -10,10,3,30,20,],\n        #77\n        [20,2,6,0,-3, \n        15,0,0,-5,20,],\n        #78\n        [45,0,0,5,8, \n        0,0,0,5,15,],\n        #79\n        [7,4,5,-5,10, \n        -5,0,0,15,10,],\n        #80\n        [-5,3,0,2,2, \n        7,-10,-59,2,15,],\n        #81\n        [5,5,5,3,-10, \n        10,-6,0,-5,10,],\n        #82\n        [0,30,0,5,10, \n        7,0,0,20,10,],\n        #83\n        [20,0,20,0,10, \n        0,0,0,5,0,],\n        #84\n        [10,0,-7,10,15, \n        10,-10,10,5,0,],\n        #85\n        [0,-5,0,0,-25, \n        10,15,15,10,5,],\n        #86\n        [30,-20,-10,0,5, \n        10,0,0,0,0,],\n        #87\n        [0,4,0,0,30, \n        0,20,0,30,-8,],\n        #88\n        [20,-6,0,0,6, \n        4,0,0,3,15,],\n        #89\n        [20,3,-5,3,10, \n        10,5,0,3,-10,],\n        #90\n        [15,-12,0,6,20, \n        4,0,0,4,15,],\n        #91\n        [15,-3,5,-3,0, \n        15,0,0,-5,0,],\n        #92\n        [10,15,-5,-25,20, \n        20,-10,10,10,25,],\n        #93\n        [20,35,0,0,-7, \n        10,-10,-7,-5,9,],\n        #94\n        [20,7,-10,0,10, \n        10,0,0,8,-13,],\n        #95\n        [50,12,-10,-10,8, \n        5,-15,0,8,-21,],\n        #96\n        [20,20,0,0,0, \n        0,0,-10,10,20,],\n        #97\n        [0,14,5,-5,18, \n        3,0,-7,10,5,],\n        #98\n        [20,-7,0,25,20, \n        20,0,7,5,10,],\n        #99\n        [25,0,-3,20,24, \n        10,0,14,-2,21,],\n        \n                \n    ])\n}\n\nnumPickRotate = len(X_train_pick2rotate['index'])\n\nprint('numPickRotate = ', numPickRotate)\n\n# -------------------------------------------------- rotate\n\nX_sample_rotate = np.zeros((10,numRotate_prior,numPickRotate,X_train.shape[1]))\ny_sample_rotate = np.zeros((10,numRotate_prior,numPickRotate))\n\nfor k0 in range(10):\n    for k1 in range(numRotate_prior):\n        for k2 in range(numPickRotate):\n            \n                idxPick_X_train = X_train_pick2rotate['index'][k2]\n                \n                idx = np.where(y_train==k0)[0][idxPick_X_train]\n                \n                y_sample_rotate[k0,k1,k2] = k0\n                \n                angleRotate = (k1/numRotate_prior * angleRange_prior) + angleOffset_prior + X_train_pick2rotate['offset'][k2][k0]\n                \n                X_sample_rotate[k0,k1,k2,:] = func_array1d_rotate2d(X_train[idx][np.newaxis,:],angleRotate, 28)\n\n                \nX_sample_rotate[X_sample_rotate < 10] = 0\n#X_sample_rotate[X_sample_rotate > 300] = 0\n\n# Hãy chuẩn hóa các giá trị pixel thành khoảng [0,1]\n# Công thức: MinMaxscale(X) = (X - X_min) / (X_max - X_min)\n\nprint(\"Before applying MinMax Scaler:\")\nprint(\"  - Minimum value:\", X_sample_rotate.min())\nprint(\"  - Maximum value:\", X_sample_rotate.max())\n\nminmax_scaler = MinMaxScaler()\n\nfor k0 in range(10):\n    for k1 in range(numRotate_prior):\n        X_sample_rotate[k0,k1,:,:] = minmax_scaler.fit_transform(X_sample_rotate[k0,k1,:,:]) * 255\n\nprint(\"\\nAfter applying MinMax Scaler:\")\nprint(\"  - Minimum value:\", X_sample_rotate.min())\nprint(\"  - Maximum value:\", X_sample_rotate.max())\n\n\n\n# Tiếp theo, hãy hình dung một hình ảnh từ mỗi lớp.\n# Chúng ta sẽ sử dụng hàm 'imshow' của matplotlib.\n\n# cho k2 trong phạm vi(numPickRotate):\nfor k2 in range(60,70):\n    k1 = 0\n    # k1 = numRotate_prior - 1\n\n    fig, axs = plt.subplots(nrows=2, ncols=5, figsize=(10, 5))\n    \n    for k0, ax in enumerate(axs.flat):\n        img = ax.imshow(\n            X=X_sample_rotate[k0, k1, k2, :].reshape(28, 28),\n            cmap='Blues'\n        )      \n        ax.get_yaxis().set_visible(False)\n        ax.get_xaxis().set_visible(False)\n        ax.set_title(f'Label: {k0}')\n\n    # Hiển thị số lưới ảnh trên hình\n    fig.suptitle(f'Lưới ảnh số {k2}', fontsize=14)\n    plt.show()\nX_train_rotate = np.reshape(X_sample_rotate, (-1,784))\ny_train_rotate = np.reshape(y_sample_rotate, (-1,1)).flatten()","metadata":{"execution":{"iopub.status.busy":"2024-06-10T17:06:16.766854Z","iopub.execute_input":"2024-06-10T17:06:16.768250Z","iopub.status.idle":"2024-06-10T17:06:27.520915Z","shell.execute_reply.started":"2024-06-10T17:06:16.768187Z","shell.execute_reply":"2024-06-10T17:06:27.519598Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# # 3. Phân tích thành phần chính","metadata":{}},{"cell_type":"markdown","source":"Phân tích thành phần chính (PCA) là một kỹ thuật thống kê để giảm tính chiều của tập dữ liệu. Điều này được thực hiện bằng cách chuyển đổi tuyến tính dữ liệu sang một hệ tọa độ mới trong đó (hầu hết) sự thay đổi trong dữ liệu có thể được mô tả với ít thứ nguyên hơn dữ liệu ban đầu.\n\nThành phần chính đầu tiên có thể được định nghĩa một cách tương đương là hướng tối đa hóa phương sai của dữ liệu dự kiến. Thành phần chính thứ i có thể được lấy làm hướng trực giao với thành phần chính thứ i-1 để tối đa hóa phương sai của dữ liệu dự kiến.\n\nsklearn.decomposition.PCA: Giảm kích thước tuyến tính bằng cách sử dụng Phân tách giá trị đơn lẻ của dữ liệu để chiếu dữ liệu đó vào không gian có chiều thấp hơn.\n\nỞ đây chúng tôi sẽ sử dụng 10 thành phần chính hàng đầu, giải thích gần 50% phương sai trong dữ liệu. Điều này có nghĩa là chúng tôi có thể biểu thị 50% phương sai của dữ liệu với không gian tính năng nhỏ hơn >98% so với dữ liệu ban đầu (10 tính năng so với 784 tính năng)","metadata":{}},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"code","source":"# Hãy chuẩn hóa các giá trị pixel thành khoảng [0,1]\n# Công thức: MinMaxscale(X) = (X - X_min) / (X_max - X_min)\n\nprint(\"Before applying MinMax Scaler:\")\nprint(\"  - Minimum value:\", X_train.min())\nprint(\"  - Maximum value:\", X_train.max())\n\nminmax_scaler = MinMaxScaler()\nX_train_rotate_scaled = minmax_scaler.fit_transform(X_train_rotate)\n\nprint(\"\\nAfter applying MinMax Scaler:\")\nprint(\"  - Minimum value:\", X_train_rotate_scaled.min())\nprint(\"  - Maximum value:\", X_train_rotate_scaled.max())","metadata":{"execution":{"iopub.status.busy":"2024-06-10T16:15:50.261843Z","iopub.execute_input":"2024-06-10T16:15:50.262509Z","iopub.status.idle":"2024-06-10T16:15:50.421074Z","shell.execute_reply.started":"2024-06-10T16:15:50.262450Z","shell.execute_reply":"2024-06-10T16:15:50.419574Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Trên thực tế, chúng tôi sẽ nhúng MinMaxScaler và PCA\n# mô-đun vào Đường ống Sklearn.\n\npca = Pipeline(steps=[\n    ('scaler', MinMaxScaler()),\n    ('pca', PCA(n_components=10))\n])\n\nX_train_rotate_pca = pca.fit_transform(X=X_train_rotate)\n\nprint('X_train_pca shape:', X_train_rotate_pca.shape)","metadata":{"execution":{"iopub.status.busy":"2024-06-10T16:15:50.427249Z","iopub.execute_input":"2024-06-10T16:15:50.427630Z","iopub.status.idle":"2024-06-10T16:15:51.239250Z","shell.execute_reply.started":"2024-06-10T16:15:50.427600Z","shell.execute_reply":"2024-06-10T16:15:51.237690Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Hãy trích xuất tỷ lệ phương sai được giải thích\n# Và hãy tính tổng tích lũy của chúng\n\npca_object = pca.named_steps['pca']\nvar_ratio = pd.Series(\n    data=pca_object.explained_variance_ratio_,\n    index=range(1, 11)\n)\n\ncumsum_var_ratio = var_ratio.cumsum()","metadata":{"execution":{"iopub.status.busy":"2024-06-10T16:15:51.241629Z","iopub.execute_input":"2024-06-10T16:15:51.243265Z","iopub.status.idle":"2024-06-10T16:15:51.258320Z","shell.execute_reply.started":"2024-06-10T16:15:51.243205Z","shell.execute_reply":"2024-06-10T16:15:51.256534Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Vẽ biểu đồ tỷ lệ phương sai giải thích cho từng thành phần (trái)\n# Và vẽ tổng tích lũy của chúng (phải)\n\nfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15,5))\n\nsns.barplot(\n    x=var_ratio.index, \n    y=var_ratio.values, \n    color='#4895EE', \n    ax=ax1\n)\nax1.set(\n    title='Explained Variance Ratio PCA',\n    xlabel='Component',\n    ylabel='Var Ratio',\n)\nax1.set_ylim(0, 0.5)\n\nsns.barplot(\n    x=cumsum_var_ratio.index, \n    y=cumsum_var_ratio.values, \n    color='#4895EE', \n    ax=ax2\n)\nax2.set(\n    title='Cumulative Explained Variance Ratio PCA',\n    xlabel='Component',\n    ylabel='Cumulative Var Ratio',\n)\n_ = ax2.set_ylim(0, 0.5)","metadata":{"execution":{"iopub.status.busy":"2024-06-10T16:15:51.260348Z","iopub.execute_input":"2024-06-10T16:15:51.262110Z","iopub.status.idle":"2024-06-10T16:15:51.999568Z","shell.execute_reply.started":"2024-06-10T16:15:51.262060Z","shell.execute_reply":"2024-06-10T16:15:51.998293Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Hãy đặt các thành phần ở định dạng Pandas DataFrame\n# Bằng cách này chúng ta có thể sử dụng thư viện seaborn và pploly\n# để trực quan hóa dữ liệu.\n# (các gói này hoạt động tốt hơn với Pandas DataFrames)\ndf_train_pca = pd.DataFrame(\n    data=X_train_rotate_pca[:,:3], \n    columns=['x', 'y', 'z']\n)\n# Hãy thêm mục tiêu để đặt màu\ndf_train_pca['target'] = y_train_rotate\n\nprint(df_train_pca.shape)\ndf_train_pca.head()","metadata":{"execution":{"iopub.status.busy":"2024-06-10T16:15:52.001816Z","iopub.execute_input":"2024-06-10T16:15:52.002300Z","iopub.status.idle":"2024-06-10T16:15:52.021833Z","shell.execute_reply.started":"2024-06-10T16:15:52.002251Z","shell.execute_reply":"2024-06-10T16:15:52.020622Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Trực quan hóa hai chiều của dữ liệu\n# Ở đây các thành phần chính của Top2 được vẽ\n\nsns.set_style(\"dark\")\nax = sns.scatterplot(\n    data=df_train_pca,\n    x='x', \n    y='y', \n    hue='target', \n    palette='Blues',\n)\nax.set(\n    title='PCA Two-Dimensional Projection',\n    xlabel='1st Comp.',\n    ylabel='2nd Comp.'\n)\nax.axhline(y=0, linestyle='--', color='#FFBF00', zorder=-1)\nax.axvline(x=0, linestyle='--', color='#FFBF00', zorder=-1)","metadata":{"execution":{"iopub.status.busy":"2024-06-10T16:15:52.023463Z","iopub.execute_input":"2024-06-10T16:15:52.023923Z","iopub.status.idle":"2024-06-10T16:15:54.334069Z","shell.execute_reply.started":"2024-06-10T16:15:52.023880Z","shell.execute_reply":"2024-06-10T16:15:54.332824Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Trực quan hóa hai chiều của dữ liệu\n# Ở đây các thành phần chính của Top3 được vẽ\n\nsns.set_style(\"white\")\nfig = px.scatter_3d(\n    data_frame=df_train_pca,\n    x='x',\n    y='y',\n    z='z',\n    labels={\n        'x': '1st Comp.',\n        'y': '2nd Comp.',\n        'z': '3rd Comp.'\n    },\n    color='target',\n    title='PCA Three-Dimensional Projection',\n    color_continuous_scale='blues',\n    template='ggplot2'\n)\n\nfig.show()","metadata":{"execution":{"iopub.status.busy":"2024-06-10T16:15:54.335469Z","iopub.execute_input":"2024-06-10T16:15:54.335832Z","iopub.status.idle":"2024-06-10T16:15:56.928300Z","shell.execute_reply.started":"2024-06-10T16:15:54.335801Z","shell.execute_reply":"2024-06-10T16:15:56.927084Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Bây giờ, hãy áp dụng biến đổi nghịch đảo để tính toán\n# sự gần đúng của hình ảnh dựa trên nguyên tắc 10\n#thành phần.\n# Chúng ta có thể thấy rằng chỉ với 10 thành phần chúng ta đã truyền tải được một lượng lớn\n# một phần thông tin của mỗi hình ảnh.\n\npca_object = pca.named_steps['pca']\n\nfig, axs = plt.subplots(nrows=10, ncols=2, figsize=(6,20))\n\nfor i in range(10):\n    idx = np.where(y_train_rotate==i)[0][0]\n    original_img = axs[i, 0].imshow(\n        X=X_train_rotate[idx].reshape(28, 28),\n        cmap='Blues'\n    )\n    original_img.axes.get_yaxis().set_visible(False)\n    original_img.axes.get_xaxis().set_visible(False)\n    original_img.axes.set_title(f'Original [{i}]:')\n    \n    approx_img_ = pca_object.inverse_transform(X=X_train_rotate_pca[idx])\n    approx_img = axs[i, 1].imshow(\n        X=approx_img_.reshape(28, 28),\n        cmap='Blues'\n    )\n    approx_img.axes.get_yaxis().set_visible(False)\n    approx_img.axes.get_xaxis().set_visible(False)\n    approx_img.axes.set_title(f'Approximation [{i}]:')","metadata":{"execution":{"iopub.status.busy":"2024-06-10T16:15:56.929702Z","iopub.execute_input":"2024-06-10T16:15:56.930063Z","iopub.status.idle":"2024-06-10T16:15:57.982636Z","shell.execute_reply.started":"2024-06-10T16:15:56.930032Z","shell.execute_reply":"2024-06-10T16:15:57.981434Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Chứng tỏ các thành phần PCA không tương quan\n# (Câu nói này đúng về mặt định nghĩa và cách xây dựng\n# của thuật toán Phân tích thành phần chính)\n\ncorr = np.corrcoef(x=X_train_rotate_pca, rowvar=False)\ncorr = np.around(corr, decimals=2)\n\nax = sns.heatmap(\n    data=corr, \n    vmax=1, \n    vmin=-1,\n    square=True,\n    linewidths=.5,\n    annot=True,\n    cmap='Blues',\n)\n\n_ = ax.set(\n    title='Correlation PCA Components [Uncorrelated]',\n    xlabel='Components',\n    ylabel='Components'\n)","metadata":{"execution":{"iopub.status.busy":"2024-06-10T16:15:57.984174Z","iopub.execute_input":"2024-06-10T16:15:57.984530Z","iopub.status.idle":"2024-06-10T16:15:59.016755Z","shell.execute_reply.started":"2024-06-10T16:15:57.984499Z","shell.execute_reply":"2024-06-10T16:15:59.015514Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Phần 4: Sử dụng K-Nearest Neighbors Classifier phân loại 10 thành phần chính hàng đầu từ PCA.","metadata":{}},{"cell_type":"markdown","source":"Thuật toán K-Nearest Neighbors là một thuật toán phân loại học tập có giám sát, không tham số, sử dụng độ gần để phân loại hoặc dự đoán về việc nhóm một điểm dữ liệu riêng lẻ. Dự đoán: Nhãn lớp được chỉ định trên cơ sở đa số phiếu bầu. nhãn được thể hiện thường xuyên nhất xung quanh một điểm dữ liệu nhất định.\n\nTrong dự án này, đầu vào của Bộ phân loại KNN sẽ là 10 thành phần chính hàng đầu từ PCA.\n\nsklearn.neighbors.KNeighborsClassifier: Trình phân loại thực hiện bỏ phiếu k-hàng xóm gần nhất. Chúng tôi sẽ chạy GridSearchCV để tối ưu hóa siêu tham số n_neighbors.","metadata":{}},{"cell_type":"markdown","source":"mô hình học máy trên tập dữ liệu Train","metadata":{}},{"cell_type":"code","source":"knn_clf = Pipeline(steps=[\n    ('scaler', MinMaxScaler()),\n    ('pca', PCA(n_components=10)),\n    ('knn', KNeighborsClassifier())\n])\n\nknn_clf_params = {\n    'knn__n_neighbors': [2, 4, 8, 16, 32]\n}\n\nknn_clf_gs = GridSearchCV(\n    estimator=knn_clf, \n    param_grid=knn_clf_params,\n    scoring='accuracy',\n    n_jobs=-1,\n    cv=5,\n    verbose=1,\n    return_train_score=True\n)\n\nknn_clf_gs.fit(X=X_train_rotate_pca, y=y_train_rotate)\n\nprint('best PCA+KNN params:', knn_clf_gs.best_params_)\nprint('best PCA+KNN cv accuracy:', knn_clf_gs.best_score_)","metadata":{"execution":{"iopub.status.busy":"2024-06-10T16:15:59.018481Z","iopub.execute_input":"2024-06-10T16:15:59.018932Z","iopub.status.idle":"2024-06-10T16:16:15.080227Z","shell.execute_reply.started":"2024-06-10T16:15:59.018891Z","shell.execute_reply":"2024-06-10T16:16:15.077919Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Vẽ sơ đồ độ chính xác trong đào tạo và xác nhận\n# cho mỗi giá trị Siêu tham số được kiểm tra trong quá trình\n# Tìm kiếm lưới.\n# Biểu đồ này cho phép chúng ta kiểm tra xem có trang bị quá mức hay không.\n\nfig, ax = plt.subplots()\n\nax.plot(\n    range(len(knn_clf_params['knn__n_neighbors'])), \n    knn_clf_gs.cv_results_['mean_train_score'],\n    label='train',\n    color='blue'\n)\nax.plot(\n    range(len(knn_clf_params['knn__n_neighbors'])),\n    knn_clf_gs.cv_results_['mean_test_score'],\n    label='test',\n    color='orange'\n)\nax.set_xticks(\n    ticks=range(len(knn_clf_params['knn__n_neighbors'])),\n    labels=knn_clf_params['knn__n_neighbors']\n)\n\nii = knn_clf_params['knn__n_neighbors'].index(\n    knn_clf_gs.best_params_['knn__n_neighbors']\n)\n\nplt.axvline(x=ii, linestyle='--', color='red', label='best', alpha=0.3)\nplt.legend()\nplt.xlabel(\"'n_neighbors' vals\")\nplt.ylabel('Accuracy')\nplt.title(\"PCA+KNN GridSearchCV Results\")\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-06-10T16:16:15.083649Z","iopub.execute_input":"2024-06-10T16:16:15.084312Z","iopub.status.idle":"2024-06-10T16:16:15.496490Z","shell.execute_reply.started":"2024-06-10T16:16:15.084255Z","shell.execute_reply":"2024-06-10T16:16:15.495387Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Phần 5: Tạo một tệp tin chứa các dự đoán của mô hình học máy trên tập dữ liệu Test","metadata":{}},{"cell_type":"code","source":"# Tính toán và hiển thị Ma trận nhầm lẫn\n# Lưu ý: toàn bộ tập dữ liệu huấn luyện được sử dụng ở đây\n\nbest_cv_clf = knn_clf_gs.best_estimator_\ny_pred = best_cv_clf.predict(X=X_train_rotate_pca)\nconf_matrix = confusion_matrix(y_true=y_train_rotate, y_pred=y_pred)\n\nconf_matrix_disp = ConfusionMatrixDisplay(conf_matrix)\nconf_matrix_disp.plot(cmap='Blues')","metadata":{"execution":{"iopub.status.busy":"2024-06-10T16:16:15.497784Z","iopub.execute_input":"2024-06-10T16:16:15.498123Z","iopub.status.idle":"2024-06-10T16:16:17.141252Z","shell.execute_reply.started":"2024-06-10T16:16:15.498094Z","shell.execute_reply":"2024-06-10T16:16:17.139889Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Tính báo cáo phân loại bằng sklearn\n# Lưu ý: toàn bộ tập dữ liệu huấn luyện được sử dụng ở đây\nclf_report = classification_report(\n    y_true=y_train_rotate,\n    y_pred=y_pred,\n    labels=range(10),\n)\n# In báo cáo phân loại\nprint(clf_report)","metadata":{"execution":{"iopub.status.busy":"2024-06-10T16:16:17.142790Z","iopub.execute_input":"2024-06-10T16:16:17.143180Z","iopub.status.idle":"2024-06-10T16:16:17.173865Z","shell.execute_reply.started":"2024-06-10T16:16:17.143147Z","shell.execute_reply":"2024-06-10T16:16:17.172286Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Tính toán và hiển thị Ma trận nhầm lẫn\n# Lưu ý: toàn bộ tập dữ liệu huấn luyện được sử dụng ở đây\n\nbest_cv_clf = knn_clf_gs.best_estimator_\ny_pred = best_cv_clf.predict(X=pca_object.transform(X_train))\nconf_matrix = confusion_matrix(y_true=y_train, y_pred=y_pred)\n\nconf_matrix_disp = ConfusionMatrixDisplay(conf_matrix)\nconf_matrix_disp.plot(cmap='Blues')\n\n# Tính báo cáo phân loại bằng sklearn\n# Lưu ý: toàn bộ tập dữ liệu huấn luyện được sử dụng ở đây\n\nclf_report = classification_report(\n    y_true=y_train,\n    y_pred=y_pred,\n    labels=range(10),\n)\n\n# In báo cáo phân loại\nprint(clf_report)","metadata":{"execution":{"iopub.status.busy":"2024-06-10T16:16:17.175198Z","iopub.execute_input":"2024-06-10T16:16:17.175540Z","iopub.status.idle":"2024-06-10T16:16:27.063102Z","shell.execute_reply.started":"2024-06-10T16:16:17.175508Z","shell.execute_reply":"2024-06-10T16:16:27.061515Z"},"trusted":true},"execution_count":null,"outputs":[]}]}