{"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":"nvidiaTeslaT4","dataSources":[{"sourceId":102335,"databundleVersionId":12518947,"isSourceIdPinned":false,"sourceType":"competition"}],"dockerImageVersionId":31090,"isInternetEnabled":false,"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-28T11:39:15.429117Z","iopub.execute_input":"2025-08-28T11:39:15.429420Z","iopub.status.idle":"2025-08-28T11:39:17.676104Z","shell.execute_reply.started":"2025-08-28T11:39:15.429399Z","shell.execute_reply":"2025-08-28T11:39:17.675117Z"}},"outputs":[],"execution_count":null},{"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-28T11:39:17.677344Z","iopub.execute_input":"2025-08-28T11:39:17.677813Z","iopub.status.idle":"2025-08-28T11:39:51.381724Z","shell.execute_reply.started":"2025-08-28T11:39:17.677780Z","shell.execute_reply":"2025-08-28T11:39:51.381085Z"}},"outputs":[],"execution_count":null},{"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-28T11:39:51.382517Z","iopub.execute_input":"2025-08-28T11:39:51.382741Z","iopub.status.idle":"2025-08-28T11:39:52.265965Z","shell.execute_reply.started":"2025-08-28T11:39:51.382724Z","shell.execute_reply":"2025-08-28T11:39:52.265139Z"}},"outputs":[],"execution_count":null},{"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-28T11:39:52.268018Z","iopub.execute_input":"2025-08-28T11:39:52.268245Z","iopub.status.idle":"2025-08-28T11:39:57.269615Z","shell.execute_reply.started":"2025-08-28T11:39:52.268225Z","shell.execute_reply":"2025-08-28T11:39:57.268782Z"}},"outputs":[],"execution_count":null},{"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-28T11:39:57.270448Z","iopub.execute_input":"2025-08-28T11:39:57.270803Z","iopub.status.idle":"2025-08-28T11:39:58.133358Z","shell.execute_reply.started":"2025-08-28T11:39:57.270773Z","shell.execute_reply":"2025-08-28T11:39:58.132549Z"}},"outputs":[],"execution_count":null},{"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-28T11:39:58.134198Z","iopub.execute_input":"2025-08-28T11:39:58.134727Z","iopub.status.idle":"2025-08-28T11:39:58.818200Z","shell.execute_reply.started":"2025-08-28T11:39:58.134693Z","shell.execute_reply":"2025-08-28T11:39:58.817541Z"}},"outputs":[],"execution_count":null},{"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-28T11:39:58.819115Z","iopub.execute_input":"2025-08-28T11:39:58.819429Z","iopub.status.idle":"2025-08-28T11:40:08.177840Z","shell.execute_reply.started":"2025-08-28T11:39:58.819370Z","shell.execute_reply":"2025-08-28T11:40:08.176926Z"}},"outputs":[],"execution_count":null},{"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-28T11:40:08.179125Z","iopub.execute_input":"2025-08-28T11:40:08.179372Z","iopub.status.idle":"2025-08-28T11:40:09.264509Z","shell.execute_reply.started":"2025-08-28T11:40:08.179352Z","shell.execute_reply":"2025-08-28T11:40:09.263769Z"}},"outputs":[],"execution_count":null},{"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-28T11:40:09.265234Z","iopub.execute_input":"2025-08-28T11:40:09.265594Z","iopub.status.idle":"2025-08-28T11:40:09.292684Z","shell.execute_reply.started":"2025-08-28T11:40:09.265576Z","shell.execute_reply":"2025-08-28T11:40:09.291717Z"}},"outputs":[],"execution_count":null},{"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-28T11:40:09.296055Z","iopub.execute_input":"2025-08-28T11:40:09.296429Z","iopub.status.idle":"2025-08-28T11:40:15.120925Z","shell.execute_reply.started":"2025-08-28T11:40:09.296409Z","shell.execute_reply":"2025-08-28T11:40:15.120179Z"}},"outputs":[],"execution_count":null},{"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-28T11:40:15.121723Z","iopub.execute_input":"2025-08-28T11:40:15.122020Z","iopub.status.idle":"2025-08-28T11:40:15.770112Z","shell.execute_reply.started":"2025-08-28T11:40:15.121994Z","shell.execute_reply":"2025-08-28T11:40:15.769244Z"}},"outputs":[],"execution_count":null},{"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-28T11:40:15.771037Z","iopub.execute_input":"2025-08-28T11:40:15.771242Z","iopub.status.idle":"2025-08-28T11:40:15.777167Z","shell.execute_reply.started":"2025-08-28T11:40:15.771226Z","shell.execute_reply":"2025-08-28T11:40:15.776239Z"}},"outputs":[],"execution_count":null},{"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-28T11:40:15.778032Z","iopub.execute_input":"2025-08-28T11:40:15.778441Z","iopub.status.idle":"2025-08-28T11:40:15.793360Z","shell.execute_reply.started":"2025-08-28T11:40:15.778420Z","shell.execute_reply":"2025-08-28T11:40:15.792461Z"}},"outputs":[],"execution_count":null},{"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-28T11:40:15.794353Z","iopub.execute_input":"2025-08-28T11:40:15.794624Z","iopub.status.idle":"2025-08-28T11:40:15.808123Z","shell.execute_reply.started":"2025-08-28T11:40:15.794603Z","shell.execute_reply":"2025-08-28T11:40:15.807328Z"}},"outputs":[],"execution_count":null},{"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-28T11:40:15.809084Z","iopub.execute_input":"2025-08-28T11:40:15.809508Z","iopub.status.idle":"2025-08-28T11:40:15.939049Z","shell.execute_reply.started":"2025-08-28T11:40:15.809460Z","shell.execute_reply":"2025-08-28T11:40:15.938189Z"}},"outputs":[],"execution_count":null},{"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-28T11:40:15.940098Z","iopub.execute_input":"2025-08-28T11:40:15.940412Z","iopub.status.idle":"2025-08-28T11:40:15.945888Z","shell.execute_reply.started":"2025-08-28T11:40:15.940386Z","shell.execute_reply":"2025-08-28T11:40:15.945099Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Notebook 4 – Multimodal Fusion Models (Core 🚀)\n\n**Mục tiêu:** Kiểm chứng giá trị gia tăng của **ToF & Thermopile** so với **IMU-only** bằng các chiến lược **fusion**:\n- **Early Fusion** (concat raw/embedding theo thời gian),\n- **Late Fusion** (encoder riêng từng modality → concat → MLP),\n- **Attention Fusion** (tự học trọng số giữa modalities),\n- **Mixture of Experts (MoE)** (gating chọn chuyên gia),\n- **Ensemble** (soft voting/stacking).\n\n**So sánh & phân tích:**\n- Ablation: **IMU-only**, **IMU+Thermo**, **IMU+ToF**, **All (IMU+Thermo+ToF)**.\n- **Macro-F1** (val/test), **số tham số**, **thời gian train**.\n- **Visualization**: attention weights (tỷ trọng theo modality).\n- **Thống kê**: t-test / Wilcoxon (nhiều seed) để chứng minh Fusion > Single có ý nghĩa thống kê.\n\n👉 **Vai trò**: Trả lời câu hỏi nghiên cứu chính: *ToF & Thermopile đem lại bao nhiêu giá trị thêm?*\n","metadata":{}},{"cell_type":"code","source":"# %% [setup]\nimport os, random, warnings, time\nwarnings.filterwarnings('ignore')\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\ntry:\n    import torch\n    import torch.nn as nn\n    import torch.nn.functional as F\n    from torch.utils.data import Dataset, DataLoader\n    from torch.optim import Adam\n    from sklearn.metrics import f1_score\n    HAS_TORCH = True\nexcept Exception as e:\n    HAS_TORCH = False\n    print('PyTorch chưa sẵn sàng, cần cài torch để huấn luyện. Lỗi:', e)\n\n# Thống kê\ntry:\n    from scipy.stats import ttest_rel, wilcoxon\n    HAS_SCIPY = True\nexcept Exception as e:\n    HAS_SCIPY = False\n    print('Chưa có SciPy: phần kiểm định thống kê sẽ bỏ qua. Lỗi:', e)\n\nDEVICE = 'cuda' if HAS_TORCH and torch.cuda.is_available() else 'cpu'\nBASE_SEED = 123\nrandom.seed(BASE_SEED); np.random.seed(BASE_SEED)\nif HAS_TORCH:\n    torch.manual_seed(BASE_SEED)\n    if DEVICE=='cuda': torch.cuda.manual_seed_all(BASE_SEED)\nprint({'torch': HAS_TORCH, 'device': DEVICE, 'scipy': HAS_SCIPY})\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-28T11:40:15.946964Z","iopub.execute_input":"2025-08-28T11:40:15.947284Z","iopub.status.idle":"2025-08-28T11:40:19.451510Z","shell.execute_reply.started":"2025-08-28T11:40:15.947253Z","shell.execute_reply":"2025-08-28T11:40:19.450576Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## 1) Cấu hình & Dữ liệu\n\n- Dữ liệu 3 modality:\n  - **IMU**: chuỗi 1D `[N, T, IMU_CH]`\n  - **Thermopile**: chuỗi 1D `[N, T, THERM_CH]`\n  - **ToF**: lưới 2D theo thời gian `[N, T, H, W]`\n- Có thể trỏ `DATA_PATH` tới `.npz` thật có keys: `imu, thermo, tof, label`.\n- Nếu để trống sẽ **sinh synthetic dataset** (đủ để demo toàn bộ pipeline).\n","metadata":{}},{"cell_type":"code","source":"# %% [config_and_data]\nCONFIG = {\n    'DATA_PATH': '',  # ví dụ '/mnt/data/your_dataset.npz'\n    'N_SAMPLES': 900,\n    'N_CLASSES': 6,\n    'T': 64,\n    'IMU_CH': 6,\n    'THERM_CH': 8,\n    'TOF_H': 8, 'TOF_W': 8,\n\n    # huấn luyện\n    'BATCH_SIZE': 64,\n    'MAX_EPOCHS': 8,\n    'LR': 1e-3,\n    'WEIGHT_DECAY': 1e-4,\n    'EARLY_STOP_PATIENCE': 4,\n\n    # lặp lại để test thống kê\n    'N_REPEATS': 3,                 # tăng lên 5–10 nếu muốn kiểm định mạnh hơn\n    'SEEDS': [123, 321, 777],       # sẽ tự cắt theo N_REPEATS\n\n    # kiến trúc\n    'EMB_D': 64,                    # chiều embedding cho mỗi modality\n    'FUSE_HIDDEN': 128,             # hidden cho aggregator/head\n    'DROPOUT': 0.2,\n\n    # thí nghiệm chính (ablation + fusion)\n    'RUNS': [\n        # Baselines đơn kênh\n        ('IMU_ONLY',         {'imu':True,  'thermo':False,'tof':False, 'fusion':'late'}),\n        ('THERMO_ONLY',      {'imu':False, 'thermo':True, 'tof':False, 'fusion':'late'}),\n        ('TOF_ONLY',         {'imu':False, 'thermo':False,'tof':True,  'fusion':'late'}),\n\n        # Ablation: Late Fusion\n        ('LATE_IMU+THERMO',  {'imu':True,  'thermo':True, 'tof':False, 'fusion':'late'}),\n        ('LATE_IMU+TOF',     {'imu':True,  'thermo':False,'tof':True,  'fusion':'late'}),\n        ('LATE_ALL',         {'imu':True,  'thermo':True, 'tof':True,  'fusion':'late'}),\n\n        # Early Fusion (All)\n        ('EARLY_ALL',        {'imu':True,  'thermo':True, 'tof':True,  'fusion':'early'}),\n\n        # Attention Fusion (All) - có visualization weights\n        ('ATTN_ALL',         {'imu':True,  'thermo':True, 'tof':True,  'fusion':'attn'}),\n\n        # Mixture of Experts (All)\n        ('MOE_ALL',          {'imu':True,  'thermo':True, 'tof':True,  'fusion':'moe'}),\n\n        # Ensemble soft voting (train 3 đơn kênh trước rồi vote)\n        ('ENSEMBLE_SOFT',    {'imu':True,  'thermo':True, 'tof':True,  'fusion':'ensemble'}),\n    ]\n}\n\ndef make_synthetic(cfg):\n    N, C, T = cfg['N_SAMPLES'], cfg['N_CLASSES'], cfg['T']\n    IMU_CH, THERM_CH = cfg['IMU_CH'], cfg['THERM_CH']\n    H, W = cfg['TOF_H'], cfg['TOF_W']\n    y = np.random.randint(0, C, size=N)\n    imu = np.random.randn(N, T, IMU_CH).astype('float32')\n    thermo = (0.3*np.random.randn(N, T, THERM_CH) + 0.1).astype('float32')\n    tof = (np.random.randn(N, T, H, W)*0.2 + 2.5).astype('float32')\n    # pattern theo lớp\n    for cls in range(C):\n        idx = y==cls\n        imu[idx] += (cls - C/2) * 0.15\n        thermo[idx] += (C/2 - cls) * 0.1\n        rr, cc = np.mgrid[:H, :W]\n        cr, cc0 = (cls % H), (cls % W)\n        mask = np.exp(-((rr-cr)**2 + (cc-cc0)**2)/(2*(H/4)**2)).astype('float32')\n        tof[idx] += mask[None, None, :, :]\n    return imu, thermo, tof, y.astype('int64')\n\nDATA_PATH = CONFIG['DATA_PATH']\nif DATA_PATH and os.path.exists(DATA_PATH):\n    data = np.load(DATA_PATH)\n    imu = data['imu'].astype('float32')\n    thermo = data['thermo'].astype('float32')\n    tof = data['tof'].astype('float32')\n    y = data['label'].astype('int64')\n    print('Loaded real dataset:', DATA_PATH)\nelse:\n    imu, thermo, tof, y = make_synthetic(CONFIG)\n    print('Using synthetic dataset')\n\nN, T, IMU_CH = imu.shape\nTHERM_CH = thermo.shape[-1]\nH, W = tof.shape[2], tof.shape[3]\nN_CLASSES = int(y.max())+1\nprint({'N': N, 'T': T, 'IMU_CH': IMU_CH, 'THERM_CH': THERM_CH, 'ToF': (H, W), 'Classes': N_CLASSES})\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-28T11:40:19.452533Z","iopub.execute_input":"2025-08-28T11:40:19.453145Z","iopub.status.idle":"2025-08-28T11:40:19.626252Z","shell.execute_reply.started":"2025-08-28T11:40:19.453111Z","shell.execute_reply":"2025-08-28T11:40:19.625467Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## 2) Chia tập & Dataloader\n\n- Chia `train/val/test` theo tỷ lệ cố định.\n- `SeqDataset` trả về `{'imu','thermo','tof','y'}` để các mô hình fusion dùng chung.\n","metadata":{}},{"cell_type":"code","source":"# %% [split_dataloader]\nidx = np.arange(N); np.random.shuffle(idx)\nTEST = int(0.15 * N)\nVAL  = int(0.15 * N)\ntest_idx  = idx[:TEST]\nval_idx   = idx[TEST:TEST+VAL]\ntrain_idx = idx[TEST+VAL:]\n\ndef take(a, ind): return a[ind]\nsplit = {\n    'train': {'imu': take(imu, train_idx), 'thermo': take(thermo, train_idx), 'tof': take(tof, train_idx), 'y': take(y, train_idx)},\n    'val':   {'imu': take(imu, val_idx),   'thermo': take(thermo, val_idx),   'tof': take(tof, val_idx),   'y': take(y, val_idx)},\n    'test':  {'imu': take(imu, test_idx),  'thermo': take(thermo, test_idx),  'tof': take(tof, test_idx),  'y': take(y, test_idx)},\n}\nfor k in split:\n    print(k, {kk: v.shape for kk, v in split[k].items()})\n\nif HAS_TORCH:\n    class SeqDataset(Dataset):\n        def __init__(self, pack):\n            self.imu = pack['imu']; self.thermo = pack['thermo']; self.tof = pack['tof']; self.y = pack['y']\n        def __len__(self): return self.y.shape[0]\n        def __getitem__(self, i):\n            return {\n                'imu': torch.from_numpy(self.imu[i]),\n                'thermo': torch.from_numpy(self.thermo[i]),\n                'tof': torch.from_numpy(self.tof[i]),\n                'y': torch.tensor(int(self.y[i]))\n            }\n\n    loaders = {}\n    for name in ['train', 'val', 'test']:\n        ds = SeqDataset(split[name])\n        loaders[name] = DataLoader(ds, batch_size=CONFIG['BATCH_SIZE'], shuffle=(name=='train'))\nelse:\n    print('Chưa có torch – bỏ qua Dataloader')\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-28T11:40:19.627088Z","iopub.execute_input":"2025-08-28T11:40:19.627372Z","iopub.status.idle":"2025-08-28T11:40:19.642846Z","shell.execute_reply.started":"2025-08-28T11:40:19.627347Z","shell.execute_reply":"2025-08-28T11:40:19.642027Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## 3) Kiến trúc: Encoder & Fusion\n\n- **Encoders:**\n  - `Embed1D`: tuyến tính theo kênh (giữ nguyên T) → `[B, T, d]`\n  - `FrameCNN2D`: conv 2D trên từng frame ToF → `[B, T, d]`\n  - `VecEncoder*`: trung bình theo thời gian → `[B, d]`\n\n- **Fusion:**\n  - **Early Fusion**: nối embeddings theo thời gian → Conv1D + GAP → MLP.\n  - **Late Fusion**: vector từng modality → concat → MLP.\n  - **Attention Fusion**: vector từng modality → attention (softmax) → weighted sum → MLP (xuất cả weights).\n  - **MoE**: mỗi modality = một *expert* sinh logits; gating (softmax) → tổ hợp logits.\n","metadata":{}},{"cell_type":"code","source":"# %% [models]\nif HAS_TORCH:\n    # ----- Embedding 1D cho IMU/Thermo (giữ T) -----\n    class Embed1D(nn.Module):\n        def __init__(self, in_ch, d, dropout=0.0):\n            super().__init__()\n            self.proj = nn.Linear(in_ch, d)\n            self.drop = nn.Dropout(dropout)\n        def forward(self, x):           # x: [B, T, C]\n            return self.drop(self.proj(x))  # [B, T, d]\n\n    # ----- CNN2D per-frame cho ToF (giữ T) -----\n    class FrameCNN2D(nn.Module):\n        def __init__(self, out_d=64, dropout=0.0):\n            super().__init__()\n            self.conv1 = nn.Conv2d(1, 32, 3, padding=1)\n            self.conv2 = nn.Conv2d(32, out_d, 3, padding=1)\n            self.pool = nn.AdaptiveAvgPool2d((1, 1))\n            self.drop = nn.Dropout(dropout)\n        def forward(self, tof):  # tof: [B, T, H, W]\n            B, T, H, W = tof.shape\n            x = tof.unsqueeze(2)                   # [B, T, 1, H, W]\n            h = x.reshape(B*T, 1, H, W)\n            h = F.relu(self.conv1(h))\n            h = F.relu(self.conv2(h))\n            h = self.pool(h).squeeze(-1).squeeze(-1)  # [B*T, out_d]\n            h = self.drop(h).view(B, T, -1)           # [B, T, out_d]\n            return h\n\n    # ----- Vector encoders (mean theo T) -----\n    class VecEncoder1D(nn.Module):\n        def __init__(self, in_ch, d, dropout=0.0):\n            super().__init__()\n            self.emb = Embed1D(in_ch, d, dropout)\n        def forward(self, x):               # x: [B, T, C]\n            h = self.emb(x)                 # [B, T, d]\n            return h.mean(dim=1)            # [B, d]\n\n    class VecEncoderToF(nn.Module):\n        def __init__(self, d, dropout=0.0):\n            super().__init__()\n            self.enc = FrameCNN2D(d, dropout)\n        def forward(self, tof):             # tof: [B, T, H, W]\n            h = self.enc(tof)               # [B, T, d]\n            return h.mean(dim=1)            # [B, d]\n\n    # ----- Head MLP -----\n    class HeadMLP(nn.Module):\n        def __init__(self, in_d, n_classes, hidden=128, dropout=0.2):\n            super().__init__()\n            self.net = nn.Sequential(\n                nn.Dropout(dropout),\n                nn.Linear(in_d, hidden), nn.ReLU(),\n                nn.Linear(hidden, n_classes)\n            )\n        def forward(self, x): return self.net(x)\n\n    # ----- Early Fusion -----\n    class EarlyFusionModel(nn.Module):\n        def __init__(self, use_imu, use_thermo, use_tof, cfg):\n            super().__init__()\n            d = cfg['EMB_D']; hid = cfg['FUSE_HIDDEN']; dr = cfg['DROPOUT']\n            self.use_imu, self.use_thermo, self.use_tof = use_imu, use_thermo, use_tof\n            if use_imu:    self.emb_imu    = Embed1D(IMU_CH, d, dr)\n            if use_thermo: self.emb_thermo = Embed1D(THERM_CH, d, dr)\n            if use_tof:    self.emb_tof    = FrameCNN2D(d, dr)\n            Dsum = (d if use_imu else 0) + (d if use_thermo else 0) + (d if use_tof else 0)\n            # Aggregator theo thời gian: Conv1D + GAP\n            self.conv = nn.Conv1d(Dsum, hid, kernel_size=3, padding=1)\n            self.pool = nn.AdaptiveAvgPool1d(1)\n            self.head = HeadMLP(hid, N_CLASSES, hidden=hid, dropout=dr)\n\n        def forward(self, imu, thermo, tof):\n            feats = []\n            if self.use_imu:    feats.append(self.emb_imu(imu))      # [B,T,d]\n            if self.use_thermo: feats.append(self.emb_thermo(thermo))\n            if self.use_tof:    feats.append(self.emb_tof(tof))\n            h = torch.cat(feats, dim=-1)          # [B, T, Dsum]\n            h = h.transpose(1, 2)                 # [B, Dsum, T]\n            h = F.relu(self.conv(h))              # [B, hid, T]\n            h = self.pool(h).squeeze(-1)          # [B, hid]\n            return self.head(h)\n\n    # ----- Late Fusion -----\n    class LateFusionModel(nn.Module):\n        def __init__(self, use_imu, use_thermo, use_tof, cfg):\n            super().__init__()\n            d = cfg['EMB_D']; hid = cfg['FUSE_HIDDEN']; dr = cfg['DROPOUT']\n            self.use_imu, self.use_thermo, self.use_tof = use_imu, use_thermo, use_tof\n            if use_imu:    self.vec_imu    = VecEncoder1D(IMU_CH, d, dr)\n            if use_thermo: self.vec_thermo = VecEncoder1D(THERM_CH, d, dr)\n            if use_tof:    self.vec_tof    = VecEncoderToF(d, dr)\n            Dsum = (d if use_imu else 0) + (d if use_thermo else 0) + (d if use_tof else 0)\n            self.head = HeadMLP(Dsum, N_CLASSES, hidden=hid, dropout=dr)\n\n        def forward(self, imu, thermo, tof):\n            vecs = []\n            if self.use_imu:    vecs.append(self.vec_imu(imu))\n            if self.use_thermo: vecs.append(self.vec_thermo(thermo))\n            if self.use_tof:    vecs.append(self.vec_tof(tof))\n            h = torch.cat(vecs, dim=-1)    # [B, Dsum]\n            return self.head(h)\n\n    # ----- Attention Fusion (xuất weights) -----\n    class AttentionFusionModel(nn.Module):\n        def __init__(self, use_imu, use_thermo, use_tof, cfg):\n            super().__init__()\n            d = cfg['EMB_D']; hid = cfg['FUSE_HIDDEN']; dr = cfg['DROPOUT']\n            self.use_imu, self.use_thermo, self.use_tof = use_imu, use_thermo, use_tof\n            if use_imu:    self.vec_imu    = VecEncoder1D(IMU_CH, d, dr)\n            if use_thermo: self.vec_thermo = VecEncoder1D(THERM_CH, d, dr)\n            if use_tof:    self.vec_tof    = VecEncoderToF(d, dr)\n            self.score = nn.Sequential(nn.Linear(d, d), nn.Tanh(), nn.Linear(d, 1))\n            self.head  = HeadMLP(d, N_CLASSES, hidden=hid, dropout=dr)\n\n        def forward(self, imu, thermo, tof, return_weights=False):\n            vecs = []\n            names = []\n            if self.use_imu:    vecs.append(self.vec_imu(imu));        names.append('IMU')\n            if self.use_thermo: vecs.append(self.vec_thermo(thermo));  names.append('Thermo')\n            if self.use_tof:    vecs.append(self.vec_tof(tof));        names.append('ToF')\n            V = torch.stack(vecs, dim=1)        # [B, M, d]\n            s = self.score(V)                   # [B, M, 1]\n            w = torch.softmax(s.squeeze(-1), dim=1)  # [B, M]\n            z = (w.unsqueeze(-1) * V).sum(dim=1)     # [B, d]\n            logits = self.head(z)\n            if return_weights:\n                return logits, w, names\n            return logits\n\n    # ----- Mixture of Experts (logits fusion) -----\n    class MoEModel(nn.Module):\n        def __init__(self, use_imu, use_thermo, use_tof, cfg):\n            super().__init__()\n            d = cfg['EMB_D']; hid = cfg['FUSE_HIDDEN']; dr = cfg['DROPOUT']\n            self.use_imu, self.use_thermo, self.use_tof = use_imu, use_thermo, use_tof\n            self.vecs = nn.ModuleDict()\n            self.experts = nn.ModuleList()\n            names = []\n            if use_imu:\n                self.vecs['imu'] = VecEncoder1D(IMU_CH, d, dr);  self.experts.append(HeadMLP(d, N_CLASSES, hidden=hid, dropout=dr)); names.append('imu')\n            if use_thermo:\n                self.vecs['thermo'] = VecEncoder1D(THERM_CH, d, dr); self.experts.append(HeadMLP(d, N_CLASSES, hidden=hid, dropout=dr)); names.append('thermo')\n            if use_tof:\n                self.vecs['tof'] = VecEncoderToF(d, dr); self.experts.append(HeadMLP(d, N_CLASSES, hidden=hid, dropout=dr)); names.append('tof')\n            self.names = names\n            self.gate = nn.Sequential(\n                nn.Linear(d*len(names), hid), nn.ReLU(), nn.Linear(hid, len(names))\n            )\n\n        def forward(self, imu, thermo, tof, return_weights=False):\n            vec_list = []\n            logit_list = []\n            for nm, enc in self.vecs.items():\n                if nm=='imu':      v = enc(imu)\n                elif nm=='thermo': v = enc(thermo)\n                else:              v = enc(tof)\n                vec_list.append(v)\n            V = torch.stack(vec_list, dim=1)                 # [B, M, d]\n            # experts\n            for i, v in enumerate(vec_list):\n                logit_list.append(self.experts[i](v))        # [B, C]\n            L = torch.stack(logit_list, dim=1)               # [B, M, C]\n            # gate\n            g = self.gate(V.reshape(V.size(0), -1))          # [B, M]\n            w = torch.softmax(g, dim=1)                      # [B, M]\n            logits = (w.unsqueeze(-1) * L).sum(dim=1)        # [B, C]\n            if return_weights:\n                return logits, w, self.names\n            return logits\nelse:\n    print('Chưa có torch – bỏ qua models')\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-28T11:40:19.643816Z","iopub.execute_input":"2025-08-28T11:40:19.644047Z","iopub.status.idle":"2025-08-28T11:40:19.673620Z","shell.execute_reply.started":"2025-08-28T11:40:19.644028Z","shell.execute_reply":"2025-08-28T11:40:19.672802Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## 4) Huấn luyện & Đánh giá\n\n- `run_epoch(...)` chấp nhận batch có cả 3 modality và gọi đúng forward theo loại model.\n- Trả về `loss` + `macro-F1`.\n- Lưu lại **best model** theo `val_loss`.\n","metadata":{}},{"cell_type":"code","source":"# %% [train_utils]\nif HAS_TORCH:\n    def macro_f1(y_true, y_pred): return f1_score(y_true, y_pred, average='macro')\n\n    class EarlyStopping:\n        def __init__(self, patience=4, min_delta=0.0):\n            self.patience = patience; self.min_delta = min_delta\n            self.best = None; self.count = 0; self.stop = False\n        def step(self, value):\n            if self.best is None or value < self.best - self.min_delta:\n                self.best = value; self.count = 0\n            else:\n                self.count += 1\n                if self.count >= self.patience: self.stop = True\n\n    def run_epoch(model, loader, criterion, optimizer=None):\n        train = optimizer is not None\n        model.train() if train else model.eval()\n        total = 0.0; ys=[]; yhs=[]\n        for b in loader:\n            imu_b = b['imu'].to(DEVICE).float()\n            th_b  = b['thermo'].to(DEVICE).float()\n            tof_b = b['tof'].to(DEVICE).float()\n            y_b   = b['y'].to(DEVICE)\n            if train: optimizer.zero_grad()\n            # Hỗ trợ Attention/MoE trả về (logits, weights, names)\n            out = model(imu_b, th_b, tof_b)\n            logits = out[0] if isinstance(out, tuple) else out\n            loss = criterion(logits, y_b)\n            if train:\n                loss.backward(); optimizer.step()\n            total += loss.item() * y_b.size(0)\n            ys.append(y_b.detach().cpu().numpy())\n            yhs.append(logits.detach().cpu().argmax(dim=1).cpu().numpy())\n        ys = np.concatenate(ys); yhs = np.concatenate(yhs)\n        return total / len(loader.dataset), macro_f1(ys, yhs)\n\n    def fit_model(model, loaders, cfg):\n        model = model.to(DEVICE)\n        criterion = nn.CrossEntropyLoss()\n        optim = Adam(model.parameters(), lr=cfg['LR'], weight_decay=cfg['WEIGHT_DECAY'])\n        early = EarlyStopping(patience=cfg['EARLY_STOP_PATIENCE'])\n        best_state = None; best_val = float('inf')\n        hist = {'epoch': [], 'train_loss': [], 'val_loss': [], 'train_f1': [], 'val_f1': []}\n        t0 = time.monotonic()\n        for ep in range(cfg['MAX_EPOCHS']):\n            tr_loss, tr_f1 = run_epoch(model, loaders['train'], criterion, optim)\n            vl_loss, vl_f1 = run_epoch(model, loaders['val'],   criterion, None)\n            hist['epoch'].append(ep+1); hist['train_loss'].append(tr_loss); hist['val_loss'].append(vl_loss)\n            hist['train_f1'].append(tr_f1); hist['val_f1'].append(vl_f1)\n            if vl_loss < best_val:\n                best_val = vl_loss\n                best_state = {k: v.detach().cpu().clone() for k,v in model.state_dict().items()}\n            print(f\"[EP {ep+1:02d}] tr_loss={tr_loss:.4f} val_loss={vl_loss:.4f} tr_f1={tr_f1:.4f} val_f1={vl_f1:.4f}\")\n            early.step(vl_loss)\n            if early.stop:\n                print(\"Early stopping.\"); break\n        t1 = time.monotonic()\n        if best_state is not None:\n            model.load_state_dict(best_state)\n        return model, hist, (t1 - t0)\n\n    @torch.no_grad()\n    def evaluate_test(model, loader):\n        model.eval(); ys=[]; yhs=[]\n        for b in loader:\n            imu_b = b['imu'].to(DEVICE).float()\n            th_b  = b['thermo'].to(DEVICE).float()\n            tof_b = b['tof'].to(DEVICE).float()\n            y_b   = b['y'].to(DEVICE)\n            out = model(imu_b, th_b, tof_b)\n            logits = out[0] if isinstance(out, tuple) else out\n            ys.append(y_b.cpu().numpy())\n            yhs.append(logits.argmax(dim=1).cpu().numpy())\n        ys = np.concatenate(ys); yhs = np.concatenate(yhs)\n        return f1_score(ys, yhs, average='macro')\nelse:\n    print('Chưa có torch – bỏ qua train utils')\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-28T11:40:19.674675Z","iopub.execute_input":"2025-08-28T11:40:19.675012Z","iopub.status.idle":"2025-08-28T11:40:19.692799Z","shell.execute_reply.started":"2025-08-28T11:40:19.674979Z","shell.execute_reply":"2025-08-28T11:40:19.691987Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## 5) Khởi tạo mô hình theo `fusion` & chạy thí nghiệm\n\n- `factory(fusion)` tạo: **early / late / attn / moe**.\n- Chạy các mục trong `CONFIG['RUNS']` (bao gồm ablation).\n- Lưu: **macro-F1 (val/test)**, **params**, **thời gian train**.\n","metadata":{}},{"cell_type":"code","source":"# %% [experiments]\nfrom pathlib import Path\n\nif HAS_TORCH:\n    def make_model(use_imu, use_thermo, use_tof, fusion, cfg):\n        if fusion == 'early':\n            return EarlyFusionModel(use_imu, use_thermo, use_tof, cfg)\n        if fusion == 'late':\n            return LateFusionModel(use_imu, use_thermo, use_tof, cfg)\n        if fusion == 'attn':\n            return AttentionFusionModel(use_imu, use_thermo, use_tof, cfg)\n        if fusion == 'moe':\n            return MoEModel(use_imu, use_thermo, use_tof, cfg)\n        if fusion == 'ensemble':\n            return None  # xử lý riêng\n        raise ValueError('Unknown fusion: '+fusion)\n\n    def param_count(model): return sum(p.numel() for p in model.parameters())\n\n    # Train models đơn kênh để dùng cho Ensemble soft voting\n    def train_unimodal_baselines(loaders, cfg):\n        uni = {}\n        # IMU\n        m_imu = LateFusionModel(True, False, False, cfg).to(DEVICE)\n        m_imu, _, _ = fit_model(m_imu, loaders, cfg); uni['IMU'] = m_imu\n        # Thermo\n        m_th = LateFusionModel(False, True, False, cfg).to(DEVICE)\n        m_th, _, _ = fit_model(m_th, loaders, cfg); uni['THERMO'] = m_th\n        # ToF\n        m_tof = LateFusionModel(False, False, True, cfg).to(DEVICE)\n        m_tof, _, _ = fit_model(m_tof, loaders, cfg); uni['TOF'] = m_tof\n        return uni\n\n    @torch.no_grad()\n    def eval_ensemble_soft(uni_models, loader):\n        for k in uni_models: uni_models[k].eval()\n        ys=[]; yhs=[]\n        for b in loader:\n            imu_b = b['imu'].to(DEVICE).float()\n            th_b  = b['thermo'].to(DEVICE).float()\n            tof_b = b['tof'].to(DEVICE).float()\n            y_b   = b['y'].to(DEVICE)\n            probs = []\n            # mỗi model trả về logits từ modality tương ứng\n            logits_imu  = uni_models['IMU'](imu_b, th_b, tof_b)\n            logits_th   = uni_models['THERMO'](imu_b, th_b, tof_b)\n            logits_tof  = uni_models['TOF'](imu_b, th_b, tof_b)\n            for lg in [logits_imu, logits_th, logits_tof]:\n                if isinstance(lg, tuple): lg = lg[0]\n                probs.append(torch.softmax(lg, dim=1))\n            p = torch.stack(probs, dim=0).mean(dim=0)   # soft voting\n            yhat = p.argmax(dim=1)\n            ys.append(y_b.cpu().numpy()); yhs.append(yhat.cpu().numpy())\n        ys = np.concatenate(ys); yhs = np.concatenate(yhs)\n        return f1_score(ys, yhs, average='macro')\n\n    results = []\n    histories = {}\n\n    for name, cfg_run in CONFIG['RUNS']:\n        use_imu, use_th, use_tof = cfg_run['imu'], cfg_run['thermo'], cfg_run['tof']\n        fusion = cfg_run['fusion']\n        print(f\"\\n=== Run {name} | fusion={fusion} | use: IMU={use_imu}, Thermo={use_th}, ToF={use_tof} ===\")\n\n        if fusion == 'ensemble':\n            uni = train_unimodal_baselines(loaders, CONFIG)\n            te_f1 = eval_ensemble_soft(uni, loaders['test'])\n            results.append({'exp': name, 'fusion': fusion, 'modalities': f\"{use_imu}{use_th}{use_tof}\",\n                            'params': int(sum(param_count(m) for m in uni.values())),\n                            'train_time_sec': np.nan, 'val_f1': np.nan, 'test_f1': float(te_f1)})\n            print(f\"==> Ensemble soft voting: test F1 = {te_f1:.4f}\")\n            continue\n\n        model = make_model(use_imu, use_th, use_tof, fusion, CONFIG).to(DEVICE)\n        nparam = param_count(model)\n        model, hist, train_time = fit_model(model, loaders, CONFIG)\n        te_f1 = evaluate_test(model, loaders['test'])\n\n        histories[name] = pd.DataFrame(hist)\n        results.append({\n            'exp': name, 'fusion': fusion, 'modalities': f\"{use_imu}{use_th}{use_tof}\",\n            'params': int(nparam), 'train_time_sec': float(train_time),\n            'val_f1': float(hist['val_f1'][-1]), 'test_f1': float(te_f1)\n        })\n        print(f\"==> {name}: test macro-F1 = {te_f1:.4f}\")\n\n    res_df = pd.DataFrame(results).sort_values('test_f1', ascending=False)\n    display(res_df)\n    out_dir = Path('/mnt/data'); out_dir.mkdir(parents=True, exist_ok=True)\n    out_p = out_dir / 'multimodal_results.csv'\n    res_df.to_csv(out_p, index=False)\n    print('Đã lưu kết quả tại:', out_p)\nelse:\n    print('Chưa có torch – bỏ qua experiments')\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-28T11:40:19.693724Z","iopub.execute_input":"2025-08-28T11:40:19.694011Z","iopub.status.idle":"2025-08-28T11:43:57.284606Z","shell.execute_reply.started":"2025-08-28T11:40:19.693982Z","shell.execute_reply":"2025-08-28T11:43:57.283639Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## 6) Visualization Attention Weights\n\n- Lấy model **ATTN_ALL** đã huấn luyện → xuất `weights ∈ [B, M]`.\n- In **tỷ trọng trung bình (%)** của từng modality trên **val**.\n- Vẽ bar chart minh hoạ.\n","metadata":{}},{"cell_type":"code","source":"# %% [viz_attention]\nif HAS_TORCH:\n    # Khởi tạo lại model attention & nạp trọng số tốt nhất bằng cách huấn luyện ngắn\n    attn_model = AttentionFusionModel(True, True, True, CONFIG).to(DEVICE)\n    attn_model, _, _ = fit_model(attn_model, loaders, CONFIG)\n    # Thu weights trên val\n    attn_model.eval()\n    ws = []\n    names_ref = None\n    with torch.no_grad():\n        for b in loaders['val']:\n            imu_b = b['imu'].to(DEVICE).float()\n            th_b  = b['thermo'].to(DEVICE).float()\n            tof_b = b['tof'].to(DEVICE).float()\n            logits, w, names = attn_model(imu_b, th_b, tof_b, return_weights=True)\n            ws.append(w.cpu().numpy())\n            if names_ref is None: names_ref = names\n    W = np.concatenate(ws, axis=0)  # [N_val, M]\n    mean_w = W.mean(axis=0)\n    perc = 100*mean_w/mean_w.sum()\n    for nm, pi in zip(names_ref, perc):\n        print(f\"{nm}: {pi:.1f}%\")\n\n    # Vẽ bar\n    plt.figure()\n    plt.bar(names_ref, perc)\n    plt.title('Attention weights trung bình theo modality (val)')\n    plt.ylabel('Phần trăm (%)')\n    plt.tight_layout(); plt.show()\nelse:\n    print('Chưa có torch – bỏ qua visualization attention')\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-28T11:43:57.285624Z","iopub.execute_input":"2025-08-28T11:43:57.285956Z","iopub.status.idle":"2025-08-28T11:44:27.548023Z","shell.execute_reply.started":"2025-08-28T11:43:57.285928Z","shell.execute_reply":"2025-08-28T11:44:27.547147Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## 7) MoE & Ensemble\n\n- **MoE**: các *expert* là logits của từng modality; **gating** (softmax) trộn theo trọng số → đã chạy trong `MOE_ALL`.\n- **Ensemble**: soft voting từ 3 model đơn kênh (IMU / Thermo / ToF) → `ENSEMBLE_SOFT`.\n","metadata":{}},{"cell_type":"code","source":"# (Đã thực hiện trong Section 6 — không cần thêm code ở đây)\nprint(\"MoE và Ensemble đã được chạy trong phần thí nghiệm.\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-28T11:44:27.549068Z","iopub.execute_input":"2025-08-28T11:44:27.549722Z","iopub.status.idle":"2025-08-28T11:44:27.554109Z","shell.execute_reply.started":"2025-08-28T11:44:27.549692Z","shell.execute_reply":"2025-08-28T11:44:27.553253Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## 8) Kiểm định thống kê\n\n- Chạy nhiều seed (theo `CONFIG['N_REPEATS']`) cho:\n  - **IMU-only** (baseline)\n  - **Attention Fusion (All)** (mô hình mạnh, có weights)\n- Lưu danh sách `test_F1` theo seed, thực hiện **t-test có ghép cặp** và **Wilcoxon signed-rank**.\n","metadata":{}},{"cell_type":"code","source":"# %% [stats_tests]\nif HAS_TORCH and HAS_SCIPY:\n    seeds = CONFIG['SEEDS'][:CONFIG['N_REPEATS']]\n    f1_imu, f1_fuse = [], []\n\n    def set_seed(s):\n        random.seed(s); np.random.seed(s)\n        torch.manual_seed(s); \n        if DEVICE=='cuda': torch.cuda.manual_seed_all(s)\n\n    for s in seeds:\n        print(f\"\\n== Re-run with seed {s} ==\")\n        set_seed(s)\n        # Rebuild loaders (shuffle khác)\n        idx = np.arange(N); np.random.shuffle(idx)\n        TEST = int(0.15 * N); VAL = int(0.15 * N)\n        test_idx, val_idx, train_idx = idx[:TEST], idx[TEST:TEST+VAL], idx[TEST+VAL:]\n        split2 = {\n            'train': {'imu': imu[train_idx], 'thermo': thermo[train_idx], 'tof': tof[train_idx], 'y': y[train_idx]},\n            'val':   {'imu': imu[val_idx],   'thermo': thermo[val_idx],   'tof': tof[val_idx],   'y': y[val_idx]},\n            'test':  {'imu': imu[test_idx],  'thermo': thermo[test_idx],  'tof': tof[test_idx],  'y': y[test_idx]},\n        }\n        class DS(Dataset):\n            def __init__(self, p): self.p=p\n            def __len__(self): return self.p['y'].shape[0]\n            def __getitem__(self, i):\n                return {'imu': torch.from_numpy(self.p['imu'][i]),\n                        'thermo': torch.from_numpy(self.p['thermo'][i]),\n                        'tof': torch.from_numpy(self.p['tof'][i]),\n                        'y': torch.tensor(int(self.p['y'][i]))}\n        loaders2 = {}\n        for nm in ['train','val','test']:\n            loaders2[nm] = DataLoader(DS(split2[nm]), batch_size=CONFIG['BATCH_SIZE'], shuffle=(nm=='train'))\n\n        # IMU-only\n        m_imu = LateFusionModel(True, False, False, CONFIG).to(DEVICE)\n        m_imu, _, _ = fit_model(m_imu, loaders2, CONFIG)\n        f1i = evaluate_test(m_imu, loaders2['test'])\n        f1_imu.append(f1i)\n\n        # Attention Fusion All\n        m_attn = AttentionFusionModel(True, True, True, CONFIG).to(DEVICE)\n        m_attn, _, _ = fit_model(m_attn, loaders2, CONFIG)\n        f1a = evaluate_test(m_attn, loaders2['test'])\n        f1_fuse.append(f1a)\n\n        print(f\"Seed {s}: IMU-only={f1i:.4f} | ATTN_ALL={f1a:.4f}\")\n\n    print(\"\\n== Kiểm định thống kê (paired) ==\")\n    t_res = ttest_rel(f1_fuse, f1_imu)\n    w_res = wilcoxon(f1_fuse, f1_imu, zero_method='wilcox', correction=False, alternative='two-sided')\n    print(\"Paired t-test:    t=%.4f, p=%.6f\" % (t_res.statistic, t_res.pvalue))\n    print(\"Wilcoxon signed:  W=%.4f, p=%.6f\" % (w_res.statistic, w_res.pvalue))\n    print(\"Các vector F1:\", \"\\n  IMU:\", f1_imu, \"\\n  ATTN:\", f1_fuse)\nelse:\n    print(\"Thiếu torch hoặc scipy — bỏ qua kiểm định thống kê.\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-28T11:44:27.555034Z","iopub.execute_input":"2025-08-28T11:44:27.555300Z","iopub.status.idle":"2025-08-28T11:45:59.338779Z","shell.execute_reply.started":"2025-08-28T11:44:27.555283Z","shell.execute_reply":"2025-08-28T11:45:59.337834Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## 9) Kết luận\n\n- **Fusion (đặc biệt Attention / Late với đủ modalities)** thường **vượt IMU-only** trên macro-F1 ⇒ cho thấy **giá trị thêm** của **ToF & Thermopile**.\n- **Visualization** attention: cung cấp trực quan tỷ trọng theo modality (vd: *IMU 70%*, *ToF 20%*, *Thermo 10%*).\n- **Thống kê** (t-test / Wilcoxon) xác nhận chênh lệch có ý nghĩa (tuỳ thuộc số seed).\n\n## 10) Ghi chú\n- Tăng `N_REPEATS`/epoch để kiểm định mạnh hơn (chi phí thời gian lớn hơn).\n- Có thể thay **aggregator** của Early Fusion (TCN/Transformer) để cải thiện.\n- Lưu kết quả: `/mnt/data/multimodal_results.csv`.\n","metadata":{}},{"cell_type":"code","source":"# %% [end]\nprint(\"Notebook 4 hoàn tất ✅. Kết quả chính lưu tại /mnt/data/multimodal_results.csv\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-28T11:45:59.339764Z","iopub.execute_input":"2025-08-28T11:45:59.340096Z","iopub.status.idle":"2025-08-28T11:45:59.344271Z","shell.execute_reply.started":"2025-08-28T11:45:59.340076Z","shell.execute_reply":"2025-08-28T11:45:59.343318Z"}},"outputs":[],"execution_count":null}]}