{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":102335,"databundleVersionId":12518947,"sourceType":"competition"}],"dockerImageVersionId":31089,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# 1. Tổng quan","metadata":{}},{"cell_type":"markdown","source":"Mục tiêu là khám phá các thuật toán học máy giám sát để phát hiện hành vi dựa trên dữ liệu cảm biến. Chúng ta sẽ xử lý các vấn đề như giá trị thiếu, xây dựng đường ống (pipelines), tạo ra sơ đồ phụ thuộc, và áp dụng mã hóa một lần.\n\nChúng ta sẽ sử dụng dữ liệu từ các cảm biến để dự đoán hành vi của các đối tượng trong môi trường. Các thuật toán học máy sẽ giúp phân loại hành vi dựa trên các đặc điểm đo lường được từ dữ liệu cảm biến. Mục tiêu cuối cùng là xây dựng một mô hình có khả năng dự đoán chính xác hành vi dựa trên các tính năng cảm biến được cung cấp.","metadata":{}},{"cell_type":"markdown","source":"# Outline","metadata":{}},{"cell_type":"markdown","source":"## 1.1 Tải và Khám Phá Dữ Liệu","metadata":{}},{"cell_type":"markdown","source":"Tải dữ liệu và tiến hành kiểm tra sơ bộ (kích thước, loại dữ liệu, và các thuộc tính).\n\nPhân tích thống kê cho các tính năng trong dataset, bao gồm:\n* Giá trị thiếu và cách xử lý.\n* Các tính năng đặc biệt như giới tính, tuổi, hành vi.\n* Kiểm tra sự phân phối mục tiêu và đặc tính dữ liệu qua biểu đồ phân phối và biểu đồ hộp.","metadata":{}},{"cell_type":"markdown","source":"## 1.2 Tiền Xử Lý Dữ Liệu","metadata":{}},{"cell_type":"markdown","source":"* Xử lý các giá trị thiếu bằng các phương pháp phù hợp.\n* Tách biệt dữ liệu thành các nhóm: cảm biến IMU, ToF, và mục tiêu.\n* Chuẩn hóa và chuẩn bị dữ liệu cho mô hình.\n* Feature Engineering để tối ưu hóa đặc trưng dữ liệu.","metadata":{}},{"cell_type":"markdown","source":"## 1.3 Khám Phá Dữ Liệu và Trực Quan Hóa","metadata":{}},{"cell_type":"markdown","source":"Trực quan hóa mối quan hệ giữa các tính năng:\n* Tương quan Pearson giữa các tính năng.\n* Biểu đồ phân tán giữa các tính năng chính (ví dụ: chiều cao, trọng lượng, v.v.).\n* Biểu đồ hình tròn cho các tính năng phân loại như giới tính.\n* Tính toán mối tương quan giữa các dữ liệu cảm biến (IMU, ToF, v.v.).","metadata":{}},{"cell_type":"markdown","source":"## 1.4 Xây Dựng Mô Hình Học Máy","metadata":{}},{"cell_type":"markdown","source":"Chọn mô hình học máy phù hợp: Linear Regression, Decision Tree, Random Forest, XGBoost, MLP, và các mô hình hồi quy khác.\n\nTối ưu hóa mô hình qua Grid Search và Cross-Validation (K-fold).\n\nTối ưu hóa siêu tham số để cải thiện độ chính xác.","metadata":{}},{"cell_type":"markdown","source":"## 1.5 Đánh Giá Mô Hình và Tối Ưu Hóa","metadata":{}},{"cell_type":"markdown","source":"Đánh giá mô hình dựa trên các chỉ số như F1-score, accuracy, precision, recall.\n\nSử dụng ensemble learning như bagging và boosting để kết hợp các mô hình và cải thiện hiệu suất.\n\nTối ưu hóa mô hình cuối cùng để đảm bảo tính ổn định và khả năng dự đoán chính xác trong các bộ dữ liệu thực tế.","metadata":{}},{"cell_type":"markdown","source":"## 1.6 Kết Quả và Thảo Luận\n","metadata":{}},{"cell_type":"markdown","source":"Trình bày kết quả mô hình với các chỉ số đánh giá chi tiết.\n\nPhân tích các yếu tố ảnh hưởng đến độ chính xác của mô hình.\n\nKết luận về mô hình tối ưu và khả năng áp dụng vào thực tế.","metadata":{}},{"cell_type":"markdown","source":"# 2. Tổng quan dữ liệu","metadata":{}},{"cell_type":"markdown","source":"## 2.1 Tải dữ liệu và thư viện","metadata":{}},{"cell_type":"code","source":"import pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport warnings\nfrom matplotlib.ticker import MaxNLocator\nfrom mpl_toolkits.mplot3d import Axes3D\nimport os\nimport polars as pl\nimport kaggle_evaluation.cmi_inference_server\nfrom sklearn.metrics import accuracy_score, f1_score\nimport joblib\nfrom scipy.spatial.transform import Rotation as R","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2025-08-17T08:36:25.896744Z","iopub.execute_input":"2025-08-17T08:36:25.897044Z","iopub.status.idle":"2025-08-17T08:36:27.789251Z","shell.execute_reply.started":"2025-08-17T08:36:25.896991Z","shell.execute_reply":"2025-08-17T08:36:27.788645Z"}},"outputs":[],"execution_count":1},{"cell_type":"code","source":"# Tải tập dữ liệu\n#Dữ liệu cảm biến cho tập huấn luyện (Train Sensor Data): \ntrain_df = pd.read_csv(\"/kaggle/input/cmi-detect-behavior-with-sensor-data/train.csv\")\n\n#Thông tin nhân khẩu học của đối tượng trong tập huấn luyện (giới tính, tuổi, ...): \ntrain_dem_df = pd.read_csv(\"/kaggle/input/cmi-detect-behavior-with-sensor-data/train_demographics.csv\")\n\n#Dữ liệu cảm biến cho tập kiểm tra:\ntest_df = pd.read_csv(\"/kaggle/input/cmi-detect-behavior-with-sensor-data/test.csv\")\n\n# Thông tin nhân khẩu học của đối tượng trong tập kiểm tra:\ntest_dem_df = pd.read_csv(\"/kaggle/input/cmi-detect-behavior-with-sensor-data/test_demographics.csv\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-17T08:36:27.790295Z","iopub.execute_input":"2025-08-17T08:36:27.790629Z","iopub.status.idle":"2025-08-17T08:36:59.90559Z","shell.execute_reply.started":"2025-08-17T08:36:27.790612Z","shell.execute_reply":"2025-08-17T08:36:59.905055Z"}},"outputs":[],"execution_count":2},{"cell_type":"markdown","source":"## 2.1 Khám phá dữ liệu","metadata":{}},{"cell_type":"markdown","source":"### 2.1.3 Tóm tắt thống kê các tính năng ","metadata":{}},{"cell_type":"code","source":"datasets = {\n    \"Train Data\": train_df,\n    \"Train Demographics\": train_dem_df,\n    \"Test Data\": test_df,\n    \"Test Demographics\": test_dem_df,\n}\n\nfor name, df in datasets.items():\n    print(f\"Missing values in {name}:\")\n    missing = df.isnull().sum()\n    missing = missing[missing > 0]\n    if not missing.empty:\n        print(missing)\n    else:\n        print(\"  ✅ No missing values.\")\n    print()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-17T08:36:59.906289Z","iopub.execute_input":"2025-08-17T08:36:59.906496Z","iopub.status.idle":"2025-08-17T08:37:00.687121Z","shell.execute_reply.started":"2025-08-17T08:36:59.90648Z","shell.execute_reply":"2025-08-17T08:37:00.686361Z"}},"outputs":[{"name":"stdout","text":"Missing values in Train Data:\nrot_w         3692\nrot_x         3692\nrot_y         3692\nrot_z         3692\nthm_1         6987\n             ...  \ntof_5_v59    30142\ntof_5_v60    30142\ntof_5_v61    30142\ntof_5_v62    30142\ntof_5_v63    30142\nLength: 329, dtype: int64\n\nMissing values in Train Demographics:\n  ✅ No missing values.\n\nMissing values in Test Data:\n  ✅ No missing values.\n\nMissing values in Test Demographics:\n  ✅ No missing values.\n\n","output_type":"stream"}],"execution_count":3},{"cell_type":"markdown","source":"### 2.1.5 kiểm tra giá trị trùng lặp","metadata":{}},{"cell_type":"code","source":"#Kiểm tra trùng lặp (Duplicate Rows): .duplicated(): Trả về Series boolean, dòng nào trùng lặp sẽ là True.\n#                                     .sum(): Đếm tổng số dòng trùng lặp.\n#Kiểm tra xem dữ liệu có bản ghi nào bị trùng không — quan trọng cho việc làm sạch dữ liệu.\n\n# Đếm các hàng trùng lặp trong train_df\ntrain_duplicates = train_df.duplicated().sum()\n\n# Đếm các hàng trùng lặp trong  test_df\ntest_duplicates = test_df.duplicated().sum()\n\n# Đếm các hàng trùng lặp trong train_dem_df (optional)\ntrain_dem_duplicates = train_dem_df.duplicated().sum()\n# Đếm các hàng trùng lặp trong test_dem_df (optional)\ntest_dem_duplicates = test_dem_df.duplicated().sum()\n\n# In số lượng dòng trùng:\nprint(f\"Number of duplicate rows in train_df: {train_duplicates}\")\nprint(f\"Number of duplicate rows in test_df: {test_duplicates}\")\nprint(f\"Number of duplicate rows in train_dem_df: {train_dem_duplicates}\")\nprint(f\"Number of duplicate rows in test_dem_df: {test_dem_duplicates}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-17T08:37:00.688894Z","iopub.execute_input":"2025-08-17T08:37:00.689117Z","iopub.status.idle":"2025-08-17T08:37:05.198784Z","shell.execute_reply.started":"2025-08-17T08:37:00.6891Z","shell.execute_reply":"2025-08-17T08:37:05.19806Z"}},"outputs":[{"name":"stdout","text":"Number of duplicate rows in train_df: 0\nNumber of duplicate rows in test_df: 0\nNumber of duplicate rows in train_dem_df: 0\nNumber of duplicate rows in test_dem_df: 0\n","output_type":"stream"}],"execution_count":4},{"cell_type":"markdown","source":"## Tiền xử lý dữ liệu","metadata":{}},{"cell_type":"markdown","source":"### Tỷ lệ phần trăm Null","metadata":{}},{"cell_type":"markdown","source":"#### UTILS/HELPERS","metadata":{}},{"cell_type":"code","source":"def null_percent(df):\n    per=((df.isnull().sum()/len(df))*100).round(2)\n    return per[per>0]\n\nprint(\"Nan Values in Train data\")\nprint(null_percent(train_df))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-17T08:37:05.199465Z","iopub.execute_input":"2025-08-17T08:37:05.199705Z","iopub.status.idle":"2025-08-17T08:37:06.008504Z","shell.execute_reply.started":"2025-08-17T08:37:05.199687Z","shell.execute_reply":"2025-08-17T08:37:06.007631Z"}},"outputs":[{"name":"stdout","text":"Nan Values in Train data\nrot_w        0.64\nrot_x        0.64\nrot_y        0.64\nrot_z        0.64\nthm_1        1.22\n             ... \ntof_5_v59    5.24\ntof_5_v60    5.24\ntof_5_v61    5.24\ntof_5_v62    5.24\ntof_5_v63    5.24\nLength: 329, dtype: float64\n","output_type":"stream"}],"execution_count":5},{"cell_type":"markdown","source":"Các cột có tỷ lệ NaN cao nhất là các cột có tên bắt đầu với tof_5_v (5.24% NaN).\n\nCác cột khác như rot_x, rot_w có tỷ lệ NaN thấp hơn nhiều (0.64%).","metadata":{}},{"cell_type":"markdown","source":"## 2.2 Quan sát hoặc xu hướng ban đầu","metadata":{}},{"cell_type":"code","source":"# --- 2.4 Hợp nhất dữ liệu nhân khẩu học và cảm biến ---\nmerged_train = pd.merge(train_df, train_dem_df, on=\"subject\", how=\"left\")\nmerged_test = pd.merge(test_df, test_dem_df, on=\"subject\", how=\"left\")\n\nprint(\"Merged Train Shape:\", merged_train.shape)\nprint(\"Merged Test Shape:\", merged_test.shape)\ndisplay(merged_train.head(2))\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-17T08:37:06.009481Z","iopub.execute_input":"2025-08-17T08:37:06.009879Z","iopub.status.idle":"2025-08-17T08:37:06.69335Z","shell.execute_reply.started":"2025-08-17T08:37:06.009848Z","shell.execute_reply":"2025-08-17T08:37:06.6924Z"}},"outputs":[{"name":"stdout","text":"Merged Train Shape: (574945, 348)\nMerged Test Shape: (107, 343)\n","output_type":"stream"},{"output_type":"display_data","data":{"text/plain":"              row_id sequence_type sequence_id  sequence_counter      subject  \\\n0  SEQ_000007_000000        Target  SEQ_000007                 0  SUBJ_059520   \n1  SEQ_000007_000001        Target  SEQ_000007                 1  SUBJ_059520   \n\n                       orientation                                   behavior  \\\n0  Seated Lean Non Dom - FACE DOWN  Relaxes and moves hand to target location   \n1  Seated Lean Non Dom - FACE DOWN  Relaxes and moves hand to target location   \n\n        phase             gesture     acc_x  ...  tof_5_v61  tof_5_v62  \\\n0  Transition  Cheek - pinch skin  6.683594  ...       -1.0       -1.0   \n1  Transition  Cheek - pinch skin  6.949219  ...       -1.0       -1.0   \n\n   tof_5_v63  adult_child  age  sex  handedness  height_cm  \\\n0       -1.0            0   12    1           1      163.0   \n1       -1.0            0   12    1           1      163.0   \n\n   shoulder_to_wrist_cm  elbow_to_wrist_cm  \n0                    52               24.0  \n1                    52               24.0  \n\n[2 rows x 348 columns]","text/html":"<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>row_id</th>\n      <th>sequence_type</th>\n      <th>sequence_id</th>\n      <th>sequence_counter</th>\n      <th>subject</th>\n      <th>orientation</th>\n      <th>behavior</th>\n      <th>phase</th>\n      <th>gesture</th>\n      <th>acc_x</th>\n      <th>...</th>\n      <th>tof_5_v61</th>\n      <th>tof_5_v62</th>\n      <th>tof_5_v63</th>\n      <th>adult_child</th>\n      <th>age</th>\n      <th>sex</th>\n      <th>handedness</th>\n      <th>height_cm</th>\n      <th>shoulder_to_wrist_cm</th>\n      <th>elbow_to_wrist_cm</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>SEQ_000007_000000</td>\n      <td>Target</td>\n      <td>SEQ_000007</td>\n      <td>0</td>\n      <td>SUBJ_059520</td>\n      <td>Seated Lean Non Dom - FACE DOWN</td>\n      <td>Relaxes and moves hand to target location</td>\n      <td>Transition</td>\n      <td>Cheek - pinch skin</td>\n      <td>6.683594</td>\n      <td>...</td>\n      <td>-1.0</td>\n      <td>-1.0</td>\n      <td>-1.0</td>\n      <td>0</td>\n      <td>12</td>\n      <td>1</td>\n      <td>1</td>\n      <td>163.0</td>\n      <td>52</td>\n      <td>24.0</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>SEQ_000007_000001</td>\n      <td>Target</td>\n      <td>SEQ_000007</td>\n      <td>1</td>\n      <td>SUBJ_059520</td>\n      <td>Seated Lean Non Dom - FACE DOWN</td>\n      <td>Relaxes and moves hand to target location</td>\n      <td>Transition</td>\n      <td>Cheek - pinch skin</td>\n      <td>6.949219</td>\n      <td>...</td>\n      <td>-1.0</td>\n      <td>-1.0</td>\n      <td>-1.0</td>\n      <td>0</td>\n      <td>12</td>\n      <td>1</td>\n      <td>1</td>\n      <td>163.0</td>\n      <td>52</td>\n      <td>24.0</td>\n    </tr>\n  </tbody>\n</table>\n<p>2 rows × 348 columns</p>\n</div>"},"metadata":{}}],"execution_count":6},{"cell_type":"markdown","source":"**Merged Train Shape:** (574945, 348) - Sau khi hợp nhất, merged_train có 574,945 dòng và 348 cột, tức là dữ liệu từ train_df (574,945 dòng và 341 cột) đã được kết hợp với 7 cột từ train_dem_df (vì train_dem_df có 8 cột, nhưng 1 cột là subject đã được sử dụng làm khóa hợp nhất).\n\n**Merged Test Shape:** (107, 343) - Tương tự, merged_test có 107 dòng và 343 cột, kết quả là hợp nhất giữa test_df (107 dòng và 336 cột) với test_dem_df (8 cột, với 1 cột subject là khóa hợp nhất).","metadata":{}},{"cell_type":"code","source":"# --- Thống kê mô tả toàn bộ merged_train ---\nmerged_train.describe().T\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-17T08:37:06.694439Z","iopub.execute_input":"2025-08-17T08:37:06.694755Z","iopub.status.idle":"2025-08-17T08:37:14.90571Z","shell.execute_reply.started":"2025-08-17T08:37:06.694734Z","shell.execute_reply":"2025-08-17T08:37:14.904862Z"}},"outputs":[{"execution_count":7,"output_type":"execute_result","data":{"text/plain":"                         count        mean        std         min         25%  \\\nsequence_counter      574945.0   43.645234  45.717673    0.000000   17.000000   \nacc_x                 574945.0    1.639980   5.781259  -34.585938   -2.964844   \nacc_y                 574945.0    1.790704   5.003945  -24.402344   -2.121094   \nacc_z                 574945.0   -0.459811   6.096490  -42.855469   -5.417969   \nrot_w                 571253.0    0.360375   0.225739    0.000000    0.180237   \n...                        ...         ...        ...         ...         ...   \nsex                   574945.0    0.600247   0.489848    0.000000    0.000000   \nhandedness            574945.0    0.875898   0.329699    0.000000    1.000000   \nheight_cm             574945.0  167.647967  10.740996  135.000000  163.000000   \nshoulder_to_wrist_cm  574945.0   51.502566   4.900248   41.000000   49.000000   \nelbow_to_wrist_cm     574945.0   25.418165   2.964853   18.000000   24.000000   \n\n                             50%         75%         max  \nsequence_counter       35.000000   54.000000  699.000000  \nacc_x                   2.972656    6.343750   46.328125  \nacc_y                   0.695312    6.816406   27.183594  \nacc_z                  -1.562500    5.164062   30.078125  \nrot_w                   0.340332    0.503479    0.999390  \n...                          ...         ...         ...  \nsex                     1.000000    1.000000    1.000000  \nhandedness              1.000000    1.000000    1.000000  \nheight_cm             170.000000  174.000000  190.500000  \nshoulder_to_wrist_cm   52.000000   55.000000   71.000000  \nelbow_to_wrist_cm      25.000000   27.000000   44.000000  \n\n[340 rows x 8 columns]","text/html":"<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>count</th>\n      <th>mean</th>\n      <th>std</th>\n      <th>min</th>\n      <th>25%</th>\n      <th>50%</th>\n      <th>75%</th>\n      <th>max</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>sequence_counter</th>\n      <td>574945.0</td>\n      <td>43.645234</td>\n      <td>45.717673</td>\n      <td>0.000000</td>\n      <td>17.000000</td>\n      <td>35.000000</td>\n      <td>54.000000</td>\n      <td>699.000000</td>\n    </tr>\n    <tr>\n      <th>acc_x</th>\n      <td>574945.0</td>\n      <td>1.639980</td>\n      <td>5.781259</td>\n      <td>-34.585938</td>\n      <td>-2.964844</td>\n      <td>2.972656</td>\n      <td>6.343750</td>\n      <td>46.328125</td>\n    </tr>\n    <tr>\n      <th>acc_y</th>\n      <td>574945.0</td>\n      <td>1.790704</td>\n      <td>5.003945</td>\n      <td>-24.402344</td>\n      <td>-2.121094</td>\n      <td>0.695312</td>\n      <td>6.816406</td>\n      <td>27.183594</td>\n    </tr>\n    <tr>\n      <th>acc_z</th>\n      <td>574945.0</td>\n      <td>-0.459811</td>\n      <td>6.096490</td>\n      <td>-42.855469</td>\n      <td>-5.417969</td>\n      <td>-1.562500</td>\n      <td>5.164062</td>\n      <td>30.078125</td>\n    </tr>\n    <tr>\n      <th>rot_w</th>\n      <td>571253.0</td>\n      <td>0.360375</td>\n      <td>0.225739</td>\n      <td>0.000000</td>\n      <td>0.180237</td>\n      <td>0.340332</td>\n      <td>0.503479</td>\n      <td>0.999390</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>sex</th>\n      <td>574945.0</td>\n      <td>0.600247</td>\n      <td>0.489848</td>\n      <td>0.000000</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>handedness</th>\n      <td>574945.0</td>\n      <td>0.875898</td>\n      <td>0.329699</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n      <td>1.000000</td>\n    </tr>\n    <tr>\n      <th>height_cm</th>\n      <td>574945.0</td>\n      <td>167.647967</td>\n      <td>10.740996</td>\n      <td>135.000000</td>\n      <td>163.000000</td>\n      <td>170.000000</td>\n      <td>174.000000</td>\n      <td>190.500000</td>\n    </tr>\n    <tr>\n      <th>shoulder_to_wrist_cm</th>\n      <td>574945.0</td>\n      <td>51.502566</td>\n      <td>4.900248</td>\n      <td>41.000000</td>\n      <td>49.000000</td>\n      <td>52.000000</td>\n      <td>55.000000</td>\n      <td>71.000000</td>\n    </tr>\n    <tr>\n      <th>elbow_to_wrist_cm</th>\n      <td>574945.0</td>\n      <td>25.418165</td>\n      <td>2.964853</td>\n      <td>18.000000</td>\n      <td>24.000000</td>\n      <td>25.000000</td>\n      <td>27.000000</td>\n      <td>44.000000</td>\n    </tr>\n  </tbody>\n</table>\n<p>340 rows × 8 columns</p>\n</div>"},"metadata":{}}],"execution_count":7},{"cell_type":"code","source":"#Kiểm tra thiếu giá trị & thống kê cảm biến: \n#Danh sách các cột không thuộc cảm biến (có thể là ID, thông tin khác). \n\nexcluded_prefixes = ('acc_', 'rot_', 'thm_', 'tof_')\nsensor_cols = [col for col in train_df.columns if not col.startswith(excluded_prefixes)]\n\n# Sensor Data Summary for TRAIN\n#isnull().sum(): Đếm số giá trị bị thiếu.\nmissing_sensor_train = pd.DataFrame({\n    'Feature': sensor_cols,\n    '[TRAIN] Missing Count': train_df[sensor_cols].isnull().sum().values,\n    '[TRAIN] Missing %': (train_df[sensor_cols].isnull().sum().values / len(train_df)) * 100\n})\n\n#nunique(): Đếm số lượng giá trị duy nhất.\nunique_sensor_train = pd.DataFrame({\n    'Feature': sensor_cols,\n    'Unique Values [TRAIN]': train_df[sensor_cols].nunique().values\n})\n\n#dtypes: Lấy kiểu dữ liệu của từng cột.\ndtypes_sensor = pd.DataFrame({\n    'Feature': sensor_cols,\n    'Data Type': train_df[sensor_cols].dtypes.values\n})\n\n# Merge all summaries (NO test set)\n#merge: Gộp các bảng thống kê thành bảng duy nhất theo Feature.\nsensor_summary = missing_sensor_train \\\n    .merge(unique_sensor_train, on='Feature', how='left') \\\n    .merge(dtypes_sensor, on='Feature', how='left')\n\n# Display styled DataFrame (mask NaNs just for styling)\n#fillna(0): Điền giá trị thiếu bằng 0 (cho đẹp mắt khi hiển thị).\n#.style.background_gradient: Tô màu nền theo giá trị giúp dễ nhìn.\nstyled_df = sensor_summary.fillna(0)\nstyled_df.style.background_gradient(cmap='viridis')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-17T08:37:14.906572Z","iopub.execute_input":"2025-08-17T08:37:14.906839Z","iopub.status.idle":"2025-08-17T08:37:15.923792Z","shell.execute_reply.started":"2025-08-17T08:37:14.906818Z","shell.execute_reply":"2025-08-17T08:37:15.923071Z"}},"outputs":[{"execution_count":8,"output_type":"execute_result","data":{"text/plain":"<pandas.io.formats.style.Styler at 0x7d71d322bbd0>","text/html":"<style type=\"text/css\">\n#T_4c554_row0_col1, #T_4c554_row0_col2, #T_4c554_row1_col1, #T_4c554_row1_col2, #T_4c554_row1_col3, #T_4c554_row2_col1, #T_4c554_row2_col2, #T_4c554_row3_col1, #T_4c554_row3_col2, #T_4c554_row3_col3, #T_4c554_row4_col1, #T_4c554_row4_col2, #T_4c554_row4_col3, #T_4c554_row5_col1, #T_4c554_row5_col2, #T_4c554_row5_col3, #T_4c554_row6_col1, #T_4c554_row6_col2, #T_4c554_row6_col3, #T_4c554_row7_col1, #T_4c554_row7_col2, #T_4c554_row7_col3, #T_4c554_row8_col1, #T_4c554_row8_col2, #T_4c554_row8_col3 {\n  background-color: #440154;\n  color: #f1f1f1;\n}\n#T_4c554_row0_col3 {\n  background-color: #fde725;\n  color: #000000;\n}\n#T_4c554_row2_col3 {\n  background-color: #450559;\n  color: #f1f1f1;\n}\n</style>\n<table id=\"T_4c554\">\n  <thead>\n    <tr>\n      <th class=\"blank level0\" >&nbsp;</th>\n      <th id=\"T_4c554_level0_col0\" class=\"col_heading level0 col0\" >Feature</th>\n      <th id=\"T_4c554_level0_col1\" class=\"col_heading level0 col1\" >[TRAIN] Missing Count</th>\n      <th id=\"T_4c554_level0_col2\" class=\"col_heading level0 col2\" >[TRAIN] Missing %</th>\n      <th id=\"T_4c554_level0_col3\" class=\"col_heading level0 col3\" >Unique Values [TRAIN]</th>\n      <th id=\"T_4c554_level0_col4\" class=\"col_heading level0 col4\" >Data Type</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th id=\"T_4c554_level0_row0\" class=\"row_heading level0 row0\" >0</th>\n      <td id=\"T_4c554_row0_col0\" class=\"data row0 col0\" >row_id</td>\n      <td id=\"T_4c554_row0_col1\" class=\"data row0 col1\" >0</td>\n      <td id=\"T_4c554_row0_col2\" class=\"data row0 col2\" >0.000000</td>\n      <td id=\"T_4c554_row0_col3\" class=\"data row0 col3\" >574945</td>\n      <td id=\"T_4c554_row0_col4\" class=\"data row0 col4\" >object</td>\n    </tr>\n    <tr>\n      <th id=\"T_4c554_level0_row1\" class=\"row_heading level0 row1\" >1</th>\n      <td id=\"T_4c554_row1_col0\" class=\"data row1 col0\" >sequence_type</td>\n      <td id=\"T_4c554_row1_col1\" class=\"data row1 col1\" >0</td>\n      <td id=\"T_4c554_row1_col2\" class=\"data row1 col2\" >0.000000</td>\n      <td id=\"T_4c554_row1_col3\" class=\"data row1 col3\" >2</td>\n      <td id=\"T_4c554_row1_col4\" class=\"data row1 col4\" >object</td>\n    </tr>\n    <tr>\n      <th id=\"T_4c554_level0_row2\" class=\"row_heading level0 row2\" >2</th>\n      <td id=\"T_4c554_row2_col0\" class=\"data row2 col0\" >sequence_id</td>\n      <td id=\"T_4c554_row2_col1\" class=\"data row2 col1\" >0</td>\n      <td id=\"T_4c554_row2_col2\" class=\"data row2 col2\" >0.000000</td>\n      <td id=\"T_4c554_row2_col3\" class=\"data row2 col3\" >8151</td>\n      <td id=\"T_4c554_row2_col4\" class=\"data row2 col4\" >object</td>\n    </tr>\n    <tr>\n      <th id=\"T_4c554_level0_row3\" class=\"row_heading level0 row3\" >3</th>\n      <td id=\"T_4c554_row3_col0\" class=\"data row3 col0\" >sequence_counter</td>\n      <td id=\"T_4c554_row3_col1\" class=\"data row3 col1\" >0</td>\n      <td id=\"T_4c554_row3_col2\" class=\"data row3 col2\" >0.000000</td>\n      <td id=\"T_4c554_row3_col3\" class=\"data row3 col3\" >700</td>\n      <td id=\"T_4c554_row3_col4\" class=\"data row3 col4\" >int64</td>\n    </tr>\n    <tr>\n      <th id=\"T_4c554_level0_row4\" class=\"row_heading level0 row4\" >4</th>\n      <td id=\"T_4c554_row4_col0\" class=\"data row4 col0\" >subject</td>\n      <td id=\"T_4c554_row4_col1\" class=\"data row4 col1\" >0</td>\n      <td id=\"T_4c554_row4_col2\" class=\"data row4 col2\" >0.000000</td>\n      <td id=\"T_4c554_row4_col3\" class=\"data row4 col3\" >81</td>\n      <td id=\"T_4c554_row4_col4\" class=\"data row4 col4\" >object</td>\n    </tr>\n    <tr>\n      <th id=\"T_4c554_level0_row5\" class=\"row_heading level0 row5\" >5</th>\n      <td id=\"T_4c554_row5_col0\" class=\"data row5 col0\" >orientation</td>\n      <td id=\"T_4c554_row5_col1\" class=\"data row5 col1\" >0</td>\n      <td id=\"T_4c554_row5_col2\" class=\"data row5 col2\" >0.000000</td>\n      <td id=\"T_4c554_row5_col3\" class=\"data row5 col3\" >4</td>\n      <td id=\"T_4c554_row5_col4\" class=\"data row5 col4\" >object</td>\n    </tr>\n    <tr>\n      <th id=\"T_4c554_level0_row6\" class=\"row_heading level0 row6\" >6</th>\n      <td id=\"T_4c554_row6_col0\" class=\"data row6 col0\" >behavior</td>\n      <td id=\"T_4c554_row6_col1\" class=\"data row6 col1\" >0</td>\n      <td id=\"T_4c554_row6_col2\" class=\"data row6 col2\" >0.000000</td>\n      <td id=\"T_4c554_row6_col3\" class=\"data row6 col3\" >4</td>\n      <td id=\"T_4c554_row6_col4\" class=\"data row6 col4\" >object</td>\n    </tr>\n    <tr>\n      <th id=\"T_4c554_level0_row7\" class=\"row_heading level0 row7\" >7</th>\n      <td id=\"T_4c554_row7_col0\" class=\"data row7 col0\" >phase</td>\n      <td id=\"T_4c554_row7_col1\" class=\"data row7 col1\" >0</td>\n      <td id=\"T_4c554_row7_col2\" class=\"data row7 col2\" >0.000000</td>\n      <td id=\"T_4c554_row7_col3\" class=\"data row7 col3\" >2</td>\n      <td id=\"T_4c554_row7_col4\" class=\"data row7 col4\" >object</td>\n    </tr>\n    <tr>\n      <th id=\"T_4c554_level0_row8\" class=\"row_heading level0 row8\" >8</th>\n      <td id=\"T_4c554_row8_col0\" class=\"data row8 col0\" >gesture</td>\n      <td id=\"T_4c554_row8_col1\" class=\"data row8 col1\" >0</td>\n      <td id=\"T_4c554_row8_col2\" class=\"data row8 col2\" >0.000000</td>\n      <td id=\"T_4c554_row8_col3\" class=\"data row8 col3\" >18</td>\n      <td id=\"T_4c554_row8_col4\" class=\"data row8 col4\" >object</td>\n    </tr>\n  </tbody>\n</table>\n"},"metadata":{}}],"execution_count":8},{"cell_type":"markdown","source":"- Không có giá trị thiếu: Tất cả các cột trong bảng thống kê đều không có giá trị thiếu (Missing Count = 0), cho thấy dữ liệu của bạn rất đầy đủ.\n\n- Sự đa dạng trong dữ liệu: Các cột như row_id, sequence_id, và subject có số lượng giá trị duy nhất khá lớn, trong khi các cột như sequence_type, phase, và behavior có ít giá trị duy nhất hơn, cho thấy chúng có thể là các thông tin phân loại.\n\n- Kiểu dữ liệu: Hầu hết các cột đều có kiểu dữ liệu object, ngoại trừ sequence_counter có kiểu int64, điều này cho thấy hầu hết các cột chứa thông tin phân loại (string), chỉ có một cột chứa giá trị số nguyên.","metadata":{}},{"cell_type":"code","source":"#Thống kê tương tự cho nhân khẩu học: Tương tự như phần thống kê cảm biến nhưng áp dụng cho dữ liệu nhân khẩu học.\n\n# Cột nhân khẩu học (không loại trừ)\ndem_cols = train_dem_df.columns\n\n# Giá trị bị thiếu trong dữ liệu nhân khẩu học của train \nmissing_demo_train = pd.DataFrame({\n    'Feature': dem_cols,\n    '[TRAIN DEMO] Missing Count': train_dem_df[dem_cols].isnull().sum().values,\n    '[TRAIN DEMO] Missing %': (train_dem_df[dem_cols].isnull().sum().values / len(train_dem_df)) * 100\n})\n\n# Giá trị duy nhất được tính trong dữ liệu nhân khẩu học của train \nunique_demo_train = pd.DataFrame({\n    'Feature': dem_cols,\n    'Unique Values [TRAIN DEMO]': train_dem_df[dem_cols].nunique().values\n})\n\n# Data types\ndtypes_demo = pd.DataFrame({\n    'Feature': dem_cols,\n    'Data Type': train_dem_df[dem_cols].dtypes.values\n})\n\n# Tóm tắt hợp nhất (chỉ dành cho đào tạo)\ndemo_summary = (\n    missing_demo_train\n    .merge(unique_demo_train, on='Feature', how='left')\n    .merge(dtypes_demo, on='Feature', how='left')\n)\n\n# Hiển thị tóm tắt theo phong cách\ndemo_summary.style.background_gradient(cmap='viridis')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-17T08:37:15.924711Z","iopub.execute_input":"2025-08-17T08:37:15.925122Z","iopub.status.idle":"2025-08-17T08:37:15.949479Z","shell.execute_reply.started":"2025-08-17T08:37:15.925099Z","shell.execute_reply":"2025-08-17T08:37:15.948664Z"}},"outputs":[{"execution_count":9,"output_type":"execute_result","data":{"text/plain":"<pandas.io.formats.style.Styler at 0x7d71cd337e10>","text/html":"<style type=\"text/css\">\n#T_e9dee_row0_col1, #T_e9dee_row0_col2, #T_e9dee_row1_col1, #T_e9dee_row1_col2, #T_e9dee_row1_col3, #T_e9dee_row2_col1, #T_e9dee_row2_col2, #T_e9dee_row3_col1, #T_e9dee_row3_col2, #T_e9dee_row3_col3, #T_e9dee_row4_col1, #T_e9dee_row4_col2, #T_e9dee_row4_col3, #T_e9dee_row5_col1, #T_e9dee_row5_col2, #T_e9dee_row6_col1, #T_e9dee_row6_col2, #T_e9dee_row7_col1, #T_e9dee_row7_col2 {\n  background-color: #440154;\n  color: #f1f1f1;\n}\n#T_e9dee_row0_col3 {\n  background-color: #fde725;\n  color: #000000;\n}\n#T_e9dee_row2_col3 {\n  background-color: #31678e;\n  color: #f1f1f1;\n}\n#T_e9dee_row5_col3 {\n  background-color: #26828e;\n  color: #f1f1f1;\n}\n#T_e9dee_row6_col3 {\n  background-color: #3c4f8a;\n  color: #f1f1f1;\n}\n#T_e9dee_row7_col3 {\n  background-color: #472d7b;\n  color: #f1f1f1;\n}\n</style>\n<table id=\"T_e9dee\">\n  <thead>\n    <tr>\n      <th class=\"blank level0\" >&nbsp;</th>\n      <th id=\"T_e9dee_level0_col0\" class=\"col_heading level0 col0\" >Feature</th>\n      <th id=\"T_e9dee_level0_col1\" class=\"col_heading level0 col1\" >[TRAIN DEMO] Missing Count</th>\n      <th id=\"T_e9dee_level0_col2\" class=\"col_heading level0 col2\" >[TRAIN DEMO] Missing %</th>\n      <th id=\"T_e9dee_level0_col3\" class=\"col_heading level0 col3\" >Unique Values [TRAIN DEMO]</th>\n      <th id=\"T_e9dee_level0_col4\" class=\"col_heading level0 col4\" >Data Type</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th id=\"T_e9dee_level0_row0\" class=\"row_heading level0 row0\" >0</th>\n      <td id=\"T_e9dee_row0_col0\" class=\"data row0 col0\" >subject</td>\n      <td id=\"T_e9dee_row0_col1\" class=\"data row0 col1\" >0</td>\n      <td id=\"T_e9dee_row0_col2\" class=\"data row0 col2\" >0.000000</td>\n      <td id=\"T_e9dee_row0_col3\" class=\"data row0 col3\" >81</td>\n      <td id=\"T_e9dee_row0_col4\" class=\"data row0 col4\" >object</td>\n    </tr>\n    <tr>\n      <th id=\"T_e9dee_level0_row1\" class=\"row_heading level0 row1\" >1</th>\n      <td id=\"T_e9dee_row1_col0\" class=\"data row1 col0\" >adult_child</td>\n      <td id=\"T_e9dee_row1_col1\" class=\"data row1 col1\" >0</td>\n      <td id=\"T_e9dee_row1_col2\" class=\"data row1 col2\" >0.000000</td>\n      <td id=\"T_e9dee_row1_col3\" class=\"data row1 col3\" >2</td>\n      <td id=\"T_e9dee_row1_col4\" class=\"data row1 col4\" >int64</td>\n    </tr>\n    <tr>\n      <th id=\"T_e9dee_level0_row2\" class=\"row_heading level0 row2\" >2</th>\n      <td id=\"T_e9dee_row2_col0\" class=\"data row2 col0\" >age</td>\n      <td id=\"T_e9dee_row2_col1\" class=\"data row2 col1\" >0</td>\n      <td id=\"T_e9dee_row2_col2\" class=\"data row2 col2\" >0.000000</td>\n      <td id=\"T_e9dee_row2_col3\" class=\"data row2 col3\" >28</td>\n      <td id=\"T_e9dee_row2_col4\" class=\"data row2 col4\" >int64</td>\n    </tr>\n    <tr>\n      <th id=\"T_e9dee_level0_row3\" class=\"row_heading level0 row3\" >3</th>\n      <td id=\"T_e9dee_row3_col0\" class=\"data row3 col0\" >sex</td>\n      <td id=\"T_e9dee_row3_col1\" class=\"data row3 col1\" >0</td>\n      <td id=\"T_e9dee_row3_col2\" class=\"data row3 col2\" >0.000000</td>\n      <td id=\"T_e9dee_row3_col3\" class=\"data row3 col3\" >2</td>\n      <td id=\"T_e9dee_row3_col4\" class=\"data row3 col4\" >int64</td>\n    </tr>\n    <tr>\n      <th id=\"T_e9dee_level0_row4\" class=\"row_heading level0 row4\" >4</th>\n      <td id=\"T_e9dee_row4_col0\" class=\"data row4 col0\" >handedness</td>\n      <td id=\"T_e9dee_row4_col1\" class=\"data row4 col1\" >0</td>\n      <td id=\"T_e9dee_row4_col2\" class=\"data row4 col2\" >0.000000</td>\n      <td id=\"T_e9dee_row4_col3\" class=\"data row4 col3\" >2</td>\n      <td id=\"T_e9dee_row4_col4\" class=\"data row4 col4\" >int64</td>\n    </tr>\n    <tr>\n      <th id=\"T_e9dee_level0_row5\" class=\"row_heading level0 row5\" >5</th>\n      <td id=\"T_e9dee_row5_col0\" class=\"data row5 col0\" >height_cm</td>\n      <td id=\"T_e9dee_row5_col1\" class=\"data row5 col1\" >0</td>\n      <td id=\"T_e9dee_row5_col2\" class=\"data row5 col2\" >0.000000</td>\n      <td id=\"T_e9dee_row5_col3\" class=\"data row5 col3\" >37</td>\n      <td id=\"T_e9dee_row5_col4\" class=\"data row5 col4\" >float64</td>\n    </tr>\n    <tr>\n      <th id=\"T_e9dee_level0_row6\" class=\"row_heading level0 row6\" >6</th>\n      <td id=\"T_e9dee_row6_col0\" class=\"data row6 col0\" >shoulder_to_wrist_cm</td>\n      <td id=\"T_e9dee_row6_col1\" class=\"data row6 col1\" >0</td>\n      <td id=\"T_e9dee_row6_col2\" class=\"data row6 col2\" >0.000000</td>\n      <td id=\"T_e9dee_row6_col3\" class=\"data row6 col3\" >21</td>\n      <td id=\"T_e9dee_row6_col4\" class=\"data row6 col4\" >int64</td>\n    </tr>\n    <tr>\n      <th id=\"T_e9dee_level0_row7\" class=\"row_heading level0 row7\" >7</th>\n      <td id=\"T_e9dee_row7_col0\" class=\"data row7 col0\" >elbow_to_wrist_cm</td>\n      <td id=\"T_e9dee_row7_col1\" class=\"data row7 col1\" >0</td>\n      <td id=\"T_e9dee_row7_col2\" class=\"data row7 col2\" >0.000000</td>\n      <td id=\"T_e9dee_row7_col3\" class=\"data row7 col3\" >12</td>\n      <td id=\"T_e9dee_row7_col4\" class=\"data row7 col4\" >float64</td>\n    </tr>\n  </tbody>\n</table>\n"},"metadata":{}}],"execution_count":9},{"cell_type":"markdown","source":"- Không có giá trị thiếu: Các cột nhân khẩu học đều không có giá trị thiếu, cho thấy dữ liệu đầy đủ và sẵn sàng để phân tích.\n\n- Sự đa dạng trong dữ liệu: Các cột như subject, age, và height_cm có sự đa dạng về giá trị duy nhất, trong khi các cột như sex, handedness có ít giá trị duy nhất hơn, cho thấy đây là các cột phân loại.\n\n- Kiểu dữ liệu: Các cột phần lớn có kiểu dữ liệu int64 hoặc float64, cho thấy dữ liệu chủ yếu là số nguyên hoặc số thực. Các cột như subject có kiểu dữ liệu object, có thể là các chuỗi ký tự.","metadata":{}},{"cell_type":"markdown","source":"### 2.2.2. Sensor-Based Features (Tính năng dựa trên cảm biến)","metadata":{}},{"cell_type":"markdown","source":"#### **NOTE:**\n* acc_: Gia tốc kế.\n* rot_: Cảm biến quay.\n* thm_: Nhiệt độ, độ ẩm.\n* tof_: Khoảng cách.\n","metadata":{}},{"cell_type":"markdown","source":"# 3. EDA","metadata":{}},{"cell_type":"markdown","source":"## 3.1. Numerical Feature Distribution Analysis (Phân tích phân phối tính năng số) (Phân tích đơn biến)","metadata":{}},{"cell_type":"markdown","source":"### 3.1.1 Participant & Contextual Features (Tính năng của người tham gia và bối cảnh)","metadata":{}},{"cell_type":"markdown","source":"### 3.1.2 Sensor-Based Features (Tính năng dựa trên cảm biến)","metadata":{}},{"cell_type":"markdown","source":"**Mục tiêu:**\nTrích xuất các đặc trưng thống kê (mean, std, max) từ dữ liệu sensor (acceleration, rotation, temperature, ToF) theo từng sequence_id để phục vụ mô hình học máy hoặc phân tích dữ liệu.","metadata":{}},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\n\n# 1) Sao chép đào tạo và kiểm tra để chúng ta không sửa đổi DataFrame gốc\ntrain_temp = train_df.copy()\ntest_temp  = test_df.copy()\n\n# 2) GIA TỐC KẾ: tính toán độ lớn tại mỗi dấu thời gian\ntrain_temp['acc_mag'] = np.sqrt(\n    train_temp['acc_x']**2 + train_temp['acc_y']**2 + train_temp['acc_z']**2\n)\ntest_temp['acc_mag'] = np.sqrt(\n    test_temp['acc_x']**2 + test_temp['acc_y']**2 + test_temp['acc_z']**2\n)\n\n# 3) ROTATION: tính toán “góc quay” từ thành phần quaternion w\n# (Lưu ý: rot_w nằm trong [-1,1], do đó arccos hợp lệ. Chúng tôi bỏ qua NaN nếu có.)\ntrain_temp['rot_angle'] = 2 * np.arccos(train_temp['rot_w'].clip(-1,1))\ntest_temp['rot_angle']  = 2 * np.arccos(test_temp['rot_w'].clip(-1,1))\n\n# 4) Nhóm theo sequence_id và tổng hợp các tóm tắt gia tốc kế\nacc_agg_funcs = {\n    'acc_mag': ['mean', 'std', 'max']\n}\ntrain_acc_summary = train_temp.groupby('sequence_id').agg(acc_agg_funcs)\ntest_acc_summary  = test_temp.groupby('sequence_id').agg(acc_agg_funcs)\n\n# Làm phẳng cột MultiIndex\ntrain_acc_summary.columns = ['acc_mag_' + stat for stat in ['mean', 'std', 'max']]\ntest_acc_summary.columns  = ['acc_mag_' + stat for stat in ['mean', 'std', 'max']]\n\n# 5) Nhóm theo sequence_id và tổng hợp tóm tắt vòng quay\nrot_agg_funcs = {\n    'rot_angle': ['mean', 'std', 'max']\n}\ntrain_rot_summary = train_temp.groupby('sequence_id').agg(rot_agg_funcs)\ntest_rot_summary  = test_temp.groupby('sequence_id').agg(rot_agg_funcs)\n\ntrain_rot_summary.columns = ['rot_angle_' + stat for stat in ['mean', 'std', 'max']]\ntest_rot_summary.columns  = ['rot_angle_' + stat for stat in ['mean', 'std', 'max']]\n\n# 6) NHIỆT ĐỘ: năm cảm biến thm_1 … thm_5\nthm_cols = [f\"thm_{i}\" for i in range(1, 6)]\n\n# Xác định hàm tổng hợp: trung bình + độ lệch chuẩn\nthm_agg_funcs = {col: ['mean', 'std'] for col in thm_cols}\n\ntrain_thm_summary = train_temp.groupby('sequence_id').agg(thm_agg_funcs)\ntest_thm_summary  = test_temp.groupby('sequence_id').agg(thm_agg_funcs)\n\n# Làm phẳng các cột MultiIndex\nflattened_thm_cols = []\nfor sensor in thm_cols:\n    for stat in ['mean','std']:\n        flattened_thm_cols.append(f\"{sensor}_{stat}\")\n\ntrain_thm_summary.columns = flattened_thm_cols\ntest_thm_summary.columns  = flattened_thm_cols\n\n# 7) THỜI GIAN BAY: mỗi cảm biến i có 64 cột pixel: tof_i_v0 … tof_i_v63\n# Chúng ta sẽ tạo một “tof_i_mean_at_ts” cho mỗi dấu thời gian, sau đó tổng hợp theo từng chuỗi.\n\ndef compute_tof_sequence_summary(df):\n    # Khởi tạo một dict để giữ DataFrames theo từng chuỗi\n    seq_summaries = {}\n\n    for i in range(1, 6):\n        # Xây dựng danh sách các cột cho cảm biến i\n        tof_cols = [f\"tof_{i}_v{pix}\" for pix in range(64)]\n        # Thay thế -1 bằng NaN để chúng không làm lệch giá trị trung bình; chuyển đổi sang float\n        ts_grid = df[tof_cols].replace(-1, np.nan).astype(float)\n        # Tính toán “trung bình trên tất cả 64 pixel” cho mỗi dấu thời gian\n        df[f\"tof_{i}_mean_at_ts\"] = ts_grid.mean(axis=1)\n    \n   # Bây giờ, nhóm theo id chuỗi và tính giá trị trung bình và độ lệch chuẩn của các giá trị trung bình đó\n    agg_dict = {f\"tof_{i}_mean_at_ts\": ['mean','std'] for i in range(1, 6)}\n    summary = df.groupby('sequence_id').agg(agg_dict)\n    # Làm phẳng các cột MultiIndex\n    flat_cols = [f\"tof_{i}_{stat}\" for i in range(1, 6) for stat in ['mean','std']]\n    summary.columns = flat_cols\n    return summary\n\ntrain_tof_summary = compute_tof_sequence_summary(train_temp)\ntest_tof_summary  = compute_tof_sequence_summary(test_temp)\n\n# 8) Hợp nhất các tóm tắt accel, rotation, thm, tof (trên sequence_id)\ntrain_sensor_summary = (\n    train_acc_summary\n    .join(train_rot_summary, how='outer')\n    .join(train_thm_summary, how='outer')\n    .join(train_tof_summary, how='outer')\n)\n\ntest_sensor_summary = (\n    test_acc_summary\n    .join(test_rot_summary, how='outer')\n    .join(test_thm_summary, how='outer')\n    .join(test_tof_summary, how='outer')\n)\n\n# 9) Thêm cột “Dataset” để chúng ta có thể thực hiện box+hist song song\ntrain_sensor_summary['Dataset'] = 'Train'\ntest_sensor_summary['Dataset']  = 'Test'\n\n# 10) Ghép nối thành một DataFrame để vẽ đồ thị\ncombined_sensor_summary = pd.concat(\n    [train_sensor_summary, test_sensor_summary],\n    axis=0\n).reset_index(drop=True)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-17T08:37:15.952348Z","iopub.execute_input":"2025-08-17T08:37:15.952614Z","iopub.status.idle":"2025-08-17T08:37:21.706826Z","shell.execute_reply.started":"2025-08-17T08:37:15.952596Z","shell.execute_reply":"2025-08-17T08:37:21.706029Z"}},"outputs":[{"name":"stderr","text":"/usr/local/lib/python3.11/dist-packages/pandas/core/computation/expressions.py:73: RuntimeWarning: invalid value encountered in greater_equal\n  return op(a, b)\n/usr/local/lib/python3.11/dist-packages/pandas/core/computation/expressions.py:73: RuntimeWarning: invalid value encountered in less_equal\n  return op(a, b)\n/usr/local/lib/python3.11/dist-packages/pandas/core/arraylike.py:399: RuntimeWarning: invalid value encountered in arccos\n  result = getattr(ufunc, method)(*inputs, **kwargs)\n","output_type":"stream"}],"execution_count":10},{"cell_type":"markdown","source":"## 3.3 Target Feature Analysis (Univariate Analysis)","metadata":{}},{"cell_type":"markdown","source":"### 3.4.2 Sensor‐Based Differentiation Across Demographics and Physiology Features","metadata":{}},{"cell_type":"code","source":"import numpy as np\nimport matplotlib.pyplot as plt\n\n# (1) Sáp nhập train_demographics vào train_df nếu chưa thực hiện\ntrain_df = train_df.merge(\n    train_dem_df,\n    on=\"subject\",\n    how=\"left\"\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-17T08:37:21.707647Z","iopub.execute_input":"2025-08-17T08:37:21.707931Z","iopub.status.idle":"2025-08-17T08:37:22.351026Z","shell.execute_reply.started":"2025-08-17T08:37:21.707906Z","shell.execute_reply":"2025-08-17T08:37:22.350422Z"}},"outputs":[],"execution_count":11},{"cell_type":"markdown","source":"## Xử lý missing values","metadata":{}},{"cell_type":"markdown","source":"### 1. IMU – Gia tốc/quaternion (acc_*, rot_w/x/y/z)","metadata":{}},{"cell_type":"code","source":"def fix_imu(df):\n    imu_cols = [c for c in df.columns if c.startswith((\"acc_\", \"rot_\"))]\n    def _seq_fix(g):\n        g[imu_cols] = g[imu_cols].interpolate(limit_direction=\"both\")\n        # renormalize quaternion\n        q = g[[\"rot_w\",\"rot_x\",\"rot_y\",\"rot_z\"]].to_numpy(float)\n        n = (q**2).sum(1)**0.5\n        n[n==0] = 1.0\n        q = q / n[:,None]\n        g[[\"rot_w\",\"rot_x\",\"rot_y\",\"rot_z\"]] = q\n        return g\n    return df.groupby(\"sequence_id\", group_keys=False).apply(_seq_fix)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-17T08:37:22.351756Z","iopub.execute_input":"2025-08-17T08:37:22.351979Z","iopub.status.idle":"2025-08-17T08:37:22.357464Z","shell.execute_reply.started":"2025-08-17T08:37:22.351962Z","shell.execute_reply":"2025-08-17T08:37:22.356586Z"}},"outputs":[],"execution_count":12},{"cell_type":"markdown","source":"### 2. Thermopile (thm_1..thm_5)","metadata":{}},{"cell_type":"code","source":"def fix_thm(df):\n    thm = [f\"thm_{i}\" for i in range(1,6)]\n    return df.groupby(\"sequence_id\", group_keys=False)[thm].apply(\n        lambda g: g.interpolate(limit_direction=\"both\").ffill().bfill()\n    )","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-17T08:37:22.358325Z","iopub.execute_input":"2025-08-17T08:37:22.358594Z","iopub.status.idle":"2025-08-17T08:37:22.372273Z","shell.execute_reply.started":"2025-08-17T08:37:22.358573Z","shell.execute_reply":"2025-08-17T08:37:22.371577Z"}},"outputs":[],"execution_count":13},{"cell_type":"markdown","source":"### 3. ToF – 5 cảm biến × 64 pixel (tof_i_vj)","metadata":{}},{"cell_type":"code","source":"def fix_tof_and_reduce(df):\n    # 1) sentinel -> NaN + flag\n    tof_pix = [c for c in df.columns if c.startswith(\"tof_\") and \"_v\" in c]\n    df[tof_pix] = df[tof_pix].replace(-1, np.nan)\n    # optional flags per sensor\n    for i in range(1,6):\n        cols = [f\"tof_{i}_v{p}\" for p in range(64) if f\"tof_{i}_v{p}\" in df]\n        df[f\"tof_{i}_missing_frac\"] = df[cols].isna().mean(axis=1)\n        df[f\"tof_{i}_mean\"] = df[cols].mean(axis=1)  # dimension reduction\n    # 2) interpolate the 5 means\n    mean_cols = [f\"tof_{i}_mean\" for i in range(1,6)]\n    df[mean_cols] = df.groupby(\"sequence_id\", group_keys=False)[mean_cols].apply(\n        lambda g: g.interpolate(limit_direction=\"both\").ffill().bfill()\n    )\n    # 3) drop heavy pixel columns to save RAM\n    df.drop(columns=tof_pix, inplace=True)\n    return df","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-17T08:37:22.373163Z","iopub.execute_input":"2025-08-17T08:37:22.373463Z","iopub.status.idle":"2025-08-17T08:37:22.384909Z","shell.execute_reply.started":"2025-08-17T08:37:22.373439Z","shell.execute_reply":"2025-08-17T08:37:22.384335Z"}},"outputs":[],"execution_count":14},{"cell_type":"markdown","source":"### 4. Pha/nhãn & metadata","metadata":{}},{"cell_type":"code","source":"from sklearn.preprocessing import LabelEncoder\nle_gesture = LabelEncoder().fit(train_df[\"gesture\"].astype(str))\ntrain_df[\"gesture_id\"] = le_gesture.transform(train_df[\"gesture\"].astype(str))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-17T08:37:22.385713Z","iopub.execute_input":"2025-08-17T08:37:22.38594Z","iopub.status.idle":"2025-08-17T08:37:22.501108Z","shell.execute_reply.started":"2025-08-17T08:37:22.385917Z","shell.execute_reply":"2025-08-17T08:37:22.500509Z"}},"outputs":[],"execution_count":15},{"cell_type":"markdown","source":"### 5. Pipeline tiền xử lý","metadata":{}},{"cell_type":"code","source":"def minimal_preprocess(df):\n    df = df.copy()\n    # 1) IMU\n    df = fix_imu(df)\n    # 2) Thermopile\n    thm_fixed = fix_thm(df)  # returns only thm cols\n    df[thm_fixed.columns] = thm_fixed\n    # 3) ToF -> means + flags, drop pixels\n    df = fix_tof_and_reduce(df)\n    # 4) Feature cơ bản (ví dụ):\n    df[\"acc_mag\"] = np.sqrt(df[\"acc_x\"]**2 + df[\"acc_y\"]**2 + df[\"acc_z\"]**2)\n    df[\"rot_angle\"] = 2*np.arccos(np.clip(df[\"rot_w\"], -1, 1))\n    return df","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-17T08:37:22.50192Z","iopub.execute_input":"2025-08-17T08:37:22.502626Z","iopub.status.idle":"2025-08-17T08:37:22.50735Z","shell.execute_reply.started":"2025-08-17T08:37:22.502602Z","shell.execute_reply":"2025-08-17T08:37:22.5065Z"}},"outputs":[],"execution_count":16}]}