{"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":53666,"databundleVersionId":6589269,"sourceType":"competition"},{"sourceId":102335,"databundleVersionId":12518947,"sourceType":"competition"},{"sourceId":12139340,"sourceType":"datasetVersion","datasetId":7645099,"isSourceIdPinned":false},{"sourceId":12293285,"sourceType":"datasetVersion","datasetId":7748073,"isSourceIdPinned":false},{"sourceId":12328761,"sourceType":"datasetVersion","datasetId":7771623,"isSourceIdPinned":false},{"sourceId":12411879,"sourceType":"datasetVersion","datasetId":7827797,"isSourceIdPinned":false},{"sourceId":12573306,"sourceType":"datasetVersion","datasetId":7932089,"isSourceIdPinned":false},{"sourceId":12723935,"sourceType":"datasetVersion","datasetId":7869970,"isSourceIdPinned":false},{"sourceId":142057134,"sourceType":"kernelVersion"},{"sourceId":240649816,"sourceType":"kernelVersion"},{"sourceId":242651758,"sourceType":"kernelVersion"},{"sourceId":246893721,"sourceType":"kernelVersion"},{"sourceId":248244433,"sourceType":"kernelVersion"},{"sourceId":249600984,"sourceType":"kernelVersion"},{"sourceId":250757185,"sourceType":"kernelVersion"},{"sourceId":251413288,"sourceType":"kernelVersion"},{"sourceId":257476184,"sourceType":"kernelVersion"}],"dockerImageVersionId":31090,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\nimport kagglehub\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n\n# Download latest version\npath = kagglehub.dataset_download(\"kerta27/cmi-data-tensorflow-train\")\npath = kagglehub.dataset_download(\"hideyukizushi/cmi25-imu-thmtof-tf-bilstm-gru-attentionlb-xx\")\npath = kagglehub.dataset_download(\"kerta27/cmi-data-gated-gru\")\npath = kagglehub.dataset_download(\"hideyukizushi/20250627-cmi-b-102-b-105\")\npath = kagglehub.dataset_download(\"hideyukizushi/cmi-d-111\")\npath = kagglehub.dataset_download(\"myso1987/cmi3-models-p\")\n\nprint(\"Path to dataset files:\", path)\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2025-08-22T19:06:15.012536Z","iopub.execute_input":"2025-08-22T19:06:15.013208Z","iopub.status.idle":"2025-08-22T19:06:16.449881Z","shell.execute_reply.started":"2025-08-22T19:06:15.013182Z","shell.execute_reply":"2025-08-22T19:06:16.449126Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# https://www.kaggle.com/code/wasupandceacar/deterministic\n# https://www.kaggle.com/code/hideyukizushi/lb-0-78-quaternions-tf-bilstm-gru-attention\n# https://www.kaggle.com/code/majiaqi111/n-splits-10\n# https://www.kaggle.com/code/hideyukizushi/cmi25-imu-thm-tof-tf-blendingmodel-lb-82\n# https://www.kaggle.com/code/wasupandceacar/cmi-metric","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-22T19:06:16.451073Z","iopub.execute_input":"2025-08-22T19:06:16.451345Z","iopub.status.idle":"2025-08-22T19:06:16.454899Z","shell.execute_reply.started":"2025-08-22T19:06:16.451328Z","shell.execute_reply":"2025-08-22T19:06:16.454180Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import tensorflow as tf\nprint(\"TensorFlow Version:\", tf.__version__)\nprint(\"Built with CUDA:\", tf.test.is_built_with_cuda())\nfrom tensorflow.python.platform import build_info as tf_build_info\nprint(\"cuDNN version:\", tf_build_info.build_info['cudnn_version'])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-22T19:06:16.455584Z","iopub.execute_input":"2025-08-22T19:06:16.455830Z","iopub.status.idle":"2025-08-22T19:06:28.499984Z","shell.execute_reply.started":"2025-08-22T19:06:16.455808Z","shell.execute_reply":"2025-08-22T19:06:28.499144Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os, json, joblib, numpy as np, pandas as pd\nimport random\nfrom pathlib import Path\nimport warnings \nwarnings.filterwarnings(\"ignore\")\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler, LabelEncoder\nfrom sklearn.utils.class_weight import compute_class_weight\n\nfrom tensorflow.keras.utils import Sequence, to_categorical, pad_sequences\nfrom tensorflow.keras.models import Model, load_model\nfrom tensorflow.keras.layers import (\n    Input, Conv1D, BatchNormalization, Activation, add, MaxPooling1D, Dropout,\n    Bidirectional, LSTM, GlobalAveragePooling1D, Dense, Multiply, Reshape,\n    Lambda, Concatenate, GRU, GaussianNoise\n)\nfrom tensorflow.keras.regularizers import l2\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.callbacks import EarlyStopping\nfrom tensorflow.keras import backend as K\nimport tensorflow as tf\nimport polars as pl\nfrom sklearn.model_selection import StratifiedGroupKFold\nfrom scipy.spatial.transform import Rotation as R\n\ndef seed_everything(seed):\n    os.environ['PYTHONHASHSEED'] = str(seed)\n    random.seed(seed)\n    np.random.seed(seed)\n    tf.random.set_seed(seed)\n    tf.experimental.numpy.random.seed(seed)\n    os.environ['TF_CUDNN_DETERMINISTIC'] = '1'\n    os.environ['TF_DETERMINISTIC_OPS'] = '1'\n\nseed_everything(seed=42)\n# (Competition metric will only be imported when TRAINing)\nTRAIN = False                     # ← set to True when you want to train\nRAW_DIR = Path(\"/kaggle/input/cmi-detect-behavior-with-sensor-data\")\nPRETRAINED_DIR = Path(\"/kaggle/input/cmi-d-111\")\nEXPORT_DIR = Path(\"./\")                                    # artefacts will be saved here\nBATCH_SIZE = 64\nPAD_PERCENTILE = 95\nLR_INIT = 5e-4\nWD = 3e-3\nMIXUP_ALPHA = 0.4\nEPOCHS = 160\nPATIENCE = 40\n\nprint(\"▶ imports ready · tensorflow\", tf.__version__)\n\n#Tensor Manipulations\ndef time_sum(x):\n    return K.sum(x, axis=1)\n\ndef squeeze_last_axis(x):\n    return tf.squeeze(x, axis=-1)\n\ndef expand_last_axis(x):\n    return tf.expand_dims(x, axis=-1)\n\ndef se_block(x, reduction=8):\n    ch = x.shape[-1]\n    se = GlobalAveragePooling1D()(x)\n    se = Dense(ch // reduction, activation='relu')(se)\n    se = Dense(ch, activation='sigmoid')(se)\n    se = Reshape((1, ch))(se)\n    return Multiply()([x, se])\n\n# Residual CNN Block with SE\ndef residual_se_cnn_block(x, filters, kernel_size, pool_size=2, drop=0.3, wd=1e-4):\n    shortcut = x\n    for _ in range(2):\n        x = Conv1D(filters, kernel_size, padding='same', use_bias=False,\n                   kernel_regularizer=l2(wd))(x)\n        x = BatchNormalization()(x)\n        x = Activation('relu')(x)\n    x = se_block(x)\n    if shortcut.shape[-1] != filters:\n        shortcut = Conv1D(filters, 1, padding='same', use_bias=False,\n                          kernel_regularizer=l2(wd))(shortcut)\n        shortcut = BatchNormalization()(shortcut)\n    x = add([x, shortcut])\n    x = Activation('relu')(x)\n    x = MaxPooling1D(pool_size)(x)\n    x = Dropout(drop)(x)\n    return x\n\ndef attention_layer(inputs):\n    score = Dense(1, activation='tanh')(inputs)\n    score = Lambda(squeeze_last_axis)(score)\n    weights = Activation('softmax')(score)\n    weights = Lambda(expand_last_axis)(weights)\n    context = Multiply()([inputs, weights])\n    context = Lambda(time_sum)(context)\n    return context\n\n# Normalizes and cleans the time series sequence. \ndef preprocess_sequence(df_seq: pd.DataFrame, feature_cols: list[str], scaler: StandardScaler):\n    mat = df_seq[feature_cols].ffill().bfill().fillna(0).values\n    return scaler.transform(mat).astype('float32')\n\n# MixUp the data argumentation in order to regularize the neural network. \nclass MixupGenerator(Sequence):\n    def __init__(self, X, y, batch_size, alpha=0.2):\n        self.X, self.y = X, y\n        self.batch = batch_size\n        self.alpha = alpha\n        self.indices = np.arange(len(X))\n    def __len__(self):\n        return int(np.ceil(len(self.X) / self.batch))\n    def __getitem__(self, i):\n        idx = self.indices[i*self.batch:(i+1)*self.batch]\n        Xb, yb = self.X[idx], self.y[idx]\n        lam = np.random.beta(self.alpha, self.alpha)\n        perm = np.random.permutation(len(Xb))\n        X_mix = lam * Xb + (1-lam) * Xb[perm]\n        y_mix = lam * yb + (1-lam) * yb[perm]\n        return X_mix, y_mix\n    def on_epoch_end(self):\n        np.random.shuffle(self.indices)\n\ndef remove_gravity_from_acc(acc_data, rot_data):\n    if isinstance(acc_data, pd.DataFrame):\n        acc_values = acc_data[['acc_x', 'acc_y', 'acc_z']].values\n    else:\n        acc_values = acc_data\n    if isinstance(rot_data, pd.DataFrame):\n        quat_values = rot_data[['rot_x', 'rot_y', 'rot_z', 'rot_w']].values\n    else:\n        quat_values = rot_data\n    num_samples = acc_values.shape[0]\n    linear_accel = np.zeros_like(acc_values)\n    gravity_world = np.array([0, 0, 9.81])\n    for i in range(num_samples):\n        if np.all(np.isnan(quat_values[i])) or np.all(np.isclose(quat_values[i], 0)):\n            linear_accel[i, :] = acc_values[i, :] \n            continue\n        try:\n            rotation = R.from_quat(quat_values[i])\n            gravity_sensor_frame = rotation.apply(gravity_world, inverse=True)\n            linear_accel[i, :] = acc_values[i, :] - gravity_sensor_frame\n        except ValueError:\n            linear_accel[i, :] = acc_values[i, :]\n    return linear_accel\n\ndef calculate_angular_velocity_from_quat(rot_data, time_delta=1/200): # Assuming 200Hz sampling rate\n    if isinstance(rot_data, pd.DataFrame):\n        quat_values = rot_data[['rot_x', 'rot_y', 'rot_z', 'rot_w']].values\n    else:\n        quat_values = rot_data\n    num_samples = quat_values.shape[0]\n    angular_vel = np.zeros((num_samples, 3))\n    for i in range(num_samples - 1):\n        q_t = quat_values[i]\n        q_t_plus_dt = quat_values[i+1]\n        if np.all(np.isnan(q_t)) or np.all(np.isclose(q_t, 0)) or \\\n           np.all(np.isnan(q_t_plus_dt)) or np.all(np.isclose(q_t_plus_dt, 0)):\n            continue\n        try:\n            rot_t = R.from_quat(q_t)\n            rot_t_plus_dt = R.from_quat(q_t_plus_dt)\n            delta_rot = rot_t.inv() * rot_t_plus_dt\n            angular_vel[i, :] = delta_rot.as_rotvec() / time_delta\n        except ValueError:\n            pass\n    return angular_vel\n\ndef calculate_angular_distance(rot_data):\n    if isinstance(rot_data, pd.DataFrame):\n        quat_values = rot_data[['rot_x', 'rot_y', 'rot_z', 'rot_w']].values\n    else:\n        quat_values = rot_data\n    num_samples = quat_values.shape[0]\n    angular_dist = np.zeros(num_samples)\n    for i in range(num_samples - 1):\n        q1 = quat_values[i]\n        q2 = quat_values[i+1]\n        if np.all(np.isnan(q1)) or np.all(np.isclose(q1, 0)) or \\\n           np.all(np.isnan(q2)) or np.all(np.isclose(q2, 0)):\n            angular_dist[i] = 0\n            continue\n        try:\n            r1 = R.from_quat(q1)\n            r2 = R.from_quat(q2)\n            relative_rotation = r1.inv() * r2\n            angle = np.linalg.norm(relative_rotation.as_rotvec())\n            angular_dist[i] = angle\n        except ValueError:\n            angular_dist[i] = 0\n            pass\n    return angular_dist\n\ndef build_two_branch_model(pad_len, imu_dim, tof_dim, n_classes, wd=1e-4):\n    inp = Input(shape=(pad_len, imu_dim+tof_dim))\n    imu = Lambda(lambda t: t[:, :, :imu_dim])(inp)\n    tof = Lambda(lambda t: t[:, :, imu_dim:])(inp)\n    x1 = residual_se_cnn_block(imu, 64, 3, drop=0.1, wd=wd)\n    x1 = residual_se_cnn_block(x1, 128, 5, drop=0.1, wd=wd)\n    x2 = Conv1D(64, 3, padding='same', use_bias=False, kernel_regularizer=l2(wd))(tof)\n    x2 = BatchNormalization()(x2); x2 = Activation('relu')(x2)\n    x2 = MaxPooling1D(2)(x2); x2 = Dropout(0.2)(x2)\n    x2 = Conv1D(128, 3, padding='same', use_bias=False, kernel_regularizer=l2(wd))(x2)\n    x2 = BatchNormalization()(x2); x2 = Activation('relu')(x2)\n    x2 = MaxPooling1D(2)(x2); x2 = Dropout(0.2)(x2)\n    merged = Concatenate()([x1, x2])\n    xa = Bidirectional(LSTM(128, return_sequences=True, kernel_regularizer=l2(wd)))(merged)\n    xb = Bidirectional(GRU(128, return_sequences=True, kernel_regularizer=l2(wd)))(merged)\n    xc = GaussianNoise(0.09)(merged)\n    xc = Dense(16, activation='elu')(xc)\n    x = Concatenate()([xa, xb, xc])\n    x = Dropout(0.4)(x)\n    x = attention_layer(x)\n    for units, drop in [(256, 0.5), (128, 0.3)]:\n        x = Dense(units, use_bias=False, kernel_regularizer=l2(wd))(x)\n        x = BatchNormalization()(x); x = Activation('relu')(x)\n        x = Dropout(drop)(x)\n    out = Dense(n_classes, activation='softmax', kernel_regularizer=l2(wd))(x)\n    return Model(inp, out)\n\ntmp_model = build_two_branch_model(127,7,325,18)\n\ncustom_objs = {\n    'time_sum': time_sum, 'squeeze_last_axis': squeeze_last_axis, 'expand_last_axis': expand_last_axis,\n    'se_block': se_block, 'residual_se_cnn_block': residual_se_cnn_block, 'attention_layer': attention_layer,\n}\n\n# ----------------------------------------------------------------- #\n# Load any Models\n# * is 2 Train Model Load\n# ----------------------------------------------------------------- #\n\nPRETRAINED_DIR = Path(\"/kaggle/input/cmi-d-111\")\nprint(\"▶ INFERENCE MODE 1,2 – loading artefacts from\", PRETRAINED_DIR)\nfinal_feature_cols = np.load(PRETRAINED_DIR / \"feature_cols.npy\", allow_pickle=True).tolist()\npad_len        = int(np.load(PRETRAINED_DIR / \"sequence_maxlen.npy\"))\nscaler         = joblib.load(PRETRAINED_DIR / \"scaler.pkl\")\ngesture_classes = np.load(PRETRAINED_DIR / \"gesture_classes.npy\", allow_pickle=True)\n\nmodels1 = []\nprint(f\"  Loading models for ensemble inference...\")\nfor fold in range(10):\n    model_path = f\"{PRETRAINED_DIR}/D-111_{fold}.h5\"\n    print(\">>>LoadModel>>>\",model_path)\n    model = load_model(model_path, compile=False, custom_objects=custom_objs)\n    models1.append(model)\nprint(\"-\"*50)\n\nfor fold in range(10):\n    model_path = f\"{PRETRAINED_DIR}/v0629_{fold}.h5\"\n    print(\">>>LoadModel>>>\",model_path)\n    model = load_model(model_path, compile=False, custom_objects=custom_objs)\n    models1.append(model)\nprint(\"-\"*50)\nprint(f\"[INFO]NumUseModels:{len(models1)}\")\n\nPRETRAINED_DIR = Path(\"/kaggle/input/n-splits-10\")\nprint(\"▶ INFERENCE MODE 3 – loading artefacts from\", PRETRAINED_DIR)\nfinal_feature_cols = np.load(PRETRAINED_DIR / \"feature_cols.npy\", allow_pickle=True).tolist()\npad_len        = int(np.load(PRETRAINED_DIR / \"sequence_maxlen.npy\"))\nscaler         = joblib.load(PRETRAINED_DIR / \"scaler.pkl\")\ngesture_classes = np.load(PRETRAINED_DIR / \"gesture_classes.npy\", allow_pickle=True)\nfor fold in range(10):\n    model_path = f\"{PRETRAINED_DIR}/gesture_model_fold_{fold}.h5\"\n    print(\">>>LoadModel>>>\",model_path)\n    model = load_model(model_path, compile=False, custom_objects=custom_objs)\n    models1.append(model)\nprint(\"-\"*50)\nprint(f\"[INFO]NumUseModels:{len(models1)}\")\n\nfor fold in range(10):\n    MODEL_DIR = \"/kaggle/input/cmi-data-tensorflow-train\"\n    model_path = f\"{MODEL_DIR}/gesture_model_fold_{fold}.h5\"\n    print(\">>>LoadModel>>>\",model_path)\n    model = load_model(model_path, compile=False, custom_objects=custom_objs)\n    models1.append(model)\nprint(\"-\"*50)\nprint(f\"[INFO]NumUseModels:{len(models1)}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-22T19:06:28.501991Z","iopub.execute_input":"2025-08-22T19:06:28.502651Z","iopub.status.idle":"2025-08-22T19:06:52.191151Z","shell.execute_reply.started":"2025-08-22T19:06:28.502632Z","shell.execute_reply":"2025-08-22T19:06:52.190438Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def predict1(sequence: pl.DataFrame, demographics: pl.DataFrame) -> str:\n    df_seq = sequence.to_pandas()\n    linear_accel = remove_gravity_from_acc(df_seq, df_seq)\n    df_seq['linear_acc_x'], df_seq['linear_acc_y'], df_seq['linear_acc_z'] = linear_accel[:, 0], linear_accel[:, 1], linear_accel[:, 2]\n    df_seq['linear_acc_mag'] = np.sqrt(df_seq['linear_acc_x']**2 + df_seq['linear_acc_y']**2 + df_seq['linear_acc_z']**2)\n    df_seq['linear_acc_mag_jerk'] = df_seq['linear_acc_mag'].diff().fillna(0)\n    angular_vel = calculate_angular_velocity_from_quat(df_seq)\n    df_seq['angular_vel_x'], df_seq['angular_vel_y'], df_seq['angular_vel_z'] = angular_vel[:, 0], angular_vel[:, 1], angular_vel[:, 2]\n    df_seq['angular_distance'] = calculate_angular_distance(df_seq)\n    \n    for i in range(1, 6):\n        pixel_cols = [f\"tof_{i}_v{p}\" for p in range(64)]; tof_data = df_seq[pixel_cols].replace(-1, np.nan)\n        df_seq[f'tof_{i}_mean'], df_seq[f'tof_{i}_std'], df_seq[f'tof_{i}_min'], df_seq[f'tof_{i}_max'] = tof_data.mean(axis=1), tof_data.std(axis=1), tof_data.min(axis=1), tof_data.max(axis=1)\n        \n    mat_unscaled = df_seq[final_feature_cols].ffill().bfill().fillna(0).values.astype('float32')\n    mat_scaled = scaler.transform(mat_unscaled)\n    pad_input = pad_sequences([mat_scaled], maxlen=pad_len, padding='post', truncating='post', dtype='float32')\n    \n    all_preds = [model.predict(pad_input, verbose=0)[0] for model in models1]\n    avg_pred = np.median(all_preds, axis=0) \n    return avg_pred","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-22T19:06:52.192040Z","iopub.execute_input":"2025-08-22T19:06:52.192312Z","iopub.status.idle":"2025-08-22T19:06:52.201721Z","shell.execute_reply.started":"2025-08-22T19:06:52.192288Z","shell.execute_reply":"2025-08-22T19:06:52.201000Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import polars as pl\nfrom pathlib import Path\n\nRAW_DIR = Path(\"/kaggle/input/cmi-detect-behavior-with-sensor-data\")\n\n# load CSVs\ntrain_df = pl.read_csv(RAW_DIR / \"train.csv\")\ndemo_df = pl.read_csv(RAW_DIR / \"train_demographics.csv\")\n\n# merge on \"subject\" instead of \"sequence_id\"\ntrain_seq = train_df.join(demo_df, on=\"subject\", how=\"left\")\n\n# save parquet\ntrain_seq.write_parquet(\"/kaggle/working/train_sequences.parquet\")\n\nprint(\"✅ train_sequences.parquet saved in /kaggle/working\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-22T19:06:52.202346Z","iopub.execute_input":"2025-08-22T19:06:52.202597Z","iopub.status.idle":"2025-08-22T19:07:09.834628Z","shell.execute_reply.started":"2025-08-22T19:06:52.202573Z","shell.execute_reply":"2025-08-22T19:07:09.833797Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import polars as pl\nimport numpy as np\nfrom pathlib import Path\n\nRAW_DIR = Path('/kaggle/working/')\n\ntry:\n    # Try loading training data first\n    train_seq = pl.read_parquet(RAW_DIR / \"train_sequences.parquet\")\n    feature_cols = [col for col in train_seq.columns if col.startswith(('acc_', 'rot_', 'tof_'))]\n    data = train_seq[feature_cols].to_pandas().ffill().bfill().fillna(0).values\n    print(\"Using train_sequences.parquet for mean/std calculation\")\nexcept FileNotFoundError:\n    print(\"Warning: train_sequences.parquet not found. Using test_sequences.parquet for mean/std estimation.\")\n    try:\n        test_seq = pl.read_parquet(RAW_DIR / \"test_sequences.parquet\")\n        feature_cols = [col for col in test_seq.columns if col.startswith(('acc_', 'rot_', 'tof_'))]\n        data = test_seq[feature_cols].to_pandas().ffill().bfill().fillna(0).values\n    except FileNotFoundError:\n        print(\"Error: Neither train_sequences.parquet nor test_sequences.parquet found. Using default mean=0 and std=1.\")\n        data = np.zeros((1, 332))  # 332 = 7 IMU + 5*64 ToF + 5*5 derived ToF features\n\n# Calculate mean and std\nmean = np.mean(data, axis=0)\nstd = np.std(data, axis=0) + 1e-6  # Avoid division by zero\n\n# Save to files\nnp.save('/kaggle/working/mean.npy', mean)\nnp.save('/kaggle/working/std.npy', std)\nprint(\"Generated mean.npy and std.npy in /kaggle/working\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-22T19:07:09.835853Z","iopub.execute_input":"2025-08-22T19:07:09.836177Z","iopub.status.idle":"2025-08-22T19:07:23.756016Z","shell.execute_reply.started":"2025-08-22T19:07:09.836146Z","shell.execute_reply":"2025-08-22T19:07:23.755274Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def predict3(sequence: pl.DataFrame, demographics: pl.DataFrame) -> np.ndarray:\n    import numpy as np\n    \n    pred1 = predict1(sequence, demographics)  # Model 1 (~0.820)\n    pred2 = predict2(sequence, demographics)  # Model 2 (~0.829)\n    \n    base_weights = {'A': 0.40, 'B': 0.30, 'C': 0.30}\n    \n    perturbation = np.random.uniform(-0.02, 0.02, 3)\n    weights = {\n        'A': max(0.1, min(0.8, base_weights['A'] + perturbation[0])),\n        'B': max(0.1, min(0.8, base_weights['B'] + perturbation[1])),\n        'C': max(0.1, min(0.8, base_weights['C'] + perturbation[2]))\n    }\n    total = sum(weights.values())\n    weights = {k: v/total for k, v in weights.items()}\n    \n    pred = weights['A'] * pred1 + weights['B'] * pred2 + weights['C'] * pred1\n    \n    max_prob = np.max(pred)\n    if max_prob < 0.30:  # Lowered threshold\n        pred = np.zeros_like(pred)\n        pred[np.argmax(pred1)] = 1.0\n    \n    return pred","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-22T19:07:23.756849Z","iopub.execute_input":"2025-08-22T19:07:23.757126Z","iopub.status.idle":"2025-08-22T19:07:23.764052Z","shell.execute_reply.started":"2025-08-22T19:07:23.757101Z","shell.execute_reply":"2025-08-22T19:07:23.763260Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport polars as pl\nfrom pathlib import Path\n\ndef softmax_with_temperature(pred, T=1.0):\n    pred = pred / T\n    exp_pred = np.exp(pred - np.max(pred))  # Subtract max for numerical stability\n    return exp_pred / np.sum(exp_pred)\n\ndef predict(sequence: pl.DataFrame, demographics: pl.DataFrame) -> str:\n    pred = predict3(sequence, demographics)\n    \n    # Apply softmax temperature scaling\n    pred = softmax_with_temperature(pred, T=0.75)  # Sharper predictions\n    \n    # Class-specific correction weights for imbalance\n    class_weights = np.ones(len(gesture_classes))  # Default weights\n    # Boost weights for underrepresented classes (e.g., \"Drink from bottle/cup\")\n    underrepresented = [\"Drink from bottle/cup\"]  # Add other known underrepresented classes\n    for cls in underrepresented:\n        if cls in gesture_classes:\n            idx = np.where(gesture_classes == cls)[0][0]\n            class_weights[idx] = 1.05  # 5% boost for underrepresented classes\n    \n    # Apply correction weights\n    c_w = np.array([+0.0025, -0.0005, -0.0012])\n    pred = pred * (1 + c_w[0]) * class_weights + c_w[1] + np.random.normal(0, abs(c_w[2]), pred.shape)\n    \n    # Ensure probabilities are non-negative and normalized\n    pred = np.clip(pred, 0, None)\n    pred = pred / pred.sum()\n    \n    return gesture_classes[np.argmax(pred)]\n\n# # Submission\n# RAW_DIR = Path('/kaggle/input/cmi-detect-behavior-with-sensor-data')\n# sub = pl.read_csv(RAW_DIR / \"sample_submission.csv\")\n# test_seq = pl.read_parquet(RAW_DIR / \"test_sequences.parquet\")\n# test_demo = pl.read_parquet(RAW_DIR / \"test_demographics.parquet\")\n\n# submission = []\n# for sid in sub[\"sequence_id\"].to_numpy():\n#     sequence = test_seq.filter(pl.col(\"sequence_id\") == sid)\n#     demographics = test_demo.filter(pl.col(\"sequence_id\") == sid)\n#     pred = predict(sequence, demographics)\n#     submission.append({\"sequence_id\": sid, \"gesture\": pred})\n\n# submission_df = pd.DataFrame(submission)\n# submission_df.to_csv(\"submission.csv\", index=False)\n# print(\"Submission file created: submission.csv\")\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-22T19:07:23.784516Z","iopub.execute_input":"2025-08-22T19:07:23.784737Z","iopub.status.idle":"2025-08-22T19:07:23.797372Z","shell.execute_reply.started":"2025-08-22T19:07:23.784718Z","shell.execute_reply":"2025-08-22T19:07:23.796730Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Tomorrow InshaAllah Hit 0.86","metadata":{}},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}