{"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":"none","dataSources":[{"sourceId":102335,"databundleVersionId":12518947,"sourceType":"competition"}],"dockerImageVersionId":31089,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"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-09-15T01:43:34.593852Z","iopub.execute_input":"2025-09-15T01:43:34.594121Z","iopub.status.idle":"2025-09-15T01:43:38.838731Z","shell.execute_reply.started":"2025-09-15T01:43:34.594101Z","shell.execute_reply":"2025-09-15T01:43:38.837805Z"}},"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-09-15T01:43:38.839743Z","iopub.execute_input":"2025-09-15T01:43:38.840140Z","iopub.status.idle":"2025-09-15T01:44:19.937238Z","shell.execute_reply.started":"2025-09-15T01:43:38.840118Z","shell.execute_reply":"2025-09-15T01:44:19.936306Z"}},"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-09-15T01:44:19.939024Z","iopub.execute_input":"2025-09-15T01:44:19.939298Z","iopub.status.idle":"2025-09-15T01:44:20.826772Z","shell.execute_reply.started":"2025-09-15T01:44:19.939278Z","shell.execute_reply":"2025-09-15T01:44:20.825866Z"}},"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-09-15T01:44:20.830304Z","iopub.execute_input":"2025-09-15T01:44:20.830527Z","iopub.status.idle":"2025-09-15T01:44:25.938279Z","shell.execute_reply.started":"2025-09-15T01:44:20.830507Z","shell.execute_reply":"2025-09-15T01:44:25.937467Z"}},"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-09-15T01:44:25.939249Z","iopub.execute_input":"2025-09-15T01:44:25.939563Z","iopub.status.idle":"2025-09-15T01:44:26.811252Z","shell.execute_reply.started":"2025-09-15T01:44:25.939541Z","shell.execute_reply":"2025-09-15T01:44:26.810510Z"}},"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-09-15T01:44:26.812067Z","iopub.execute_input":"2025-09-15T01:44:26.812350Z","iopub.status.idle":"2025-09-15T01:44:27.493805Z","shell.execute_reply.started":"2025-09-15T01:44:26.812319Z","shell.execute_reply":"2025-09-15T01:44:27.493025Z"}},"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-09-15T01:44:27.494804Z","iopub.execute_input":"2025-09-15T01:44:27.495155Z","iopub.status.idle":"2025-09-15T01:44:37.672597Z","shell.execute_reply.started":"2025-09-15T01:44:27.495126Z","shell.execute_reply":"2025-09-15T01:44:37.671728Z"}},"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-09-15T01:44:37.675751Z","iopub.execute_input":"2025-09-15T01:44:37.676005Z","iopub.status.idle":"2025-09-15T01:44:38.999365Z","shell.execute_reply.started":"2025-09-15T01:44:37.675983Z","shell.execute_reply":"2025-09-15T01:44:38.998730Z"}},"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-09-15T01:44:39.000196Z","iopub.execute_input":"2025-09-15T01:44:39.000586Z","iopub.status.idle":"2025-09-15T01:44:39.029885Z","shell.execute_reply.started":"2025-09-15T01:44:39.000564Z","shell.execute_reply":"2025-09-15T01:44:39.028932Z"}},"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-09-15T01:44:39.031025Z","iopub.execute_input":"2025-09-15T01:44:39.031352Z","iopub.status.idle":"2025-09-15T01:44:46.563613Z","shell.execute_reply.started":"2025-09-15T01:44:39.031324Z","shell.execute_reply":"2025-09-15T01:44:46.562747Z"}},"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-09-15T01:44:46.564700Z","iopub.execute_input":"2025-09-15T01:44:46.565031Z","iopub.status.idle":"2025-09-15T01:44:50.799483Z","shell.execute_reply.started":"2025-09-15T01:44:46.564999Z","shell.execute_reply":"2025-09-15T01:44:50.797841Z"}},"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-09-15T01:44:50.801518Z","iopub.execute_input":"2025-09-15T01:44:50.801952Z","iopub.status.idle":"2025-09-15T01:44:50.810714Z","shell.execute_reply.started":"2025-09-15T01:44:50.801923Z","shell.execute_reply":"2025-09-15T01:44:50.809774Z"}},"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-09-15T01:44:50.811784Z","iopub.execute_input":"2025-09-15T01:44:50.812118Z","iopub.status.idle":"2025-09-15T01:44:50.836712Z","shell.execute_reply.started":"2025-09-15T01:44:50.812087Z","shell.execute_reply":"2025-09-15T01:44:50.835770Z"}},"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-09-15T01:44:50.837919Z","iopub.execute_input":"2025-09-15T01:44:50.838303Z","iopub.status.idle":"2025-09-15T01:44:50.854902Z","shell.execute_reply.started":"2025-09-15T01:44:50.838274Z","shell.execute_reply":"2025-09-15T01:44:50.853775Z"}},"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-09-15T01:44:50.855795Z","iopub.execute_input":"2025-09-15T01:44:50.856116Z","iopub.status.idle":"2025-09-15T01:44:51.000571Z","shell.execute_reply.started":"2025-09-15T01:44:50.856086Z","shell.execute_reply":"2025-09-15T01:44:50.999623Z"}},"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-09-15T01:44:51.001747Z","iopub.execute_input":"2025-09-15T01:44:51.002072Z","iopub.status.idle":"2025-09-15T01:44:51.008251Z","shell.execute_reply.started":"2025-09-15T01:44:51.002039Z","shell.execute_reply":"2025-09-15T01:44:51.007171Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Notebook 3 – Transformers & Modern Time-Series Models\n\n## Goal: Compare attention-based (Transformer/TST/Informer-like) vs CNN/TCN on IMU/ToF/Thermo sensor sequences\n## Metrics: Macro-F1; Ablations over sequence length (window=50/100/200)\n## Complexity: train time per epoch & #params\n","metadata":{}},{"cell_type":"markdown","source":"## 0. Import thư viện & cấu hình chung","metadata":{}},{"cell_type":"code","source":"import os, gc, time, math, random, warnings\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.utils.data import Dataset, DataLoader\n\nfrom sklearn.preprocessing import StandardScaler, LabelEncoder\nfrom sklearn.metrics import f1_score\nfrom sklearn.model_selection import train_test_split\n\nDEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nrandom.seed(42); np.random.seed(42); torch.manual_seed(42)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-15T01:44:51.009066Z","iopub.execute_input":"2025-09-15T01:44:51.009365Z","iopub.status.idle":"2025-09-15T01:44:57.027204Z","shell.execute_reply.started":"2025-09-15T01:44:51.009344Z","shell.execute_reply":"2025-09-15T01:44:57.026370Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Notebook 3 – Transformers & Modern Time-Series Models\n# ------------------------------------------------------------\n# Goal: Compare attention-based (Transformer/TST/Informer-like) vs CNN/TCN on IMU/ToF/Thermo sensor sequences\n# Metrics: Macro-F1; Ablations over sequence length (window=50/100/200)\n# Complexity: train time per epoch & #params\n# ------------------------------------------------------------\n\nimport os, gc, time, math, random, warnings\nfrom pathlib import Path\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.utils.data import Dataset, DataLoader\n\nfrom sklearn.preprocessing import StandardScaler, LabelEncoder\nfrom sklearn.metrics import f1_score, classification_report\nfrom sklearn.model_selection import StratifiedKFold, train_test_split\n\nDEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nRNG = np.random.default_rng(42)\nrandom.seed(42); torch.manual_seed(42); np.random.seed(42)\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-15T01:44:57.028062Z","iopub.execute_input":"2025-09-15T01:44:57.028482Z","iopub.status.idle":"2025-09-15T01:44:57.036906Z","shell.execute_reply.started":"2025-09-15T01:44:57.028463Z","shell.execute_reply":"2025-09-15T01:44:57.036041Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# =====================\n# 0) DATA LOADING (Kaggle paths)\n# =====================\ntrain_df = pd.read_csv(\"/kaggle/input/cmi-detect-behavior-with-sensor-data/train.csv\")\ntrain_dem_df = pd.read_csv(\"/kaggle/input/cmi-detect-behavior-with-sensor-data/train_demographics.csv\")\ntest_df = pd.read_csv(\"/kaggle/input/cmi-detect-behavior-with-sensor-data/test.csv\")\ntest_dem_df = pd.read_csv(\"/kaggle/input/cmi-detect-behavior-with-sensor-data/test_demographics.csv\")\n\n# --- flexible merge keys\nCAND_KEYS = ['id','ID','Id','record_id','sample_id','subject_id','participant_id','user_id','person_id','uid','pid','subject','ParticipantID','session_id']\n\ndef pick_key(left: pd.DataFrame, right: pd.DataFrame, candidates=CAND_KEYS):\n    both = [k for k in candidates if k in left.columns and k in right.columns]\n    if both: return both[0], both[0]\n    l2 = [c for c in left.columns if ('id' in c.lower()) or ('subject' in c.lower()) or ('session' in c.lower())]\n    r2 = [c for c in right.columns if ('id' in c.lower()) or ('subject' in c.lower()) or ('session' in c.lower())]\n    inter = list(set(l2).intersection(r2))\n    if inter: return inter[0], inter[0]\n    raise KeyError(\"Không tìm được khóa merge giữa 2 bảng – hãy chỉnh lại tên cột khoá.\")\n\nlk, rk = pick_key(train_df, train_dem_df)\ntrain_full = train_df.merge(train_dem_df, left_on=lk, right_on=rk, how='left')\nlk_t, rk_t = pick_key(test_df, test_dem_df)\ntest_full = test_df.merge(test_dem_df, left_on=lk_t, right_on=rk_t, how='left')\n\n# --- label detection\nLABEL_CANDS = ['label','target','activity','activity_id','behavior','behavior_id','state','class']\nlabel_map = {c.lower(): c for c in train_full.columns}\nLABEL_COL = None\nfor k in LABEL_CANDS:\n    if k in label_map: LABEL_COL = label_map[k]; break\nif LABEL_COL is None:\n    # heuristic: low-cardinality, non-id\n    nn = len(train_full)\n    opts = []\n    for c in train_full.columns:\n        lc = c.lower()\n        if 'id' in lc or 'time' in lc or 'timestamp' in lc: continue\n        u = train_full[c].nunique(dropna=True)\n        if 2 <= u <= min(50, max(2, nn//10)):\n            opts.append((c,u))\n    opts.sort(key=lambda x: x[1])\n    LABEL_COL = opts[0][0]\nprint('LABEL_COL =', LABEL_COL)\n\n# --- time & grouping columns (for sequence build)\nTIME_CANDS = ['timestamp','time','frame','step','t','ts']\nGROUP_CANDS = [lk, 'session_id','trial_id','sequence_id', 'seq_id', 'record_id', 'sample_id', 'id']\n\ndef pick_time_col(df):\n    for k in TIME_CANDS:\n        for c in df.columns:\n            if c.lower() == k: return c\n            if k in c.lower(): return c\n    return None\n\nTIME_COL = pick_time_col(train_full)\nGROUP_COL = None\nfor g in GROUP_CANDS:\n    if isinstance(g,str) and g in train_full.columns:\n        GROUP_COL = g; break\nif TIME_COL is None:\n    # fallback: assume implicit order\n    TIME_COL = '___row_index__'\n    train_full[TIME_COL] = np.arange(len(train_full))\n\nprint({'TIME_COL': TIME_COL, 'GROUP_COL': GROUP_COL})\n\n# --- select sensor columns (numeric)\nSENSOR_PREFIXES = ['ax','ay','az','gx','gy','gz','acc','gyro','mag','imu','tof','thm','thermo']\nALL_NUM = [c for c in train_full.columns if pd.api.types.is_numeric_dtype(train_full[c]) and c not in [LABEL_COL]]\nSENSOR_COLS = []\nfor c in ALL_NUM:\n    lc = c.lower()\n    if any(lc.startswith(p) for p in SENSOR_PREFIXES):\n        SENSOR_COLS.append(c)\nif not SENSOR_COLS:\n    # if dataset uses other names, fallback to all numeric except demographics-like\n    SENSOR_COLS = [c for c in ALL_NUM if 'age' not in c.lower()]\n\nprint('n_sensor_cols =', len(SENSOR_COLS))\n\n# Encode labels\nle = LabelEncoder(); y_text = train_full[LABEL_COL].astype(str).values\ny_all = le.fit_transform(y_text).astype(np.int64)\nN_CLASS = len(le.classes_)\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-15T01:44:57.037953Z","iopub.execute_input":"2025-09-15T01:44:57.038270Z","iopub.status.idle":"2025-09-15T01:45:30.723687Z","shell.execute_reply.started":"2025-09-15T01:44:57.038243Z","shell.execute_reply":"2025-09-15T01:45:30.722856Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# =====================\n# 1) BUILD SEQUENCES (sliding window)\n# =====================\n\ndef build_windows(df, sensor_cols, labels, time_col, group_col, win=100, stride=None):\n    if stride is None: stride = win//2\n    X_list, y_list = [], []\n    if group_col is None:\n        df_sorted = df.sort_values(time_col)\n        arr = df_sorted[sensor_cols].values\n        yarr = labels[df_sorted.index]\n        for s in range(0, len(df_sorted)-win+1, stride):\n            X_list.append(arr[s:s+win])\n            # majority label in window\n            yy = yarr[s:s+win]\n            vals, cnts = np.unique(yy, return_counts=True)\n            y_list.append(vals[np.argmax(cnts)])\n    else:\n        for gid, gdf in df.groupby(group_col):\n            gdf = gdf.sort_values(time_col)\n            arr = gdf[sensor_cols].values\n            yarr = labels[gdf.index]\n            if len(gdf) < win: continue\n            for s in range(0, len(gdf)-win+1, stride):\n                X_list.append(arr[s:s+win])\n                yy = yarr[s:s+win]\n                vals, cnts = np.unique(yy, return_counts=True)\n                y_list.append(vals[np.argmax(cnts)])\n    X = np.stack(X_list).astype(np.float32)\n    y = np.array(y_list, dtype=np.int64)\n    return X, y\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-15T01:45:30.724672Z","iopub.execute_input":"2025-09-15T01:45:30.725004Z","iopub.status.idle":"2025-09-15T01:45:30.733116Z","shell.execute_reply.started":"2025-09-15T01:45:30.724970Z","shell.execute_reply":"2025-09-15T01:45:30.732152Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# =====================\n# 2) DATASET / DATALOADER\n# =====================\nclass SeqDataset(Dataset):\n    def __init__(self, X, y, fit_scaler=False, scaler=None):\n        # X: [N, L, C]\n        self.X = X\n        self.y = y\n        self.scaler = scaler if scaler is not None else StandardScaler()\n        if fit_scaler:\n            X2d = X.reshape(-1, X.shape[-1])\n            self.scaler.fit(X2d)\n        X2d = X.reshape(-1, X.shape[-1])\n        X_scaled = self.scaler.transform(X2d).astype(np.float32)\n        self.X = X_scaled.reshape(X.shape[0], X.shape[1], X.shape[2])\n    def __len__(self): return self.X.shape[0]\n    def __getitem__(self, idx):\n        return torch.from_numpy(self.X[idx]), torch.tensor(self.y[idx])\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-15T01:45:30.734194Z","iopub.execute_input":"2025-09-15T01:45:30.734478Z","iopub.status.idle":"2025-09-15T01:45:30.756104Z","shell.execute_reply.started":"2025-09-15T01:45:30.734457Z","shell.execute_reply":"2025-09-15T01:45:30.755171Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# =====================\n# 3) MODELS: TCN, Vanilla Transformer, TST, Informer-like\n# =====================\nclass TemporalConvBlock(nn.Module):\n    def __init__(self, in_ch, out_ch, k=3, d=1, p=0.1):\n        super().__init__()\n        # pad để giữ nguyên chiều dài: pad = dilation*(k-1)/2  (yêu cầu k lẻ)\n        assert k % 2 == 1, \"Kernel size k should be odd to keep SAME length.\"\n        pad = (k - 1) * d // 2\n\n        self.net = nn.Sequential(\n            nn.Conv1d(in_ch, out_ch, k, padding=pad, dilation=d),\n            nn.ReLU(), nn.Dropout(p),\n            nn.Conv1d(out_ch, out_ch, k, padding=pad, dilation=d),\n            nn.ReLU(), nn.Dropout(p)\n        )\n        self.down = nn.Conv1d(in_ch, out_ch, 1) if in_ch != out_ch else nn.Identity()\n\n    def forward(self, x):  # x: [B,C,L]\n        y = self.net(x)    # [B,out_ch,L]  (giữ nguyên L)\n        return F.relu(y + self.down(x))\n\n\nclass TCN(nn.Module):\n    def __init__(self, in_dim, n_class, chs=[64,64,128], ks=3, p=0.1):\n        super().__init__()\n        blocks = []\n        c = in_dim\n        d = 1\n        for ch in chs:\n            blocks.append(TemporalConvBlock(c, ch, k=ks, d=d, p=p))\n            c = ch; d *= 2\n        self.tcn = nn.Sequential(*blocks)\n        self.head = nn.Sequential(nn.AdaptiveAvgPool1d(1), nn.Flatten(), nn.Linear(c, n_class))\n    def forward(self, x):\n        # x: [B,L,C] → [B,C,L]\n        x = x.transpose(1,2)\n        z = self.tcn(x)\n        out = self.head(z)\n        return out\n\nclass PositionalEncoding(nn.Module):\n    def __init__(self, d_model, max_len=2000):\n        super().__init__()\n        pe = torch.zeros(max_len, d_model)\n        position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)\n        div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))\n        pe[:, 0::2] = torch.sin(position * div_term)\n        pe[:, 1::2] = torch.cos(position * div_term)\n        self.register_buffer('pe', pe.unsqueeze(0))\n    def forward(self, x):\n        # x: [B,L,D]\n        L = x.size(1)\n        return x + self.pe[:, :L, :]\n\nclass VanillaTransformer(nn.Module):\n    def __init__(self, in_dim, n_class, d_model=128, nhead=4, num_layers=2, dim_ff=256, p=0.1):\n        super().__init__()\n        self.proj = nn.Linear(in_dim, d_model)\n        self.pe = PositionalEncoding(d_model)\n        enc_layer = nn.TransformerEncoderLayer(d_model=d_model, nhead=nhead, dim_feedforward=dim_ff, dropout=p, batch_first=True)\n        self.enc = nn.TransformerEncoder(enc_layer, num_layers=num_layers)\n        self.head = nn.Sequential(nn.AdaptiveAvgPool1d(1), nn.Flatten(), nn.Linear(d_model, n_class))\n    def forward(self, x):\n        # x: [B,L,C]\n        z = self.proj(x)\n        z = self.pe(z)\n        z = self.enc(z)           # [B,L,D]\n        z = z.transpose(1,2)      # [B,D,L]\n        out = self.head(z)\n        return out\n\n# Time Series Transformer (TST) – channel/token projection + class token\nclass TST(nn.Module):\n    def __init__(self, in_dim, n_class, d_model=128, nhead=4, num_layers=2, dim_ff=256, p=0.1):\n        super().__init__()\n        self.proj = nn.Linear(in_dim, d_model)\n        self.cls = nn.Parameter(torch.randn(1,1,d_model))\n        self.pe = PositionalEncoding(d_model)\n        enc_layer = nn.TransformerEncoderLayer(d_model=d_model, nhead=nhead, dim_feedforward=dim_ff, dropout=p, batch_first=True)\n        self.enc = nn.TransformerEncoder(enc_layer, num_layers=num_layers)\n        self.head = nn.Linear(d_model, n_class)\n    def forward(self, x):\n        B = x.size(0)\n        z = self.proj(x)\n        z = self.pe(z)\n        cls = self.cls.expand(B, -1, -1)\n        z = torch.cat([cls, z], dim=1)  # [B,1+L,D]\n        z = self.enc(z)\n        out = self.head(z[:,0])\n        return out\n\n# Informer-like (ProbSparse-style approximation): keep top-k keys per head via attention masking\nclass InformerLite(nn.Module):\n    def __init__(self, in_dim, n_class, d_model=128, nhead=4, num_layers=2, dim_ff=256, p=0.1, topk=32):\n        super().__init__()\n        self.proj = nn.Linear(in_dim, d_model)\n        self.pe = PositionalEncoding(d_model)\n        self.layers = nn.ModuleList([\n            nn.TransformerEncoderLayer(d_model=d_model, nhead=nhead, dim_feedforward=dim_ff, dropout=p, batch_first=True)\n            for _ in range(num_layers)\n        ])\n        self.head = nn.Sequential(nn.AdaptiveAvgPool1d(1), nn.Flatten(), nn.Linear(d_model, n_class))\n        self.topk = topk\n    def forward(self, x):\n        z = self.proj(x)\n        z = self.pe(z)\n        # approximate sparsity by randomly masking tokens except top-k by variance (cheap proxy)\n        with torch.no_grad():\n            var = z.var(dim=-1)              # [B,L]\n            k = min(self.topk, z.size(1))\n            idx = var.topk(k, dim=1).indices # [B,k]\n            mask = torch.zeros(z.size(0), z.size(1), dtype=torch.bool, device=z.device)\n            for b in range(z.size(0)):\n                mask[b, idx[b]] = True\n        # keep tokens\n        kept = []\n        for b in range(z.size(0)):\n            kept.append(z[b][mask[b]])\n        # pad back to max k\n        kmax = max(t.size(0) for t in kept)\n        z2 = torch.zeros(z.size(0), kmax, z.size(-1), device=z.device)\n        for b,t in enumerate(kept): z2[b,:t.size(0)] = t\n        for lyr in self.layers:\n            z2 = lyr(z2)\n        z2 = z2.transpose(1,2)\n        out = self.head(z2)\n        return out\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-15T01:45:30.757351Z","iopub.execute_input":"2025-09-15T01:45:30.757681Z","iopub.status.idle":"2025-09-15T01:45:30.782147Z","shell.execute_reply.started":"2025-09-15T01:45:30.757613Z","shell.execute_reply":"2025-09-15T01:45:30.781171Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# =====================\n# 4) TRAIN LOOP & UTILS\n# =====================\n\ndef count_params(model):\n    return sum(p.numel() for p in model.parameters() if p.requires_grad)\n\n@torch.no_grad()\ndef evaluate(model, dl):\n    model.eval()\n    y_true, y_pred = [], []\n    for xb, yb in dl:\n        xb = xb.to(DEVICE); yb = yb.to(DEVICE)\n        logits = model(xb)\n        preds = logits.argmax(dim=1).cpu().numpy()\n        y_true.extend(yb.cpu().numpy()); y_pred.extend(preds)\n    f1 = f1_score(y_true, y_pred, average='macro')\n    return f1\n\n\ndef train_model(model, dl_tr, dl_va, epochs=10, lr=3e-4):\n    model = model.to(DEVICE)\n    opt = torch.optim.AdamW(model.parameters(), lr=lr)\n    best_f1, best_state = -1, None\n    t0 = time.time()\n    for ep in range(1, epochs+1):\n        model.train()\n        for xb, yb in dl_tr:\n            xb = xb.to(DEVICE); yb = yb.to(DEVICE)\n            opt.zero_grad()\n            logits = model(xb)\n            loss = F.cross_entropy(logits, yb)\n            loss.backward(); opt.step()\n        f1 = evaluate(model, dl_va)\n        # print(f\"Epoch {ep}: val F1={f1:.4f}\")\n        if f1 > best_f1:\n            best_f1 = f1\n            best_state = {k: v.detach().cpu().clone() for k,v in model.state_dict().items()}\n    train_time = time.time() - t0\n    if best_state is not None:\n        model.load_state_dict({k: v.to(DEVICE) for k,v in best_state.items()})\n    return best_f1, train_time, count_params(model)\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-15T01:45:30.783078Z","iopub.execute_input":"2025-09-15T01:45:30.783386Z","iopub.status.idle":"2025-09-15T01:45:30.803266Z","shell.execute_reply.started":"2025-09-15T01:45:30.783358Z","shell.execute_reply":"2025-09-15T01:45:30.802346Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# =====================\n# 5) EXPERIMENTS: window sizes & models\n# =====================\nWINDOWS = [50, 100, 200]\nEPOCHS = 8\nBATCH = 128\nRESULTS = []\n\nfor WIN in WINDOWS:\n    print(f\"\\n===== Window {WIN} =====\")\n    X, y = build_windows(train_full, SENSOR_COLS, y_all, TIME_COL, GROUP_COL, win=WIN, stride=WIN//2)\n    # small stratified split\n    tr_idx, va_idx = train_test_split(np.arange(len(y)), test_size=0.2, random_state=42, stratify=y)\n    Xtr, Xva = X[tr_idx], X[va_idx]\n    ytr, yva = y[tr_idx], y[va_idx]\n\n    ds_tr = SeqDataset(Xtr, ytr, fit_scaler=True)\n    ds_va = SeqDataset(Xva, yva, scaler=ds_tr.scaler)\n    dl_tr = DataLoader(ds_tr, batch_size=BATCH, shuffle=True, num_workers=0)\n    dl_va = DataLoader(ds_va, batch_size=BATCH, shuffle=False, num_workers=0)\n\n    C = X.shape[-1]\n\n    # TCN\n    m_tcn = TCN(in_dim=C, n_class=N_CLASS)\n    f1_tcn, t_tcn, p_tcn = train_model(m_tcn, dl_tr, dl_va, epochs=EPOCHS, lr=1e-3)\n    RESULTS.append({'model':'TCN', 'window':WIN, 'f1':f1_tcn, 'time_s':t_tcn, 'params':p_tcn})\n\n    # Vanilla Transformer\n    m_tf = VanillaTransformer(in_dim=C, n_class=N_CLASS, d_model=128, nhead=4, num_layers=2)\n    f1_tf, t_tf, p_tf = train_model(m_tf, dl_tr, dl_va, epochs=EPOCHS, lr=3e-4)\n    RESULTS.append({'model':'Transformer', 'window':WIN, 'f1':f1_tf, 'time_s':t_tf, 'params':p_tf})\n\n    # TST\n    m_tst = TST(in_dim=C, n_class=N_CLASS, d_model=128, nhead=4, num_layers=2)\n    f1_tst, t_tst, p_tst = train_model(m_tst, dl_tr, dl_va, epochs=EPOCHS, lr=3e-4)\n    RESULTS.append({'model':'TST', 'window':WIN, 'f1':f1_tst, 'time_s':t_tst, 'params':p_tst})\n\n    # Informer-like (lite)\n    m_inf = InformerLite(in_dim=C, n_class=N_CLASS, d_model=128, nhead=4, num_layers=2, topk=min(64, WIN))\n    f1_inf, t_inf, p_inf = train_model(m_inf, dl_tr, dl_va, epochs=EPOCHS, lr=3e-4)\n    RESULTS.append({'model':'InformerLite', 'window':WIN, 'f1':f1_inf, 'time_s':t_inf, 'params':p_inf})\n\n    gc.collect(); torch.cuda.empty_cache()\n\nres_df = pd.DataFrame(RESULTS)\nprint(\"\\nResults (macro-F1):\\n\", res_df.pivot(index='window', columns='model', values='f1'))\nprint(\"\\nComplexity (time_s & #params):\\n\", res_df.groupby(['model','window'])[['time_s','params']].mean())\n\n# Plot F1 vs window\nplt.figure(figsize=(6,4))\nfor m in res_df['model'].unique():\n    d = res_df[res_df['model']==m]\n    plt.plot(d['window'], d['f1'], marker='o', label=m)\nplt.xlabel('Window length'); plt.ylabel('Macro-F1'); plt.title('Scaling window length')\nplt.legend(); plt.tight_layout(); plt.show()\n\nprint(\"\\nNotebook 3 – Done.\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-15T01:45:30.804349Z","iopub.execute_input":"2025-09-15T01:45:30.804608Z","iopub.status.idle":"2025-09-15T02:45:38.944605Z","shell.execute_reply.started":"2025-09-15T01:45:30.804587Z","shell.execute_reply":"2025-09-15T02:45:38.943890Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import time\nimport numpy as np\nimport pandas as pd\nfrom sklearn.metrics import f1_score, accuracy_score\n\ndef benchmark_inference(model, dl, device=None, warmup=1):\n    device = device or DEVICE\n    model.eval()\n    # warmup\n    with torch.no_grad():\n        for _ in range(warmup):\n            for xb, _ in dl:\n                xb = xb.to(device)\n                _ = model(xb)\n                break\n    # measure\n    n_samples = 0\n    t0 = time.time()\n    with torch.no_grad():\n        for xb, _ in dl:\n            xb = xb.to(device)\n            _ = model(xb)\n            n_samples += xb.size(0)\n    t1 = time.time()\n    per_sample_ms = (t1 - t0) / max(1, n_samples) * 1000.0\n    return per_sample_ms\n\n@torch.no_grad()\ndef eval_metrics(model, dl, device=None):\n    device = device or DEVICE\n    model.eval()\n    y_true, y_pred = [], []\n    for xb, yb in dl:\n        xb, yb = xb.to(device), yb.to(device)\n        logits = model(xb)\n        y_true.extend(yb.cpu().numpy())\n        y_pred.extend(logits.argmax(1).cpu().numpy())\n    y_true = np.array(y_true); y_pred = np.array(y_pred)\n    macro = f1_score(y_true, y_pred, average='macro')\n    acc   = accuracy_score(y_true, y_pred)\n    if N_CLASS == 2:\n        binary = f1_score(y_true, y_pred, average='binary')\n    else:\n        binary = np.nan\n    return macro, acc, binary\n\ndef pretty_millions(n_params):\n    return round(float(n_params) / 1e6, 3)\n\n# =========================\n# Thu thập & in bảng kết quả\n# =========================\nrows = []\n\n# Bạn có thể tùy biến chuỗi mô tả feature:\nfeatures_used_desc = f\"All sensors ({len(SENSOR_COLS)} ch)\"\n\n# Ví dụ lặp lại train nhanh ở đây, hoặc nếu bạn đã có các biến\n# f1_xx, t_xx, p_xx và model đã train (m_xx) thì chỉ cần gọi eval/benchmark.\n# Dưới đây minh họa cho 4 model đã train trong vòng lặp window WIN:\n\nmodels_pack = [\n    (\"TCN\",           m_tcn,  f1_tcn,  t_tcn,  p_tcn,  \"AdamW\"),\n    (\"Transformer\",   m_tf,   f1_tf,   t_tf,   p_tf,   \"AdamW\"),\n    (\"TST\",           m_tst,  f1_tst,  t_tst,  p_tst,  \"AdamW\"),\n    (\"InformerLite\",  m_inf,  f1_inf,  t_inf,  p_inf,  \"AdamW\"),\n]\n\nfor name, model, f1_val_returned, train_time_s, n_params, optim_name in models_pack:\n    # Đo lại metrics và thời gian suy luận cho chuẩn\n    macro, val_acc, binary = eval_metrics(model, dl_va, DEVICE)\n    infer_ms = benchmark_inference(model, dl_va, DEVICE)\n\n    row = {\n        \"model\":               name,\n        \"features_used\":       features_used_desc,\n        \"window_size\":         WIN,\n        \"optimizer/solver\":    optim_name,\n        \"params (M)\":          pretty_millions(n_params),\n        \"Binary\":              round(binary, 4) if not np.isnan(binary) else np.nan,\n        \"Macro\":               round(macro, 4),\n        \"Final Score\":         round(macro, 4),   # bạn có thể đổi công thức nếu cần\n        \"val_acc\":             round(val_acc, 4),\n        \"train_time\":          round(float(train_time_s), 2),       # giây\n        \"inference_time\":      round(float(infer_ms), 3),           # ms / sample\n    }\n    rows.append(row)\n\nreport_df = pd.DataFrame(rows, columns=[\n    \"model\", \"features_used\", \"window_size\", \"optimizer/solver\", \"params (M)\",\n    \"Binary\", \"Macro\", \"Final Score\", \"val_acc\", \"train_time\", \"inference_time\"\n])\n\n# Sắp xếp hiển thị (tuỳ bạn)\nreport_df = report_df.sort_values([\"window_size\", \"Final Score\"], ascending=[True, False]).reset_index(drop=True)\nprint(report_df)\n\n# Nếu muốn đẹp hơn:\ntry:\n    from IPython.display import display\n    display(report_df)\nexcept:\n    pass\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-15T02:45:38.946202Z","iopub.execute_input":"2025-09-15T02:45:38.946619Z","iopub.status.idle":"2025-09-15T02:45:53.545372Z","shell.execute_reply.started":"2025-09-15T02:45:38.946598Z","shell.execute_reply":"2025-09-15T02:45:53.544585Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# =========================\n# Pivot Table để so sánh theo window & model\n# =========================\n\n# 1) Macro F1: hàng = window_size, cột = model\npivot_macro = report_df.pivot_table(\n    index=\"window_size\", columns=\"model\", values=\"Macro\", aggfunc=\"mean\"\n)\n\n# 2) Complexity: train_time & params\npivot_complexity = report_df.pivot_table(\n    index=\"model\", columns=\"window_size\", values=[\"train_time\",\"params (M)\"], aggfunc=\"mean\"\n)\n\nprint(\"\\n=== Pivot Macro F1 ===\")\ndisplay(pivot_macro)\n\nprint(\"\\n=== Pivot Complexity (train_time & params) ===\")\ndisplay(pivot_complexity)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-15T02:45:53.548640Z","iopub.execute_input":"2025-09-15T02:45:53.548920Z","iopub.status.idle":"2025-09-15T02:45:53.584244Z","shell.execute_reply.started":"2025-09-15T02:45:53.548900Z","shell.execute_reply":"2025-09-15T02:45:53.583355Z"}},"outputs":[],"execution_count":null}]}