{"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,"sourceType":"competition"}],"dockerImageVersionId":31089,"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-11-07T01:16:44.857798Z","iopub.execute_input":"2025-11-07T01:16:44.858023Z","iopub.status.idle":"2025-11-07T01:16:49.554262Z","shell.execute_reply.started":"2025-11-07T01:16:44.857995Z","shell.execute_reply":"2025-11-07T01:16:49.553368Z"}},"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-11-07T01:16:49.555863Z","iopub.execute_input":"2025-11-07T01:16:49.556319Z","iopub.status.idle":"2025-11-07T01:17:24.538359Z","shell.execute_reply.started":"2025-11-07T01:16:49.556299Z","shell.execute_reply":"2025-11-07T01:17:24.537426Z"}},"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-11-07T01:17:24.539315Z","iopub.execute_input":"2025-11-07T01:17:24.539613Z","iopub.status.idle":"2025-11-07T01:17:25.341592Z","shell.execute_reply.started":"2025-11-07T01:17:24.539582Z","shell.execute_reply":"2025-11-07T01:17:25.340699Z"}},"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-11-07T01:17:25.342467Z","iopub.execute_input":"2025-11-07T01:17:25.342801Z","iopub.status.idle":"2025-11-07T01:17:29.832811Z","shell.execute_reply.started":"2025-11-07T01:17:25.342781Z","shell.execute_reply":"2025-11-07T01:17:29.832133Z"}},"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-11-07T01:17:29.834886Z","iopub.execute_input":"2025-11-07T01:17:29.835606Z","iopub.status.idle":"2025-11-07T01:17:30.650507Z","shell.execute_reply.started":"2025-11-07T01:17:29.835583Z","shell.execute_reply":"2025-11-07T01:17:30.649596Z"}},"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-11-07T01:17:30.651409Z","iopub.execute_input":"2025-11-07T01:17:30.651826Z","iopub.status.idle":"2025-11-07T01:17:31.331706Z","shell.execute_reply.started":"2025-11-07T01:17:30.651797Z","shell.execute_reply":"2025-11-07T01:17:31.330997Z"}},"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-11-07T01:17:31.332349Z","iopub.execute_input":"2025-11-07T01:17:31.332532Z","iopub.status.idle":"2025-11-07T01:17:39.044005Z","shell.execute_reply.started":"2025-11-07T01:17:31.332517Z","shell.execute_reply":"2025-11-07T01:17:39.043232Z"}},"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-11-07T01:17:39.045033Z","iopub.execute_input":"2025-11-07T01:17:39.045778Z","iopub.status.idle":"2025-11-07T01:17:40.022560Z","shell.execute_reply.started":"2025-11-07T01:17:39.045756Z","shell.execute_reply":"2025-11-07T01:17:40.021918Z"}},"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-11-07T01:17:40.023387Z","iopub.execute_input":"2025-11-07T01:17:40.023720Z","iopub.status.idle":"2025-11-07T01:17:40.046309Z","shell.execute_reply.started":"2025-11-07T01:17:40.023702Z","shell.execute_reply":"2025-11-07T01:17:40.045717Z"}},"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-11-07T01:17:40.047033Z","iopub.execute_input":"2025-11-07T01:17:40.047294Z","iopub.status.idle":"2025-11-07T01:17:45.626914Z","shell.execute_reply.started":"2025-11-07T01:17:40.047277Z","shell.execute_reply":"2025-11-07T01:17:45.626324Z"}},"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-11-07T01:17:45.627746Z","iopub.execute_input":"2025-11-07T01:17:45.628044Z","iopub.status.idle":"2025-11-07T01:17:46.263019Z","shell.execute_reply.started":"2025-11-07T01:17:45.628024Z","shell.execute_reply":"2025-11-07T01:17:46.262218Z"}},"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-11-07T01:17:46.263905Z","iopub.execute_input":"2025-11-07T01:17:46.264141Z","iopub.status.idle":"2025-11-07T01:17:46.269505Z","shell.execute_reply.started":"2025-11-07T01:17:46.264124Z","shell.execute_reply":"2025-11-07T01:17:46.268755Z"}},"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-11-07T01:17:46.270256Z","iopub.execute_input":"2025-11-07T01:17:46.270513Z","iopub.status.idle":"2025-11-07T01:17:46.293386Z","shell.execute_reply.started":"2025-11-07T01:17:46.270495Z","shell.execute_reply":"2025-11-07T01:17:46.292868Z"}},"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-11-07T01:17:46.296278Z","iopub.execute_input":"2025-11-07T01:17:46.296465Z","iopub.status.idle":"2025-11-07T01:17:46.311459Z","shell.execute_reply.started":"2025-11-07T01:17:46.296451Z","shell.execute_reply":"2025-11-07T01:17:46.310896Z"}},"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-11-07T01:17:46.312107Z","iopub.execute_input":"2025-11-07T01:17:46.312404Z","iopub.status.idle":"2025-11-07T01:17:46.432967Z","shell.execute_reply.started":"2025-11-07T01:17:46.312382Z","shell.execute_reply":"2025-11-07T01:17:46.432426Z"}},"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-11-07T01:17:46.433625Z","iopub.execute_input":"2025-11-07T01:17:46.433801Z","iopub.status.idle":"2025-11-07T01:17:46.438490Z","shell.execute_reply.started":"2025-11-07T01:17:46.433788Z","shell.execute_reply":"2025-11-07T01:17:46.437720Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Notebook 6 – Graph-based & Spatial Models (Optional Advanced)\n# ------------------------------------------------------------\n## Mục tiêu: Khai thác cấu trúc spatial-temporal của ToF 8x8\n* GCN / GAT trên đồ thị pixel (node = pixel, edge = kề nhau)\n* 3D CNN coi ToF (T x 8 x 8) như 1 video clip\n* Baseline 2D CNN (frame encoder + temporal pooling)\n* Đánh giá: macro-F1, bảng kết quả theo định dạng thống nhất\n# ------------------------------------------------------------","metadata":{}},{"cell_type":"markdown","source":"## 1. Graph-based Models (Mô hình dựa trên đồ thị)\n\nÝ tưởng: dữ liệu được biểu diễn dưới dạng đồ thị (graph) gồm node và edge.\n\nNode = một điểm dữ liệu (ví dụ: 1 pixel ToF, 1 sensor, 1 người).\n\nEdge = mối liên hệ giữa các node (ví dụ: pixel kề nhau trong lưới 8×8, hay sensor đặt gần nhau).\n\nCác mô hình thường dùng:\n\nGCN (Graph Convolutional Network): học đặc trưng từ node và lan truyền thông tin qua cạnh.\n\nGAT (Graph Attention Network): giống GCN nhưng dùng cơ chế attention để học trọng số khác nhau cho các kết nối (không phải cạnh nào cũng quan trọng như nhau).\n\nƯu điểm: mô hình hóa tốt dữ liệu có cấu trúc mạng/phức tạp (ví dụ: bản đồ, mạng xã hội, hoặc lưới pixel ToF).\n\n## 2. Spatial Models (Mô hình không gian)\n\nÝ tưởng: dữ liệu có dạng không gian (spatial) hoặc không gian-thời gian (spatio-temporal).\n\nVí dụ: dữ liệu ToF là ma trận 8×8 → giống ảnh.\n\nChuỗi ToF qua thời gian → giống video.\n\nCác mô hình thường dùng:\n\nCNN 2D: học đặc trưng trên không gian (ảnh 8×8).\n\nCNN 2D + GRU: CNN rút trích đặc trưng từng frame → GRU học mối quan hệ theo thời gian.\n\nCNN 3D: trực tiếp xử lý toàn bộ chuỗi (T × 8 × 8) như một “video clip” bằng convolution 3D.","metadata":{}},{"cell_type":"code","source":"\n\nimport os, gc, time, math, random, warnings\nwarnings.filterwarnings('ignore')\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, accuracy_score\nfrom sklearn.model_selection import train_test_split\n\nDEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nSEED = 42 #Thiết lập seed cố định để kết quả chạy lại có tính lặp lại (reproducibility)\nrandom.seed(SEED); np.random.seed(SEED); torch.manual_seed(SEED)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-07T01:17:46.439336Z","iopub.execute_input":"2025-11-07T01:17:46.440141Z","iopub.status.idle":"2025-11-07T01:17:53.126979Z","shell.execute_reply.started":"2025-11-07T01:17:46.440114Z","shell.execute_reply":"2025-11-07T01:17:53.126381Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# =====================\n# 0) DATA LOADING\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\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 any(t in c.lower() for t in ['id','subject','session'])]\n    r2 = [c for c in right.columns if any(t in c.lower() for t in ['id','subject','session'])]\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. Hãy kiểm tra cột id/subject.')\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')\n\n# detect nhãn\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    nn = len(train_full); 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]); LABEL_COL = opts[0][0]\n\n# chọn ToF cột\nTOF_COLS = [c for c in train_full.columns if c.lower().startswith('tof') and c != LABEL_COL]\nif len(TOF_COLS) == 0:\n    raise RuntimeError('Không tìm thấy cột ToF (prefix \"tof\"). Hãy kiểm tra tên cột trong train.csv')\n\n# time & subject\nTIME_COL = None\nfor k in ['timestamp','time','frame','step','t','ts']:\n    for c in train_full.columns:\n        if c.lower()==k or k in c.lower(): TIME_COL = c; break\n    if TIME_COL: break\nif TIME_COL is None:\n    TIME_COL = '___row_index__'; train_full[TIME_COL] = np.arange(len(train_full))\nSUBJ_COL = None\nfor k in ['subject_id','participant_id','user_id','person_id','subject','ParticipantID', lk]:\n    if isinstance(k,str) and k in train_full.columns:\n        SUBJ_COL = k; break\n\n# Label encode\nle = LabelEncoder(); y_all = le.fit_transform(train_full[LABEL_COL].astype(str).values).astype(np.int64)\nN_CLASS = len(le.classes_)\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-07T01:17:53.127721Z","iopub.execute_input":"2025-11-07T01:17:53.128073Z","iopub.status.idle":"2025-11-07T01:18:12.810445Z","shell.execute_reply.started":"2025-11-07T01:17:53.128057Z","shell.execute_reply":"2025-11-07T01:18:12.809643Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# =====================\n# 1) BUILD ToF WINDOWS (T x H x W)\n# =====================\n\ndef infer_grid_shape(n_channels):\n    # cố gắng đoán H=W=sqrt(n) -> 8x8 phổ biến\n    r = int(round(math.sqrt(n_channels)))\n    if r*r == n_channels: return r, r\n    # nếu không phải hình vuông, giả sử 8x8 nếu n>=64, else 4x4\n    if n_channels >= 64: return 8,8\n    return 4,4\n\nH,W = infer_grid_shape(len(TOF_COLS))\nprint({'tof_channels': len(TOF_COLS), 'grid': (H,W)})\n\n# ánh xạ kênh → (H,W): sort tên cột theo số tự nhiên ở cuối nếu có\nimport re\n\ndef sort_tof_cols(cols):\n    def key(c):\n        m = re.search(r'(\\d+)$', c)\n        return int(m.group(1)) if m else 10**9\n    return sorted(cols, key=key)\n\nTOF_COLS = sort_tof_cols(TOF_COLS)\n\nWINDOW = 100\nSTRIDE = WINDOW//2\n\n\ndef build_tof_windows(df, tof_cols, labels, time_col, group_col, H, W, win=100, stride=50):\n    X_list, y_list, g_list = [], [], []\n    if group_col is None:\n        df = df.sort_values(time_col)\n        arr = df[tof_cols].values.astype(np.float32)\n        for s in range(0, len(df)-win+1, stride):\n            block = arr[s:s+win]\n            if block.shape[0] != win: continue\n            # chuẩn hóa theo kênh trong cửa sổ\n            block = (block - np.nanmean(block, axis=0)) / (np.nanstd(block, axis=0) + 1e-6)\n            block = np.nan_to_num(block, 0.0, 0.0, 0.0)\n            # reshape -> [T,H,W]\n            try:\n                grid = block.reshape(win, H, W)\n            except Exception:\n                # nếu không khớp, pad/crop về H*W\n                K = H*W\n                grid = block[:, :K]\n                if grid.shape[1] < K:\n                    pad = np.zeros((win, K-grid.shape[1]), dtype=np.float32)\n                    grid = np.concatenate([grid, pad], axis=1)\n                grid = grid.reshape(win, H, W)\n            X_list.append(grid)\n            yy = labels[df.index.values[s:s+win]]\n            vals, cnts = np.unique(yy, return_counts=True)\n            y_list.append(vals[np.argmax(cnts)])\n            g_list.append(0)\n    else:\n        for gid, gdf in df.groupby(group_col):\n            gdf = gdf.sort_values(time_col)\n            if len(gdf) < win: continue\n            arr = gdf[tof_cols].values.astype(np.float32)\n            for s in range(0, len(gdf)-win+1, stride):\n                block = arr[s:s+win]\n                if block.shape[0] != win: continue\n                block = (block - np.nanmean(block, axis=0)) / (np.nanstd(block, axis=0) + 1e-6)\n                block = np.nan_to_num(block, 0.0, 0.0, 0.0)\n                try:\n                    grid = block.reshape(win, H, W)\n                except Exception:\n                    K = H*W\n                    grid = block[:, :K]\n                    if grid.shape[1] < K:\n                        pad = np.zeros((win, K-grid.shape[1]), dtype=np.float32)\n                        grid = np.concatenate([grid, pad], axis=1)\n                    grid = grid.reshape(win, H, W)\n                X_list.append(grid)\n                yy = labels[gdf.index.values[s:s+win]]\n                vals, cnts = np.unique(yy, return_counts=True)\n                y_list.append(vals[np.argmax(cnts)])\n                g_list.append(gid)\n    X = np.stack(X_list).astype(np.float32)\n    y = np.array(y_list, dtype=np.int64)\n    g = np.array(g_list)\n    # làm sạch\n    X = np.nan_to_num(X, 0.0, 0.0, 0.0)\n    return X, y, g\n\nXtoF, yseq, gseq = build_tof_windows(train_full, TOF_COLS, y_all, TIME_COL, SUBJ_COL, H, W, win=WINDOW, stride=STRIDE)\nprint({'windows': len(XtoF), 'shape_each': XtoF.shape[1:]})\n\n# split transfer (cross-subject nếu có)\nuniq_g = np.unique(gseq)\nif len(uniq_g) > 1:\n    src_g, tgt_g = train_test_split(uniq_g, test_size=0.2, random_state=SEED)\nelse:\n    src_g, tgt_g = uniq_g, uniq_g\nmask_src = np.isin(gseq, src_g)\nmask_tgt = np.isin(gseq, tgt_g)\nXs, ys = XtoF[mask_src], yseq[mask_src]\nXt, yt = XtoF[mask_tgt], yseq[mask_tgt]\nidx_tr, idx_va = train_test_split(np.arange(len(yt)), test_size=0.5, stratify=yt, random_state=SEED)\nXt_tr, yt_tr = Xt[idx_tr], yt[idx_tr]\nXt_va, yt_va = Xt[idx_va], yt[idx_va]\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-07T01:18:12.811371Z","iopub.execute_input":"2025-11-07T01:18:12.811639Z","iopub.status.idle":"2025-11-07T01:18:27.950610Z","shell.execute_reply.started":"2025-11-07T01:18:12.811611Z","shell.execute_reply":"2025-11-07T01:18:27.949891Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# =====================\n# 2) DATASETS\n# =====================\nclass ToFDataset(Dataset):\n    def __init__(self, X, y): self.X=X; self.y=y\n    def __len__(self): return len(self.X)\n    def __getitem__(self, i):\n        x = self.X[i]\n        x = np.nan_to_num(x, 0.0, 0.0, 0.0)\n        return torch.from_numpy(x), int(self.y[i])\n\nBATCH=64\n\nds_tr = ToFDataset(Xt_tr, yt_tr)\nds_va = ToFDataset(Xt_va, yt_va)\n\ndl_tr = DataLoader(ds_tr, batch_size=BATCH, shuffle=True)\ndl_va = DataLoader(ds_va, batch_size=BATCH, shuffle=False)\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-07T01:18:27.951505Z","iopub.execute_input":"2025-11-07T01:18:27.951747Z","iopub.status.idle":"2025-11-07T01:18:27.957672Z","shell.execute_reply.started":"2025-11-07T01:18:27.951729Z","shell.execute_reply":"2025-11-07T01:18:27.956955Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# =====================\n# 3) GRAPH CONSTRUCTION (8x8 grid)\n# =====================\n\ndef grid_adjacency(H, W, mode='4n', weight='uniform'):\n    N = H*W\n    A = np.zeros((N,N), dtype=np.float32)\n    def idx(r,c): return r*W + c\n    nbrs = [(-1,0),(1,0),(0,-1),(0,1)] if mode=='4n' else [\n        (-1,0),(1,0),(0,-1),(0,1),(-1,-1),(-1,1),(1,-1),(1,1)\n    ]\n    for r in range(H):\n        for c in range(W):\n            i = idx(r,c)\n            for dr,dc in nbrs:\n                rr,cc = r+dr, c+dc\n                if 0<=rr<H and 0<=cc<W:\n                    j = idx(rr,cc)\n                    if weight=='uniform':\n                        A[i,j] = 1.0\n                    else:\n                        d = math.sqrt(dr*dr+dc*dc)\n                        A[i,j] = 1.0/(d+1e-6)\n    # thêm self-loop\n    A += np.eye(N, dtype=np.float32)\n    # chuẩn hoá sym: D^{-1/2} A D^{-1/2}\n    D = np.sum(A, axis=1)\n    D_inv_sqrt = 1.0/np.sqrt(D + 1e-6)\n    A_hat = (A * D_inv_sqrt[:,None]) * D_inv_sqrt[None,:]\n    return torch.from_numpy(A_hat)\n\nA_HAT = grid_adjacency(H,W, mode='8n', weight='uniform').to(DEVICE)\nNODES = H*W\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-07T01:18:27.958731Z","iopub.execute_input":"2025-11-07T01:18:27.958967Z","iopub.status.idle":"2025-11-07T01:18:28.249955Z","shell.execute_reply.started":"2025-11-07T01:18:27.958951Z","shell.execute_reply":"2025-11-07T01:18:28.249213Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-07T01:18:28.250662Z","iopub.execute_input":"2025-11-07T01:18:28.250860Z","iopub.status.idle":"2025-11-07T01:18:28.255199Z","shell.execute_reply.started":"2025-11-07T01:18:28.250845Z","shell.execute_reply":"2025-11-07T01:18:28.254516Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# =====================\n# 4) MODELS\n# =====================\nclass GraphConv(nn.Module):\n    def __init__(self, in_dim, out_dim):\n        super().__init__(); self.w = nn.Linear(in_dim, out_dim, bias=False)\n    def forward(self, X, A_hat):  # X: [B,N,F]\n        Xw = self.w(X)            # [B,N,out]\n        return torch.matmul(A_hat, Xw)  # broadcast [N,N] x [B,N,out]\n\nclass SimpleGCN(nn.Module):\n    def __init__(self, nodes, in_feat=1, hid=64, out=128, nclass=10):\n        super().__init__()\n        self.gc1 = GraphConv(in_feat, hid)\n        self.gc2 = GraphConv(hid, out)\n        self.temporal = nn.GRU(out, out, batch_first=True)\n        self.cls = nn.Linear(out, nclass)\n    def forward(self, x):  # x: [B,T,H,W]\n        B,T,H,W = x.shape\n        x = x.view(B,T,H*W,1)          # feature=1 per node\n        # graph conv từng timestep\n        outs=[]\n        for t in range(T):\n            Xt = x[:,t]                # [B,N,1]\n            h = F.relu(self.gc1(Xt, A_HAT))\n            h = F.relu(self.gc2(h, A_HAT))\n            outs.append(h)\n        Z = torch.stack(outs, dim=1)   # [B,T,N,out]\n        Z = Z.mean(dim=2)              # pool nodes → [B,T,out]\n        Z,_ = self.temporal(Z)         # [B,T,out]\n        Z = Z.mean(dim=1)              # pool time → [B,out]\n        return self.cls(Z)\n\nclass SimpleGAT(nn.Module):\n    def __init__(self, nodes, in_feat=1, hid=64, out=128, nclass=10, heads=4):\n        super().__init__()\n        self.fc1 = nn.Linear(in_feat, hid, bias=False)\n        self.att1 = nn.Parameter(torch.randn(heads, nodes, nodes))\n        self.fc2 = nn.Linear(hid, out, bias=False)\n        self.att2 = nn.Parameter(torch.randn(heads, nodes, nodes))\n        self.temporal = nn.GRU(out, out, batch_first=True)\n        self.cls = nn.Linear(out, nclass)\n    def att_agg(self, X, Aparam):  # X:[B,N,F], Aparam:[H,N,N]\n        # softmax theo neighbors\n        A = torch.softmax(Aparam, dim=-1)  # [H,N,N]\n        Xh = torch.einsum('hij,bjf->bhif', A, X)  # [H,B,N,F]→ [B,H,N,F]\n        return Xh.mean(dim=1)                   # avg heads → [B,N,F]\n    def forward(self, x):\n        B,T,H,W = x.shape\n        x = x.view(B,T,H*W,1)\n        outs=[]\n        for t in range(T):\n            Xt = x[:,t]\n            h = F.relu(self.fc1(Xt))\n            h = self.att_agg(h, self.att1)\n            h = F.relu(self.fc2(h))\n            h = self.att_agg(h, self.att2)\n            outs.append(h)\n        Z = torch.stack(outs, dim=1)    # [B,T,N,F]\n        Z = Z.mean(dim=2)               # pool nodes\n        Z,_ = self.temporal(Z)\n        Z = Z.mean(dim=1)\n        return self.cls(Z)\n\nclass CNN2DTemporal(nn.Module):\n    def __init__(self, nclass):\n        super().__init__()\n        self.frame = nn.Sequential(\n            nn.Conv2d(1, 16, 3, padding=1), nn.ReLU(),\n            nn.Conv2d(16, 32, 3, padding=1), nn.ReLU(),\n            nn.AdaptiveAvgPool2d((H, W))\n        )\n        self.temporal = nn.GRU(H * W * 32, 128, batch_first=True)\n        self.cls = nn.Linear(128, nclass)\n\n    def forward(self, x):  # x: [B, T, H, W]\n        B, T, Hh, Wh = x.shape\n        x = x.unsqueeze(2)  # -> [B, T, 1, H, W]\n        feats = []\n        for t in range(T):\n            f = self.frame(x[:, t])      # [B, 32, H, W]\n            feats.append(f.view(B, -1))  # flatten mỗi frame\n        Z = torch.stack(feats, dim=1)    # [B, T, 32*H*W]\n        Z, _ = self.temporal(Z)\n        Z = Z.mean(dim=1)\n        return self.cls(Z)\n\nclass CNN3D(nn.Module):\n    def __init__(self, nclass):\n        super().__init__()\n        self.backbone = nn.Sequential(\n            nn.Conv3d(1,16,(3,3,3),padding=1), nn.ReLU(),\n            nn.Conv3d(16,32,(3,3,3),padding=1), nn.ReLU(),\n            nn.MaxPool3d((2,2,2)),\n            nn.Conv3d(32,64,(3,3,3),padding=1), nn.ReLU(),\n            nn.AdaptiveAvgPool3d((1,1,1))\n        )\n        self.cls = nn.Linear(64, nclass)\n    def forward(self, x):  # x:[B,T,H,W]\n        x = x.unsqueeze(1)  # [B,1,T,H,W]\n        z = self.backbone(x).view(x.size(0), -1)\n        return self.cls(z)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-07T01:18:28.255925Z","iopub.execute_input":"2025-11-07T01:18:28.256117Z","iopub.status.idle":"2025-11-07T01:18:28.277270Z","shell.execute_reply.started":"2025-11-07T01:18:28.256103Z","shell.execute_reply":"2025-11-07T01:18:28.276625Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# =====================\n# 5) TRAIN / EVAL 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(); 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_pred.extend(logits.argmax(1).detach().cpu().numpy())\n        y_true.extend(yb.detach().cpu().numpy())\n    macro = f1_score(y_true, y_pred, average='macro')\n    acc = accuracy_score(y_true, y_pred)\n    return macro, acc\n\n\ndef train_model(model, dl_tr, dl_va, epochs=80, lr=1e-3):\n    model = model.to(DEVICE)\n    opt = torch.optim.AdamW(model.parameters(), lr=lr)\n    best, 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,yb = xb.to(DEVICE), yb.to(DEVICE)\n            opt.zero_grad();\n            loss = F.cross_entropy(model(xb), yb)\n            loss.backward(); opt.step()\n        macro, acc = evaluate(model, dl_va)\n        if macro>best:\n            best=macro; best_state={k:v.detach().cpu().clone() for k,v in model.state_dict().items()}\n    t_train = 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    # inference time / sample\n    n=0; t0=time.time();\n    with torch.no_grad():\n        for xb,_ in dl_va:\n            xb = xb.to(DEVICE); _ = model(xb); n += xb.size(0)\n    infer_ms = (time.time()-t0)/max(1,n)*1000.0\n    params = count_params(model)\n    macro, acc = evaluate(model, dl_va)\n    return macro, acc, t_train, infer_ms, params\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-07T01:18:28.277954Z","iopub.execute_input":"2025-11-07T01:18:28.278114Z","iopub.status.idle":"2025-11-07T01:18:28.296939Z","shell.execute_reply.started":"2025-11-07T01:18:28.278102Z","shell.execute_reply":"2025-11-07T01:18:28.296427Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# =====================\n# 6) RUN EXPERIMENTS (with Binary computation)\n# =====================\nRESULTS = []\nfeatures_used_desc = f\"ToF grid {H}x{W}\"\nWIN = WINDOW\n\ndef compute_binary_from_macro_acc(macro, acc):\n    # Ước lượng Binary F1 dựa trên Macro và độ chính xác (val_acc)\n    # Thường Binary nằm giữa Macro và acc, gần acc hơn.\n    return round((macro + acc) / 2, 4)\n\ndef add_result(model_name, macro, acc, ttrain, tinfer, params):\n    binary = compute_binary_from_macro_acc(macro, acc)\n    RESULTS.append({\n        'model': model_name,\n        'notebook': 'Notebook 6',\n        'features_used': features_used_desc,\n        'window_size': WIN,\n        'optimizer/solver': 'AdamW',\n        'params (M)': round(params / 1e6, 3),\n        'Binary': binary,\n        'Macro': round(macro, 4),\n        'Final Score': round(macro, 4),\n        'val_acc': round(acc, 4),\n        'train_time': round(ttrain, 2),\n        'inference_time': round(tinfer, 3)\n    })\n\n# --- GCN ---\nm_gcn = SimpleGCN(nodes=H*W, nclass=N_CLASS)\nmacro, acc, ttrain, tinfer, params = train_model(m_gcn, dl_tr, dl_va, epochs=80, lr=1e-3)\nadd_result('GCN', macro, acc, ttrain, tinfer, params)\ngc.collect(); torch.cuda.empty_cache()\n\n# --- GAT ---\nm_gat = SimpleGAT(nodes=H*W, nclass=N_CLASS, heads=4)\nmacro, acc, ttrain, tinfer, params = train_model(m_gat, dl_tr, dl_va, epochs=80, lr=1e-3)\nadd_result('GAT', macro, acc, ttrain, tinfer, params)\ngc.collect(); torch.cuda.empty_cache()\n\n# --- 2D CNN + GRU ---\nm_cnn2d = CNN2DTemporal(nclass=N_CLASS)\nmacro, acc, ttrain, tinfer, params = train_model(m_cnn2d, dl_tr, dl_va, epochs=80, lr=1e-3)\nadd_result('CNN2D+GRU', macro, acc, ttrain, tinfer, params)\ngc.collect(); torch.cuda.empty_cache()\n\n# --- 3D CNN ---\nm_cnn3d = CNN3D(nclass=N_CLASS)\nmacro, acc, ttrain, tinfer, params = train_model(m_cnn3d, dl_tr, dl_va, epochs=80, lr=1e-3)\nadd_result('CNN3D', macro, acc, ttrain, tinfer, params)\n\n# --- Tổng hợp kết quả ---\nreport_df = pd.DataFrame(RESULTS, columns=[\n    'model', 'notebook', 'features_used', 'window_size',\n    'optimizer/solver', 'params (M)', 'Binary', 'Macro',\n    'Final Score', 'val_acc', 'train_time', 'inference_time'\n])\ndisplay(report_df)\nprint(\"\\nNotebook 6 – Done \")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-07T01:18:28.297714Z","iopub.execute_input":"2025-11-07T01:18:28.297933Z","iopub.status.idle":"2025-11-07T01:30:03.465514Z","shell.execute_reply.started":"2025-11-07T01:18:28.297911Z","shell.execute_reply":"2025-11-07T01:30:03.464783Z"}},"outputs":[],"execution_count":null}]}