{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.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":41880,"databundleVersionId":5677426,"sourceType":"competition"}],"dockerImageVersionId":30698,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"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\n\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# 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","execution":{"iopub.status.busy":"2024-05-19T15:16:23.430879Z","iopub.execute_input":"2024-05-19T15:16:23.431376Z","iopub.status.idle":"2024-05-19T15:16:23.830490Z","shell.execute_reply.started":"2024-05-19T15:16:23.431344Z","shell.execute_reply":"2024-05-19T15:16:23.829353Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport glob\nimport lightgbm as lgb\n\nfrom sklearn.preprocessing import StandardScaler, OneHotEncoder\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.pipeline import Pipeline\n\nfrom sklearn.impute import SimpleImputer\nfrom imblearn.over_sampling import SMOTE\nfrom imblearn.under_sampling import RandomUnderSampler\nfrom lightgbm import LGBMClassifier\n\nfrom sklearn.cluster import KMeans\nfrom sklearn.feature_selection import mutual_info_classif\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import GridSearchCV\n\nfrom sklearn.metrics import f1_score, accuracy_score, precision_score, recall_score\nfrom sklearn.metrics import confusion_matrix, classification_report","metadata":{"execution":{"iopub.status.busy":"2024-05-19T15:16:34.971258Z","iopub.execute_input":"2024-05-19T15:16:34.972560Z","iopub.status.idle":"2024-05-19T15:16:34.981319Z","shell.execute_reply.started":"2024-05-19T15:16:34.972510Z","shell.execute_reply":"2024-05-19T15:16:34.980432Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data_dir = '/kaggle/input/tlvmc-parkinsons-freezing-gait-prediction/'\n# Read the dataset\n\ndefog_metadata_file = f'{data_dir}defog_metadata.csv'\ntdcsfog_metadata_file = f'{data_dir}tdcsfog_metadata.csv'\nevents_data_file = f'{data_dir}events.csv'\nsubjects_data_file = f'{data_dir}subjects.csv'\ntasks_data_file = f'{data_dir}tasks.csv'\n\n# Read the meta data\n\ndefog_metadata = pd.read_csv(defog_metadata_file)\ntdcsfog_metadata = pd.read_csv(tdcsfog_metadata_file)\nfull_metadata = pd.concat([tdcsfog_metadata, defog_metadata])\n\nevents_data = pd.read_csv(events_data_file)\nsubjects_data = pd.read_csv(subjects_data_file)\ntasks_data = pd.read_csv(tasks_data_file)","metadata":{"execution":{"iopub.status.busy":"2024-05-19T15:16:40.871107Z","iopub.execute_input":"2024-05-19T15:16:40.871607Z","iopub.status.idle":"2024-05-19T15:16:40.935395Z","shell.execute_reply.started":"2024-05-19T15:16:40.871574Z","shell.execute_reply":"2024-05-19T15:16:40.934450Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Read the data and append the Id\ndef read_data(path):\n    df = pd.read_csv(path)\n    df['Id'] = path.split(\"/\")[-1].split(\".\")[0]\n    \n    return df\n\n\n# Read and concatenate all files of the train data from specified dataset\ndef create_full_data(dataset_name):\n    paths = glob.glob(data_dir + f'train/{dataset_name}/*')\n    final_df = pd.concat([read_data(p) for p in paths])\n    final_df['dataset'] = dataset_name\n    \n    return final_df","metadata":{"execution":{"iopub.status.busy":"2024-05-19T15:17:00.932884Z","iopub.execute_input":"2024-05-19T15:17:00.933425Z","iopub.status.idle":"2024-05-19T15:17:00.940830Z","shell.execute_reply.started":"2024-05-19T15:17:00.933352Z","shell.execute_reply":"2024-05-19T15:17:00.939925Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create a dataframe with all tdcsfog data\ntdcsfog_data = create_full_data('tdcsfog')\ntdcsfog_data","metadata":{"execution":{"iopub.status.busy":"2024-05-19T15:17:10.449693Z","iopub.execute_input":"2024-05-19T15:17:10.450192Z","iopub.status.idle":"2024-05-19T15:17:32.917451Z","shell.execute_reply.started":"2024-05-19T15:17:10.450151Z","shell.execute_reply":"2024-05-19T15:17:32.916195Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create a dataframe with all defog data\ndefog_data = create_full_data('defog')\n\n\ndefog_data_valid = defog_data.loc[ \\\n                        (defog_data.Valid == True) & (defog_data.Task == True)].copy()\n\ndefog_data_valid.reset_index(drop=True, inplace=True)\ndefog_data_valid.drop(['Valid', 'Task'], axis=1, inplace=True)\n\ndefog_data_valid\n\n","metadata":{"execution":{"iopub.status.busy":"2024-05-19T15:17:46.282355Z","iopub.execute_input":"2024-05-19T15:17:46.282916Z","iopub.status.idle":"2024-05-19T15:18:17.678694Z","shell.execute_reply.started":"2024-05-19T15:17:46.282876Z","shell.execute_reply":"2024-05-19T15:18:17.677325Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"full_data = pd.concat([tdcsfog_data, defog_data_valid])\n","metadata":{"execution":{"iopub.status.busy":"2024-05-19T15:19:59.080881Z","iopub.execute_input":"2024-05-19T15:19:59.081364Z","iopub.status.idle":"2024-05-19T15:20:00.020721Z","shell.execute_reply.started":"2024-05-19T15:19:59.081332Z","shell.execute_reply":"2024-05-19T15:20:00.019519Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tasks_data['Duration'] = tasks_data['End'] - tasks_data['Begin']\n\ntasks_data = pd.pivot_table(tasks_data, values=['Duration'],\n                                index=['Id'], columns=['Task'],\n                                aggfunc='sum', fill_value=0)\n\ntasks_data.columns = [c[-1] for c in tasks_data.columns]\ntasks_data = tasks_data.reset_index()\n\ntasks_data['t_kmeans'] = KMeans(n_clusters=10, random_state=42, n_init=10) \\\n                    .fit_predict(tasks_data[tasks_data.columns[1:]])\n\n\nsubjects_data = subjects_data.fillna(0).groupby('Subject') \\\n    [['Visit', 'Age', 'YearsSinceDx', 'UPDRSIII_On', 'UPDRSIII_Off', 'NFOGQ']].median()\nsubjects_data = subjects_data.reset_index()\n\nsubjects_data['s_kmeans'] = KMeans(n_clusters=10, random_state=42, n_init=10) \\\n                    .fit_predict(subjects_data[subjects_data.columns[1:]])","metadata":{"execution":{"iopub.status.busy":"2024-05-19T15:20:02.386483Z","iopub.execute_input":"2024-05-19T15:20:02.386964Z","iopub.status.idle":"2024-05-19T15:20:03.196580Z","shell.execute_reply.started":"2024-05-19T15:20:02.386928Z","shell.execute_reply":"2024-05-19T15:20:03.195353Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"full_data = full_data.merge(full_metadata, on='Id', how='inner') \\\n                        .merge(tasks_data[['Id', 't_kmeans']], how='left', on='Id').fillna(-1) \\\n                        .merge(subjects_data.drop('Visit', axis=1),\n                                       on='Subject', how='left').fillna(-1)\n\nfull_data","metadata":{"execution":{"iopub.status.busy":"2024-05-19T15:20:09.034060Z","iopub.execute_input":"2024-05-19T15:20:09.034585Z","iopub.status.idle":"2024-05-19T15:20:43.320834Z","shell.execute_reply.started":"2024-05-19T15:20:09.034550Z","shell.execute_reply":"2024-05-19T15:20:43.319469Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"full_data[full_data.dataset == 'defog'].index[0]","metadata":{"execution":{"iopub.status.busy":"2024-05-19T15:21:12.449669Z","iopub.execute_input":"2024-05-19T15:21:12.450161Z","iopub.status.idle":"2024-05-19T15:21:15.148149Z","shell.execute_reply.started":"2024-05-19T15:21:12.450129Z","shell.execute_reply":"2024-05-19T15:21:15.146895Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"full_data = pd.concat([full_data[:1000_000], full_data[7_062_672:8_062_672]])\nfull_data","metadata":{"execution":{"iopub.status.busy":"2024-05-19T15:21:18.279830Z","iopub.execute_input":"2024-05-19T15:21:18.280338Z","iopub.status.idle":"2024-05-19T15:21:18.579793Z","shell.execute_reply.started":"2024-05-19T15:21:18.280297Z","shell.execute_reply":"2024-05-19T15:21:18.578483Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"events_data['Duration'] = events_data['Completion']-events_data['Init']\n","metadata":{"execution":{"iopub.status.busy":"2024-05-19T15:21:27.799640Z","iopub.execute_input":"2024-05-19T15:21:27.800159Z","iopub.status.idle":"2024-05-19T15:21:27.812038Z","shell.execute_reply.started":"2024-05-19T15:21:27.800109Z","shell.execute_reply":"2024-05-19T15:21:27.810516Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Merge the current chunk with full_data_sample based on the Id column\nfull_data_sample = full_data.merge(events_data[['Id', 'Type','Kinetic', 'Duration']], left_on='Id', right_on='Id', how='left')","metadata":{"execution":{"iopub.status.busy":"2024-05-19T15:21:30.273787Z","iopub.execute_input":"2024-05-19T15:21:30.274289Z","iopub.status.idle":"2024-05-19T15:21:44.076746Z","shell.execute_reply.started":"2024-05-19T15:21:30.274252Z","shell.execute_reply":"2024-05-19T15:21:44.075201Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"full_data_sample","metadata":{"execution":{"iopub.status.busy":"2024-05-19T15:22:25.430265Z","iopub.execute_input":"2024-05-19T15:22:25.430803Z","iopub.status.idle":"2024-05-19T15:22:36.134847Z","shell.execute_reply.started":"2024-05-19T15:22:25.430765Z","shell.execute_reply":"2024-05-19T15:22:36.133385Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"full_data[full_data.dataset == 'defog'].index[0]","metadata":{"execution":{"iopub.status.busy":"2024-05-19T15:22:44.448891Z","iopub.execute_input":"2024-05-19T15:22:44.450620Z","iopub.status.idle":"2024-05-19T15:22:45.025844Z","shell.execute_reply.started":"2024-05-19T15:22:44.450577Z","shell.execute_reply":"2024-05-19T15:22:45.024358Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"full_data_sample = pd.concat([full_data_sample[:1000_000], full_data_sample[7_062_672:8_062_672]])\nfull_data_sample","metadata":{"execution":{"iopub.status.busy":"2024-05-19T15:22:50.838787Z","iopub.execute_input":"2024-05-19T15:22:50.839190Z","iopub.status.idle":"2024-05-19T15:22:52.786593Z","shell.execute_reply.started":"2024-05-19T15:22:50.839161Z","shell.execute_reply":"2024-05-19T15:22:52.785194Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Step 1: Handle missing values\n# Use SimpleImputer for numerical and categorical columns\nnum_imputer = SimpleImputer(strategy='mean')  # Fill missing values with mean for numerical columns\ncat_imputer = SimpleImputer(strategy='most_frequent')  # Fill missing values with most frequent for categorical columns\n\n# Step 2: Identify numerical and categorical columns\nnumerical_cols = full_data_sample.select_dtypes(include=[np.number]).columns.tolist()  # All numerical columns\ncategorical_cols = full_data_sample.select_dtypes(include=[object, 'category']).columns.tolist()  # All categorical columns\n\n# Step 3: Convert specific categorical data to numerical\n# Convert 'Medication' to 0 for 'off', 1 otherwise\nfull_data_sample['Medication'] = np.where(full_data_sample['Medication'] == 'off', 0, 1)\n\n# Step 4: Scale numerical data using StandardScaler\nscaler = StandardScaler()  # To standardize the numerical columns\n\n# Step 5: Create a preprocessing pipeline\n# Combine transformations for numerical and categorical columns\npreprocessor = ColumnTransformer(\n    transformers=[\n        ('num', Pipeline([('impute', num_imputer), ('scale', scaler)]), numerical_cols),  # Numerical data: Impute then scale\n        ('cat', Pipeline([('impute', cat_imputer), ('encode', OneHotEncoder(drop='first'))]), categorical_cols)  # Categorical data: Impute then one-hot encode\n    ],\n    remainder='drop'  # Drop any other columns not specified\n)\n\n\n\n# Step 7: Apply preprocessing pipeline to the DataFrame\n# This will apply the transformations defined in 'preprocessor' to 'full_data_sample'\npreprocessed_data = preprocessor.fit_transform(full_data_sample)\n\n# Step 8: Print the preprocessed data\nprint(\"Preprocessed Data:\")\npreprocessed_data  # This shows the transformed data (likely as a numpy array)\n","metadata":{"execution":{"iopub.status.busy":"2024-05-19T15:23:23.949834Z","iopub.execute_input":"2024-05-19T15:23:23.950294Z","iopub.status.idle":"2024-05-19T15:23:38.045259Z","shell.execute_reply.started":"2024-05-19T15:23:23.950261Z","shell.execute_reply":"2024-05-19T15:23:38.044097Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create new features based on accelerometer data columns and returns the updated dataframe\ndef create_features(df):\n    acc_cols = ['AccV', 'AccML', 'AccAP']\n\n    # Adjusted backfill operations\n    for acc in acc_cols:\n        df[f'{acc}_lag_2'] = df.groupby('Id')[acc].shift(2).bfill()\n        df[f'{acc}_lag_3'] = df.groupby('Id')[acc].shift(3).bfill()\n        df[f'{acc}_lag_4'] = df.groupby('Id')[acc].shift(4).bfill()\n        df[f'{acc}_lag_5'] = df.groupby('Id')[acc].shift(5).bfill()\n\n        df[f'{acc}_cumsum'] = (df[acc]).groupby(df['Id']).cumsum()\n\n        df[f'{acc}_first_value'] = df.groupby('Id')[acc].transform('first')\n        df[f'{acc}_last_value'] = df.groupby('Id')[acc].transform('last')\n\n        df[f'{acc}_mean'] = df.groupby('Id')[acc].transform('mean')\n        df[f'{acc}_median'] = df.groupby('Id')[acc].transform('median')\n        df[f'{acc}_std'] = df.groupby('Id')[acc].transform('std')\n\n        df[f'{acc}_min'] = df.groupby('Id')[acc].transform('min')\n        df[f'{acc}_max'] = df.groupby('Id')[acc].transform('max')\n\n        df[f'{acc}_delta'] = df[f'{acc}_max'] - df[f'{acc}_min']\n\n        # Adjusted backfill operations for rolling mean\n        for lag in [1, 2, 3]:\n            df[f'ma_{lag}_{acc}'] = df[acc].rolling(lag).mean().bfill()\n            df[f'ma{lag}_{acc}'] = df[acc].rolling(lag).mean().bfill()\n\n    return df","metadata":{"execution":{"iopub.status.busy":"2024-05-19T15:23:42.156000Z","iopub.execute_input":"2024-05-19T15:23:42.156518Z","iopub.status.idle":"2024-05-19T15:23:42.171952Z","shell.execute_reply.started":"2024-05-19T15:23:42.156480Z","shell.execute_reply":"2024-05-19T15:23:42.170691Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Apply the above function to our dataset\nfull_data_sample = create_features(full_data_sample)\nfull_data_sample","metadata":{"execution":{"iopub.status.busy":"2024-05-19T15:23:48.935448Z","iopub.execute_input":"2024-05-19T15:23:48.935887Z","iopub.status.idle":"2024-05-19T15:24:01.199346Z","shell.execute_reply.started":"2024-05-19T15:23:48.935856Z","shell.execute_reply":"2024-05-19T15:24:01.198033Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"full_data_sample.info()","metadata":{"execution":{"iopub.status.busy":"2024-05-19T15:24:13.113864Z","iopub.execute_input":"2024-05-19T15:24:13.114375Z","iopub.status.idle":"2024-05-19T15:24:13.138514Z","shell.execute_reply.started":"2024-05-19T15:24:13.114329Z","shell.execute_reply":"2024-05-19T15:24:13.137100Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create multiclass event type column\nfull_data_sample['target'] = 'Normal'\ntargets = ['StartHesitation', 'Turn', 'Walking']\nfor target in targets:\n    full_data_sample.loc[full_data_sample[target] == 1, 'target'] = target\n    ","metadata":{"execution":{"iopub.status.busy":"2024-05-19T15:24:58.177772Z","iopub.execute_input":"2024-05-19T15:24:58.178228Z","iopub.status.idle":"2024-05-19T15:24:58.236955Z","shell.execute_reply.started":"2024-05-19T15:24:58.178194Z","shell.execute_reply":"2024-05-19T15:24:58.235239Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Assign variables with predictors and target\nX = full_data_sample.drop(['Id','dataset', 'Subject', 'StartHesitation', 'Turn', 'Walking', 'Type' ], axis=1).copy()\ny = X.pop('target')","metadata":{"execution":{"iopub.status.busy":"2024-05-19T15:25:16.654563Z","iopub.execute_input":"2024-05-19T15:25:16.655078Z","iopub.status.idle":"2024-05-19T15:25:19.742371Z","shell.execute_reply.started":"2024-05-19T15:25:16.655045Z","shell.execute_reply":"2024-05-19T15:25:19.741114Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X","metadata":{"execution":{"iopub.status.busy":"2024-05-19T15:26:26.861265Z","iopub.execute_input":"2024-05-19T15:26:26.861855Z","iopub.status.idle":"2024-05-19T15:26:27.334893Z","shell.execute_reply.started":"2024-05-19T15:26:26.861819Z","shell.execute_reply":"2024-05-19T15:26:27.333635Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y","metadata":{"execution":{"iopub.status.busy":"2024-05-19T15:26:34.186067Z","iopub.execute_input":"2024-05-19T15:26:34.186653Z","iopub.status.idle":"2024-05-19T15:26:34.198177Z","shell.execute_reply.started":"2024-05-19T15:26:34.186611Z","shell.execute_reply":"2024-05-19T15:26:34.196877Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X.fillna(X.mean(), inplace=True)","metadata":{"execution":{"iopub.status.busy":"2024-05-19T15:27:01.807002Z","iopub.execute_input":"2024-05-19T15:27:01.807535Z","iopub.status.idle":"2024-05-19T15:27:03.930505Z","shell.execute_reply.started":"2024-05-19T15:27:01.807494Z","shell.execute_reply":"2024-05-19T15:27:03.929008Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"discrete_features = X.dtypes == int\n\n# Calculate MI scores for the features in X with respect to the target variable y\ndef make_mi_scores(X, y, discrete_features):\n    mi_scores = mutual_info_classif(X, y, discrete_features=discrete_features)\n    mi_scores = pd.Series(mi_scores, name=\"MI Scores\", index=X.columns)\n    mi_scores = mi_scores.sort_values(ascending=False)\n    return mi_scores\n\n# Apply this function to our data\nmi_scores = make_mi_scores(X, y, discrete_features)","metadata":{"execution":{"iopub.status.busy":"2024-05-19T15:27:06.860754Z","iopub.execute_input":"2024-05-19T15:27:06.863960Z","iopub.status.idle":"2024-05-19T15:50:30.457645Z","shell.execute_reply.started":"2024-05-19T15:27:06.863906Z","shell.execute_reply":"2024-05-19T15:50:30.456019Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Show 20 features with the highest MI score\nmi_scores.to_frame().head(20)","metadata":{"execution":{"iopub.status.busy":"2024-05-19T15:50:49.769488Z","iopub.execute_input":"2024-05-19T15:50:49.769961Z","iopub.status.idle":"2024-05-19T15:50:49.784976Z","shell.execute_reply.started":"2024-05-19T15:50:49.769926Z","shell.execute_reply":"2024-05-19T15:50:49.783618Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def plot_mi_scores(scores):\n    scores = scores.sort_values(ascending=False)\n    fig, ax = plt.subplots(figsize=(13, 11))\n    ax = sns.barplot(x=scores.values, y=scores.index, palette=\"coolwarm\", orient='h')\n    ax.set_title(\"Mutual Information Scores\")\n    ax.set_xlabel(\"MI Scores\")\n    ax.set_ylabel(\"Features\")\n    plt.show()\n\nplot_mi_scores(mi_scores)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-05-19T15:50:58.265019Z","iopub.execute_input":"2024-05-19T15:50:58.265568Z","iopub.status.idle":"2024-05-19T15:50:59.529717Z","shell.execute_reply.started":"2024-05-19T15:50:58.265521Z","shell.execute_reply":"2024-05-19T15:50:59.528447Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n\n# Add the 'duration' column to the X dataframe\nif 'Duration' not in X.columns:\n    X['Duration'] = full_data_sample['Duration']\n\n# Now you can filter the features to keep 'Time' and 'duration'\nn_top_features = 20  # Or any other number you prefer\ntop_features = mi_scores.head(n_top_features).index.tolist()\nif 'Time' not in top_features:\n    top_features = ['Time'] + top_features\nif 'Duration' not in top_features:\n    top_features = ['Duration'] + top_features\nfiltered_df = X[top_features]  # Keep only the specified features","metadata":{"execution":{"iopub.status.busy":"2024-05-19T15:51:07.018887Z","iopub.execute_input":"2024-05-19T15:51:07.019442Z","iopub.status.idle":"2024-05-19T15:51:07.131758Z","shell.execute_reply.started":"2024-05-19T15:51:07.019369Z","shell.execute_reply":"2024-05-19T15:51:07.130326Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"filtered_df","metadata":{"execution":{"iopub.status.busy":"2024-05-19T15:51:14.824318Z","iopub.execute_input":"2024-05-19T15:51:14.824798Z","iopub.status.idle":"2024-05-19T15:51:16.092557Z","shell.execute_reply.started":"2024-05-19T15:51:14.824763Z","shell.execute_reply":"2024-05-19T15:51:16.091430Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y.value_counts()","metadata":{"execution":{"iopub.status.busy":"2024-05-19T15:51:24.564919Z","iopub.execute_input":"2024-05-19T15:51:24.565978Z","iopub.status.idle":"2024-05-19T15:51:24.850638Z","shell.execute_reply.started":"2024-05-19T15:51:24.565927Z","shell.execute_reply":"2024-05-19T15:51:24.848991Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n# Create a SMOTE object\nsmote = SMOTE(random_state=42)\n\n# Apply SMOTE to your dataset\nX_smote, y_smote = smote.fit_resample(filtered_df, y)\n\n# Verify that the class distribution is now balanced\nprint(y_smote.value_counts())","metadata":{"execution":{"iopub.status.busy":"2024-05-19T15:52:51.713655Z","iopub.execute_input":"2024-05-19T15:52:51.714156Z","iopub.status.idle":"2024-05-19T17:05:42.809160Z","shell.execute_reply.started":"2024-05-19T15:52:51.714115Z","shell.execute_reply":"2024-05-19T17:05:42.805545Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Split the balanced data into training and testing sets\nX_train, X_test, y_train, y_test = train_test_split(X_smote, y_smote, test_size=0.2, random_state=42, stratify=y_smote)\n\n","metadata":{"execution":{"iopub.status.busy":"2024-05-19T17:05:51.308061Z","iopub.execute_input":"2024-05-19T17:05:51.308681Z","iopub.status.idle":"2024-05-19T17:06:05.827641Z","shell.execute_reply.started":"2024-05-19T17:05:51.308607Z","shell.execute_reply":"2024-05-19T17:06:05.826527Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_train.shape","metadata":{"execution":{"iopub.status.busy":"2024-05-19T17:50:51.997460Z","iopub.execute_input":"2024-05-19T17:50:51.997950Z","iopub.status.idle":"2024-05-19T17:50:52.005348Z","shell.execute_reply.started":"2024-05-19T17:50:51.997915Z","shell.execute_reply":"2024-05-19T17:50:52.004458Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":" y_train.shape","metadata":{"execution":{"iopub.status.busy":"2024-05-19T17:51:20.193955Z","iopub.execute_input":"2024-05-19T17:51:20.195057Z","iopub.status.idle":"2024-05-19T17:51:20.207082Z","shell.execute_reply.started":"2024-05-19T17:51:20.195013Z","shell.execute_reply":"2024-05-19T17:51:20.205921Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_test.shape","metadata":{"execution":{"iopub.status.busy":"2024-05-19T17:51:05.351584Z","iopub.execute_input":"2024-05-19T17:51:05.352350Z","iopub.status.idle":"2024-05-19T17:51:05.363831Z","shell.execute_reply.started":"2024-05-19T17:51:05.352312Z","shell.execute_reply":"2024-05-19T17:51:05.362791Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_test.shape","metadata":{"execution":{"iopub.status.busy":"2024-05-19T17:51:39.640855Z","iopub.execute_input":"2024-05-19T17:51:39.641337Z","iopub.status.idle":"2024-05-19T17:51:39.649887Z","shell.execute_reply.started":"2024-05-19T17:51:39.641304Z","shell.execute_reply":"2024-05-19T17:51:39.648583Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_test.value_counts()","metadata":{"execution":{"iopub.status.busy":"2024-05-19T17:06:15.665263Z","iopub.execute_input":"2024-05-19T17:06:15.665765Z","iopub.status.idle":"2024-05-19T17:06:15.937042Z","shell.execute_reply.started":"2024-05-19T17:06:15.665727Z","shell.execute_reply":"2024-05-19T17:06:15.935766Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n\n\nlgbm_clf = lgb.LGBMClassifier(\n   metric='multi_logloss',\n    n_estimators=100, \n    num_class=3,\n    num_leaves=31, \n    objective='multiclass', \n    random_state=42)\n\n\n# Train the LGBM model\nlgbm_clf.fit(X_train, y_train)","metadata":{"execution":{"iopub.status.busy":"2024-05-19T19:36:59.677357Z","iopub.execute_input":"2024-05-19T19:36:59.678171Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Evaluate the model on the training data\ny_pred = lgbm_clf.predict(X_train)\n\nprint(\" Train Accuracy: \", accuracy_score(y_train, y_pred)) \n","metadata":{"execution":{"iopub.status.busy":"2024-05-19T19:33:55.152676Z","iopub.execute_input":"2024-05-19T19:33:55.153514Z","iopub.status.idle":"2024-05-19T19:35:45.222873Z","shell.execute_reply.started":"2024-05-19T19:33:55.153475Z","shell.execute_reply":"2024-05-19T19:35:45.221495Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Make predictions on the testing set\ny_pred = lgbm_clf.predict(X_test)\n\nprint(\" Test Accuracy: \", accuracy_score(y_test, y_pred))\n","metadata":{"execution":{"iopub.status.busy":"2024-05-19T19:36:11.603833Z","iopub.execute_input":"2024-05-19T19:36:11.604793Z","iopub.status.idle":"2024-05-19T19:36:38.542662Z","shell.execute_reply.started":"2024-05-19T19:36:11.604753Z","shell.execute_reply":"2024-05-19T19:36:38.541340Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"Test Classification Report: \\n\", classification_report(y_test, y_pred))\n","metadata":{"execution":{"iopub.status.busy":"2024-05-19T19:05:15.813330Z","iopub.execute_input":"2024-05-19T19:05:15.814420Z","iopub.status.idle":"2024-05-19T19:06:56.444170Z","shell.execute_reply.started":"2024-05-19T19:05:15.814369Z","shell.execute_reply":"2024-05-19T19:06:56.442769Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"Test Confusion Matrix: \\n\", confusion_matrix(y_test, y_pred))","metadata":{"execution":{"iopub.status.busy":"2024-05-19T19:21:10.644253Z","iopub.execute_input":"2024-05-19T19:21:10.645633Z","iopub.status.idle":"2024-05-19T19:21:21.807683Z","shell.execute_reply.started":"2024-05-19T19:21:10.645587Z","shell.execute_reply":"2024-05-19T19:21:21.806415Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Define the confusion matrix\n# Calculate the confusion matrix\ncm = confusion_matrix(y_test, y_pred)\n# Create a figure with one subplot\nfig, ax = plt.subplots(figsize=(10, 8))\n\n# Plot the confusion matrix\nsns.heatmap(cm, annot=True, ax=ax, cmap=\"Blues\", fmt=\"d\")\nax.set_title(\" Confusion Matrix\")\nax.set_xlabel(\"Predicted Values\")\nax.set_ylabel(\"Actual Values\")\n\n\nplt.xticks(np.arange(4), ['Normal', 'StartHesitation', 'Turn', 'Walking'])\nplt.yticks(np.arange(4), ['Normal', 'StartHesitation', 'Turn', 'Walking' ])\n\n\n# Show the plot\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-05-19T19:21:36.945242Z","iopub.execute_input":"2024-05-19T19:21:36.945733Z","iopub.status.idle":"2024-05-19T19:21:48.626218Z","shell.execute_reply.started":"2024-05-19T19:21:36.945700Z","shell.execute_reply":"2024-05-19T19:21:48.625039Z"},"trusted":true},"execution_count":null,"outputs":[]}]}