{"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-06-12T07:02:05.604295Z","iopub.execute_input":"2024-06-12T07:02:05.604672Z","iopub.status.idle":"2024-06-12T07:02:06.259419Z","shell.execute_reply.started":"2024-06-12T07:02:05.604639Z","shell.execute_reply":"2024-06-12T07:02:06.258368Z"},"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 lightgbm import LGBMClassifier\n\n\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-06-12T07:02:16.675937Z","iopub.execute_input":"2024-06-12T07:02:16.676462Z","iopub.status.idle":"2024-06-12T07:02:18.995406Z","shell.execute_reply.started":"2024-06-12T07:02:16.676429Z","shell.execute_reply":"2024-06-12T07:02:18.994590Z"},"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    df.Time = df.Time / (len(df) - 1)  # Normalize the Time column\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-06-12T06:34:26.875508Z","iopub.execute_input":"2024-06-12T06:34:26.876155Z","iopub.status.idle":"2024-06-12T06:34:26.882662Z","shell.execute_reply.started":"2024-06-12T06:34:26.876126Z","shell.execute_reply":"2024-06-12T06:34:26.881645Z"},"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-06-12T06:34:29.503968Z","iopub.execute_input":"2024-06-12T06:34:29.504335Z","iopub.status.idle":"2024-06-12T06:34:29.563524Z","shell.execute_reply.started":"2024-06-12T06:34:29.504307Z","shell.execute_reply":"2024-06-12T06:34:29.562668Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create a dataframe with all tdcsfog data\ntdcsfog_data = create_full_data('tdcsfog')\n\n# Reset the index to match the number of rows\ntdcsfog_data.reset_index(drop=True, inplace=True)\n\ntdcsfog_data\n","metadata":{"execution":{"iopub.status.busy":"2024-06-12T06:34:35.751034Z","iopub.execute_input":"2024-06-12T06:34:35.751768Z","iopub.status.idle":"2024-06-12T06:34:52.480429Z","shell.execute_reply.started":"2024-06-12T06:34:35.751735Z","shell.execute_reply":"2024-06-12T06:34:52.479429Z"},"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","metadata":{"execution":{"iopub.status.busy":"2024-06-12T06:35:07.657092Z","iopub.execute_input":"2024-06-12T06:35:07.657917Z","iopub.status.idle":"2024-06-12T06:35:32.089919Z","shell.execute_reply.started":"2024-06-12T06:35:07.657883Z","shell.execute_reply":"2024-06-12T06:35:32.088904Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"full_data = pd.concat([tdcsfog_data, defog_data_valid])\n# Reset the index to match the number of rows\nfull_data.reset_index(drop=True, inplace=True)\nfull_data","metadata":{"execution":{"iopub.status.busy":"2024-06-12T06:35:43.653005Z","iopub.execute_input":"2024-06-12T06:35:43.653637Z","iopub.status.idle":"2024-06-12T06:35:44.207431Z","shell.execute_reply.started":"2024-06-12T06:35:43.653607Z","shell.execute_reply":"2024-06-12T06:35:44.206494Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create a function to reduce memory usage\ndef reduce_mem_usage(df):\n    \n    start_mem = df.memory_usage().sum() / 1024**2\n    print('Memory usage of dataframe is {:.2f} MB'.format(start_mem))\n\n    for col in df.columns:\n        col_type = df[col].dtype.name\n\n        if col_type not in ['object', 'category', 'datetime64[ns, UTC]']:\n            c_min = df[col].min()\n            c_max = df[col].max()\n            if str(col_type)[:3] == 'int':\n                if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max:\n                    df[col] = df[col].astype(np.int16)\n                elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max:\n                    df[col] = df[col].astype(np.int16)\n                elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max:\n                    df[col] = df[col].astype(np.int32)\n                elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max:\n                    df[col] = df[col].astype(np.int64)\n            else:\n                if c_min > np.finfo(np.float16).min and c_max < np.finfo(np.float16).max:\n                    df[col] = df[col].astype(np.float16)\n                elif c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max:\n                    df[col] = df[col].astype(np.float32)\n                else:\n                    df[col] = df[col].astype(np.float64)\n\n    end_mem = df.memory_usage().sum() / 1024**2\n    print('Memory usage after optimization is: {:.2f} MB'.format(end_mem))\n   \n    return df ","metadata":{"execution":{"iopub.status.busy":"2024-06-12T06:35:58.700574Z","iopub.execute_input":"2024-06-12T06:35:58.701591Z","iopub.status.idle":"2024-06-12T06:35:58.714008Z","shell.execute_reply.started":"2024-06-12T06:35:58.701547Z","shell.execute_reply":"2024-06-12T06:35:58.712871Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\n\n# Apply the above function to our dataset\nfull_data = reduce_mem_usage(full_data)","metadata":{"execution":{"iopub.status.busy":"2024-06-12T06:36:05.770175Z","iopub.execute_input":"2024-06-12T06:36:05.770922Z","iopub.status.idle":"2024-06-12T06:36:06.305437Z","shell.execute_reply.started":"2024-06-12T06:36:05.770886Z","shell.execute_reply":"2024-06-12T06:36:06.304493Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"full_data = full_data.merge(full_metadata, on='Id', how='inner').fillna(-1) \\\n                        .merge(subjects_data[['Subject', 'Age','Sex', 'YearsSinceDx', 'UPDRSIII_On', 'UPDRSIII_Off', 'NFOGQ']],\n                                       on='Subject', how='left').fillna(-1)","metadata":{"execution":{"iopub.status.busy":"2024-06-12T06:36:08.751907Z","iopub.execute_input":"2024-06-12T06:36:08.752271Z","iopub.status.idle":"2024-06-12T06:36:35.014739Z","shell.execute_reply.started":"2024-06-12T06:36:08.752244Z","shell.execute_reply":"2024-06-12T06:36:35.013638Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"full_data","metadata":{"execution":{"iopub.status.busy":"2024-06-12T06:36:58.371749Z","iopub.execute_input":"2024-06-12T06:36:58.372566Z","iopub.status.idle":"2024-06-12T06:36:58.400434Z","shell.execute_reply.started":"2024-06-12T06:36:58.372532Z","shell.execute_reply":"2024-06-12T06:36:58.399494Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"full_data[full_data.dataset == 'tdcsfog'].index[0]","metadata":{"execution":{"iopub.status.busy":"2024-06-12T06:37:15.771817Z","iopub.execute_input":"2024-06-12T06:37:15.772735Z","iopub.status.idle":"2024-06-12T06:37:18.867787Z","shell.execute_reply.started":"2024-06-12T06:37:15.772701Z","shell.execute_reply":"2024-06-12T06:37:18.866832Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"full_data[full_data.dataset == 'defog'].index[0]","metadata":{"execution":{"iopub.status.busy":"2024-06-12T06:37:22.663161Z","iopub.execute_input":"2024-06-12T06:37:22.663518Z","iopub.status.idle":"2024-06-12T06:37:25.751481Z","shell.execute_reply.started":"2024-06-12T06:37:22.663490Z","shell.execute_reply":"2024-06-12T06:37:25.750578Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"full_data_sample = pd.concat([full_data[:500_000], full_data[7_062_672:7_562_672]])\n# Reset the index to match the number of rows\nfull_data_sample.reset_index(drop=True, inplace=True)\nfull_data_sample","metadata":{"execution":{"iopub.status.busy":"2024-06-12T06:37:32.335677Z","iopub.execute_input":"2024-06-12T06:37:32.336336Z","iopub.status.idle":"2024-06-12T06:37:32.427393Z","shell.execute_reply.started":"2024-06-12T06:37:32.336306Z","shell.execute_reply":"2024-06-12T06:37:32.426513Z"},"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)\nfull_data_sample['Sex'] = np.where(full_data_sample['Sex'] == 'M', 0, 1)\n\n# Step 4: Scale numerical data using StandardScaler\nscaler = StandardScaler()  # To standardize the numerical columns\nencoder= OneHotEncoder()#To standadize the categorical 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', encoder)]), categorical_cols)  # Categorical data: Impute then one-hot encode\n    ],\n    remainder='drop'  # Drop any other columns not specified\n)\n\n\npreprocessor.fit(full_data_sample)\n\n","metadata":{"execution":{"iopub.status.busy":"2024-06-12T06:37:50.935617Z","iopub.execute_input":"2024-06-12T06:37:50.936229Z","iopub.status.idle":"2024-06-12T06:37:55.507611Z","shell.execute_reply.started":"2024-06-12T06:37:50.936199Z","shell.execute_reply":"2024-06-12T06:37:55.506638Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Step 6: Apply preprocessing pipeline to the DataFrame\n# This will apply the transformations defined in 'preprocessor' to 'full_data_sample'\npreprocessed_data = preprocessor.transform(full_data_sample)\n\n# Step 7: Print the preprocessed data\nprint(\"Preprocessed Data:\")\npreprocessed_data# This shows the transformed data (likely as a numpy array)","metadata":{"execution":{"iopub.status.busy":"2024-06-12T06:37:59.733925Z","iopub.execute_input":"2024-06-12T06:37:59.734735Z","iopub.status.idle":"2024-06-12T06:38:02.659167Z","shell.execute_reply.started":"2024-06-12T06:37:59.734695Z","shell.execute_reply":"2024-06-12T06:38:02.658155Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"full_data_sample","metadata":{"execution":{"iopub.status.busy":"2024-06-12T06:38:07.455068Z","iopub.execute_input":"2024-06-12T06:38:07.455399Z","iopub.status.idle":"2024-06-12T06:38:07.482367Z","shell.execute_reply.started":"2024-06-12T06:38:07.455373Z","shell.execute_reply":"2024-06-12T06:38:07.481342Z"},"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    for acc in acc_cols:\n        \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        for lag in [1,2,3]:\n            \n            df[f'ma_{lag}_{acc}'] = df[acc].rolling(lag).mean().bfill()\n            \n            \n    return df","metadata":{"execution":{"iopub.status.busy":"2024-06-12T06:38:18.047696Z","iopub.execute_input":"2024-06-12T06:38:18.048539Z","iopub.status.idle":"2024-06-12T06:38:18.059989Z","shell.execute_reply.started":"2024-06-12T06:38:18.048497Z","shell.execute_reply":"2024-06-12T06:38:18.058847Z"},"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-06-12T06:38:30.361925Z","iopub.execute_input":"2024-06-12T06:38:30.362613Z","iopub.status.idle":"2024-06-12T06:38:33.380412Z","shell.execute_reply.started":"2024-06-12T06:38:30.362580Z","shell.execute_reply":"2024-06-12T06:38:33.379313Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"full_data_sample.info()","metadata":{"execution":{"iopub.status.busy":"2024-06-12T06:39:21.794004Z","iopub.execute_input":"2024-06-12T06:39:21.794646Z","iopub.status.idle":"2024-06-12T06:39:22.281011Z","shell.execute_reply.started":"2024-06-12T06:39:21.794612Z","shell.execute_reply":"2024-06-12T06:39:22.280068Z"},"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-06-12T06:39:29.989883Z","iopub.execute_input":"2024-06-12T06:39:29.990243Z","iopub.status.idle":"2024-06-12T06:39:30.010186Z","shell.execute_reply.started":"2024-06-12T06:39:29.990214Z","shell.execute_reply":"2024-06-12T06:39:30.009484Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Assign variables with predictors and target\nX = full_data_sample.drop(['Id','Subject', 'dataset', 'StartHesitation', 'Turn', 'Walking', 'Test','Visit',\n   'Medication',  'Age' , 'Sex', 'YearsSinceDx', 'UPDRSIII_On' ,'UPDRSIII_Off' ,'NFOGQ', 'Time','AccV','AccML','AccAP' ], axis=1).copy()\ny = X.pop('target')","metadata":{"execution":{"iopub.status.busy":"2024-06-12T06:39:34.021318Z","iopub.execute_input":"2024-06-12T06:39:34.021969Z","iopub.status.idle":"2024-06-12T06:39:34.311009Z","shell.execute_reply.started":"2024-06-12T06:39:34.021936Z","shell.execute_reply":"2024-06-12T06:39:34.310189Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X","metadata":{"execution":{"iopub.status.busy":"2024-06-12T06:38:53.121862Z","iopub.execute_input":"2024-06-12T06:38:53.122434Z","iopub.status.idle":"2024-06-12T06:38:53.317366Z","shell.execute_reply.started":"2024-06-12T06:38:53.122403Z","shell.execute_reply":"2024-06-12T06:38:53.316390Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y","metadata":{"execution":{"iopub.status.busy":"2024-06-12T06:38:59.259050Z","iopub.execute_input":"2024-06-12T06:38:59.259843Z","iopub.status.idle":"2024-06-12T06:38:59.266897Z","shell.execute_reply.started":"2024-06-12T06:38:59.259810Z","shell.execute_reply":"2024-06-12T06:38:59.265846Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Check the missing values in our X dataset\nX.isna().sum()[X.isna().sum() > 0]","metadata":{"execution":{"iopub.status.busy":"2024-06-12T06:39:46.598977Z","iopub.execute_input":"2024-06-12T06:39:46.599341Z","iopub.status.idle":"2024-06-12T06:39:46.768612Z","shell.execute_reply.started":"2024-06-12T06:39:46.599312Z","shell.execute_reply":"2024-06-12T06:39:46.767776Z"},"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-06-12T06:39:49.000030Z","iopub.execute_input":"2024-06-12T06:39:49.000360Z","iopub.status.idle":"2024-06-12T06:43:53.161887Z","shell.execute_reply.started":"2024-06-12T06:39:49.000335Z","shell.execute_reply":"2024-06-12T06:43:53.161054Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Show all features with the  MI score\nmi_scores.to_frame().head(3)","metadata":{"execution":{"iopub.status.busy":"2024-06-12T06:44:09.465682Z","iopub.execute_input":"2024-06-12T06:44:09.466025Z","iopub.status.idle":"2024-06-12T06:44:09.477315Z","shell.execute_reply.started":"2024-06-12T06:44:09.465999Z","shell.execute_reply":"2024-06-12T06:44:09.476421Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Select features with MI score >= 0.28\nselected_features = mi_scores[mi_scores >= 0.28]\nprint(selected_features)","metadata":{"execution":{"iopub.status.busy":"2024-06-12T06:44:16.478150Z","iopub.execute_input":"2024-06-12T06:44:16.478506Z","iopub.status.idle":"2024-06-12T06:44:16.485187Z","shell.execute_reply.started":"2024-06-12T06:44:16.478477Z","shell.execute_reply":"2024-06-12T06:44:16.484206Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"n_top_features = 21\ntop_features = mi_scores.head(n_top_features).index.tolist()\n\n# Add Time, AccV, AccML, and AccAP columns to the list\ntop_features += ['Time', 'AccV', 'AccML', 'AccAP']\n\n# Remove any duplicates and ensure the list doesn't exceed the desired number of features\ntop_features = list(set(top_features))[:(n_top_features + 4)]\n\nfiltered_df = full_data_sample[top_features]  # Keep only the specified features from full_data_sample","metadata":{"execution":{"iopub.status.busy":"2024-06-12T06:44:27.197696Z","iopub.execute_input":"2024-06-12T06:44:27.198289Z","iopub.status.idle":"2024-06-12T06:44:27.267197Z","shell.execute_reply.started":"2024-06-12T06:44:27.198256Z","shell.execute_reply":"2024-06-12T06:44:27.266430Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"filtered_df","metadata":{"execution":{"iopub.status.busy":"2024-06-12T06:44:29.952363Z","iopub.execute_input":"2024-06-12T06:44:29.953073Z","iopub.status.idle":"2024-06-12T06:44:30.147395Z","shell.execute_reply.started":"2024-06-12T06:44:29.953038Z","shell.execute_reply":"2024-06-12T06:44:30.146511Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y.value_counts()","metadata":{"execution":{"iopub.status.busy":"2024-06-04T15:21:18.472027Z","iopub.execute_input":"2024-06-04T15:21:18.472307Z","iopub.status.idle":"2024-06-04T15:21:18.593771Z","shell.execute_reply.started":"2024-06-04T15:21:18.472281Z","shell.execute_reply":"2024-06-04T15:21:18.592713Z"},"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-06-04T15:21:18.594996Z","iopub.execute_input":"2024-06-04T15:21:18.595311Z","iopub.status.idle":"2024-06-04T15:22:42.659947Z","shell.execute_reply.started":"2024-06-04T15:21:18.595275Z","shell.execute_reply":"2024-06-04T15:22:42.658769Z"},"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","metadata":{"execution":{"iopub.status.busy":"2024-06-04T15:22:42.661151Z","iopub.execute_input":"2024-06-04T15:22:42.661467Z","iopub.status.idle":"2024-06-04T15:22:49.636999Z","shell.execute_reply.started":"2024-06-04T15:22:42.661439Z","shell.execute_reply":"2024-06-04T15:22:49.635976Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_train.shape","metadata":{"execution":{"iopub.status.busy":"2024-06-04T15:22:49.638249Z","iopub.execute_input":"2024-06-04T15:22:49.638550Z","iopub.status.idle":"2024-06-04T15:22:49.644367Z","shell.execute_reply.started":"2024-06-04T15:22:49.638525Z","shell.execute_reply":"2024-06-04T15:22:49.643482Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":" y_train.shape","metadata":{"execution":{"iopub.status.busy":"2024-06-04T15:22:49.645462Z","iopub.execute_input":"2024-06-04T15:22:49.645738Z","iopub.status.idle":"2024-06-04T15:22:49.656800Z","shell.execute_reply.started":"2024-06-04T15:22:49.645715Z","shell.execute_reply":"2024-06-04T15:22:49.655960Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_test.shape","metadata":{"execution":{"iopub.status.busy":"2024-06-04T15:22:49.657858Z","iopub.execute_input":"2024-06-04T15:22:49.658971Z","iopub.status.idle":"2024-06-04T15:22:49.669707Z","shell.execute_reply.started":"2024-06-04T15:22:49.658929Z","shell.execute_reply":"2024-06-04T15:22:49.668857Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_test.shape","metadata":{"execution":{"iopub.status.busy":"2024-06-04T15:22:49.671111Z","iopub.execute_input":"2024-06-04T15:22:49.671431Z","iopub.status.idle":"2024-06-04T15:22:49.679039Z","shell.execute_reply.started":"2024-06-04T15:22:49.671402Z","shell.execute_reply":"2024-06-04T15:22:49.678154Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_test.value_counts()","metadata":{"execution":{"iopub.status.busy":"2024-06-04T15:22:49.680096Z","iopub.execute_input":"2024-06-04T15:22:49.680374Z","iopub.status.idle":"2024-06-04T15:22:49.811244Z","shell.execute_reply.started":"2024-06-04T15:22:49.680352Z","shell.execute_reply":"2024-06-04T15:22:49.810348Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"lgbm_clf = lgb.LGBMClassifier( \n    num_class=4,\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-06-04T15:22:49.812734Z","iopub.execute_input":"2024-06-04T15:22:49.812985Z","iopub.status.idle":"2024-06-04T15:25:14.467906Z","shell.execute_reply.started":"2024-06-04T15:22:49.812964Z","shell.execute_reply":"2024-06-04T15:25:14.466998Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Make predictions on the testing set\ny_pred = lgbm_clf.predict(X_test)\n\n\naccuracy = accuracy_score(y_test, y_pred)\nprecision = precision_score(y_test, y_pred, average='weighted')\nrecall = recall_score(y_test, y_pred, average='weighted')\nf1 = f1_score(y_test, y_pred, average='weighted')\n\nprint(\" Accuracy: \", accuracy , \"\\n\") \nprint(\"Precision:\", precision ,\"\\n\" )\nprint(\"Recall:\", recall, \"\\n\")\nprint(\"F1-score:\", f1, \"\\n\")","metadata":{"execution":{"iopub.status.busy":"2024-06-04T15:25:14.469334Z","iopub.execute_input":"2024-06-04T15:25:14.469926Z","iopub.status.idle":"2024-06-04T15:25:58.842377Z","shell.execute_reply.started":"2024-06-04T15:25:14.469895Z","shell.execute_reply":"2024-06-04T15:25:58.841439Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\" Classification Report: \\n\", classification_report(y_test, y_pred, digits =2))","metadata":{"execution":{"iopub.status.busy":"2024-06-04T15:25:58.843628Z","iopub.execute_input":"2024-06-04T15:25:58.844264Z","iopub.status.idle":"2024-06-04T15:26:51.590814Z","shell.execute_reply.started":"2024-06-04T15:25:58.844228Z","shell.execute_reply":"2024-06-04T15:26:51.589887Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\" Confusion Matrix: \\n\", confusion_matrix(y_test, y_pred))","metadata":{"execution":{"iopub.status.busy":"2024-06-04T15:26:51.591947Z","iopub.execute_input":"2024-06-04T15:26:51.592234Z","iopub.status.idle":"2024-06-04T15:26:57.594974Z","shell.execute_reply.started":"2024-06-04T15:26:51.592208Z","shell.execute_reply":"2024-06-04T15:26:57.594078Z"},"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-06-04T15:26:57.596072Z","iopub.execute_input":"2024-06-04T15:26:57.596356Z","iopub.status.idle":"2024-06-04T15:27:03.931319Z","shell.execute_reply.started":"2024-06-04T15:26:57.596331Z","shell.execute_reply":"2024-06-04T15:27:03.930385Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Make predictions on the testing set\ny_pred_proba = lgbm_clf.predict_proba(X_test)","metadata":{"execution":{"iopub.status.busy":"2024-06-04T15:27:03.932610Z","iopub.execute_input":"2024-06-04T15:27:03.932926Z","iopub.status.idle":"2024-06-04T15:27:11.700985Z","shell.execute_reply.started":"2024-06-04T15:27:03.932893Z","shell.execute_reply":"2024-06-04T15:27:11.699944Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create a DataFrame with the predicted probabilities\ndf = pd.DataFrame(y_pred_proba, columns=['StartHesitation', 'Turn', 'Walking', 'Normal'])\n\n# Add an ID column to the DataFrame\ndf.insert(0, 'ID', range(1, len(df) + 1))\n","metadata":{"execution":{"iopub.status.busy":"2024-06-04T15:27:11.702281Z","iopub.execute_input":"2024-06-04T15:27:11.702670Z","iopub.status.idle":"2024-06-04T15:27:11.709785Z","shell.execute_reply.started":"2024-06-04T15:27:11.702635Z","shell.execute_reply":"2024-06-04T15:27:11.708834Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nprint(os.getcwd())\nos.makedirs('FOG PD', exist_ok=True)","metadata":{"execution":{"iopub.status.busy":"2024-06-04T15:27:11.711259Z","iopub.execute_input":"2024-06-04T15:27:11.711666Z","iopub.status.idle":"2024-06-04T15:27:11.721058Z","shell.execute_reply.started":"2024-06-04T15:27:11.711633Z","shell.execute_reply":"2024-06-04T15:27:11.720155Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Save the DataFrame as a CSV file with 6 decimal points\ndf.to_csv('predicted_probs.csv', index=False, float_format='%.6f' )","metadata":{"execution":{"iopub.status.busy":"2024-06-04T15:27:11.722116Z","iopub.execute_input":"2024-06-04T15:27:11.722378Z","iopub.status.idle":"2024-06-04T15:27:18.729141Z","shell.execute_reply.started":"2024-06-04T15:27:11.722354Z","shell.execute_reply":"2024-06-04T15:27:18.728362Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Assuming your DataFrame is named 'df'\npd.set_option('display.float_format', lambda x: '%.6f' % x)","metadata":{"execution":{"iopub.status.busy":"2024-06-04T15:27:18.730113Z","iopub.execute_input":"2024-06-04T15:27:18.730370Z","iopub.status.idle":"2024-06-04T15:27:18.734840Z","shell.execute_reply.started":"2024-06-04T15:27:18.730348Z","shell.execute_reply":"2024-06-04T15:27:18.733950Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Print the predictions DataFrame\ndf","metadata":{"execution":{"iopub.status.busy":"2024-06-04T15:27:18.736184Z","iopub.execute_input":"2024-06-04T15:27:18.736537Z","iopub.status.idle":"2024-06-04T15:27:18.751635Z","shell.execute_reply.started":"2024-06-04T15:27:18.736478Z","shell.execute_reply":"2024-06-04T15:27:18.750536Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"mostOccurredEvent = df.iloc[:, 1:].idxmax(axis=1).value_counts().index[0]\nprint(f\"The most occurred event in the majority of the subjects is: {mostOccurredEvent}\")","metadata":{"execution":{"iopub.status.busy":"2024-06-04T15:27:18.752629Z","iopub.execute_input":"2024-06-04T15:27:18.752855Z","iopub.status.idle":"2024-06-04T15:27:18.976880Z","shell.execute_reply.started":"2024-06-04T15:27:18.752835Z","shell.execute_reply":"2024-06-04T15:27:18.975952Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Find the least occurred event in the majority of the subjects\nleastOccurredEvent = df.iloc[:, 1:].idxmax(axis=1).value_counts().index[-1]\nprint(f\"The least occurred event in the majority of the subjects is: {leastOccurredEvent}\")","metadata":{"execution":{"iopub.status.busy":"2024-06-04T15:27:18.977932Z","iopub.execute_input":"2024-06-04T15:27:18.978186Z","iopub.status.idle":"2024-06-04T15:27:19.197735Z","shell.execute_reply.started":"2024-06-04T15:27:18.978164Z","shell.execute_reply":"2024-06-04T15:27:19.196811Z"},"trusted":true},"execution_count":null,"outputs":[]}]}