{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# time-series 🤝 tsflex 🚀","metadata":{}},{"cell_type":"markdown","source":"### **Thanks to great works from JEROENVDD.**\n\n### improvements\n\n1. add metadata infomation and subject infomation, fix a little bug of subject feature in JEROENVDD‘s origin notebook\n2. make GroupKfold Cross Validation\n3. version11:drop task feature, because it is unavailable in hidden test set\n\n#### reference\n\n* @JEROENVDD\n    * Origin notebook link https://www.kaggle.com/code/jeroenvdd/time-series-tsflex\n    \n<br>","metadata":{}},{"cell_type":"markdown","source":"<div style=\"background-color:#f2f2f2; padding:20px; border-radius: 10px;\">\n    <h2 style=\"color:#595959;\">Check out <a href=\"https://github.com/predict-idlab/tsflex\" target=\"_blank\" style=\"color:#0099cc;\">tsflex</a>!</h2>\n    <h4 style=\"color:#737373;\">tsflex is a Python package for flexible and efficient time series feature extraction. It's great for data preprocessing and feature engineering for time series data. Check it out on <a href=\"https://github.com/predict-idlab/tsflex\" target=\"_blank\" style=\"color:#0099cc;\">GitHub</a> today!</h4>\n    \n<p style=\"color:#737373;\">This notebook is a fork of the <a href=\"https://www.kaggle.com/code/jazivxt/familiar-solvs\" target=\"_blank\" style=\"color:#0099cc;\">familiar-solvs notebook of jazivxt</a> and adds tsflex to extract some basic <a href=\"https://github.com/dmbee/seglearn\" target=\"_blank\" style=\"color:#0099cc;\">seglearn</a> features.</p>\n    \n</div>","metadata":{}},{"cell_type":"code","source":"# Install tsflex and seglearn\n!pip install tsflex --no-index --find-links=file:///kaggle/input/time-series-tools\n!pip install seglearn --no-index --find-links=file:///kaggle/input/time-series-tools","metadata":{"execution":{"iopub.status.busy":"2023-03-19T13:24:04.180093Z","iopub.execute_input":"2023-03-19T13:24:04.180582Z","iopub.status.idle":"2023-03-19T13:24:25.293013Z","shell.execute_reply.started":"2023-03-19T13:24:04.180547Z","shell.execute_reply":"2023-03-19T13:24:25.291126Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nfrom tqdm.auto import tqdm\nfrom sklearn import *\nimport glob\n\np = '/kaggle/input/tlvmc-parkinsons-freezing-gait-prediction/'\n\ntrain = glob.glob(p+'train/**/**')\ntest = glob.glob(p+'test/**/**')\nsubjects = pd.read_csv(p+'subjects.csv')\ntasks = pd.read_csv(p+'tasks.csv')\nsub = pd.read_csv(p+'sample_submission.csv')\n\ntdcsfog_metadata=pd.read_csv('/kaggle/input/tlvmc-parkinsons-freezing-gait-prediction/tdcsfog_metadata.csv')\ndefog_metadata=pd.read_csv('/kaggle/input/tlvmc-parkinsons-freezing-gait-prediction/defog_metadata.csv')\n# daily_metadata=pd.read_csv('/kaggle/input/tlvmc-parkinsons-freezing-gait-prediction/daily_metadata.csv')\ntdcsfog_metadata['Module']='tdcsfog'\ndefog_metadata['Module']='defog'\n# daily_metadata['Module']='daily'\nmetadata=pd.concat([tdcsfog_metadata,defog_metadata])\nmetadata","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-03-19T13:24:25.295107Z","iopub.execute_input":"2023-03-19T13:24:25.296531Z","iopub.status.idle":"2023-03-19T13:24:27.077514Z","shell.execute_reply.started":"2023-03-19T13:24:25.296437Z","shell.execute_reply":"2023-03-19T13:24:27.075567Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# https://www.kaggle.com/code/jazivxt/familiar-solvs\n# tasks['Duration'] = tasks['End'] - tasks['Begin']\n# tasks = pd.pivot_table(tasks, values=['Duration'], index=['Id'], columns=['Task'], aggfunc='sum', fill_value=0)\n# tasks.columns = [c[-1] for c in tasks.columns]\n# tasks = tasks.reset_index()\n# tasks['t_kmeans'] = cluster.KMeans(n_clusters=10, random_state=3).fit_predict(tasks[tasks.columns[1:]])\n\nsubjects = subjects.fillna(0).groupby('Subject').median()\nsubjects = subjects.reset_index()\n# subjects.rename(columns={'Subject':'Id'}, inplace=True)\nsubjects['s_kmeans'] = cluster.KMeans(n_clusters=10, random_state=3).fit_predict(subjects[subjects.columns[1:]])\nsubjects=subjects.rename(columns={'Visit':'s_Visit','Age':'s_Age','YearsSinceDx':'s_YearsSinceDx','UPDRSIII_On':'s_UPDRSIII_On','UPDRSIII_Off':'s_UPDRSIII_Off','NFOGQ':'s_NFOGQ'})\n\n# display(tasks)\ndisplay(subjects)","metadata":{"execution":{"iopub.status.busy":"2023-03-19T13:24:27.079271Z","iopub.execute_input":"2023-03-19T13:24:27.079633Z","iopub.status.idle":"2023-03-19T13:24:27.233834Z","shell.execute_reply.started":"2023-03-19T13:24:27.079606Z","shell.execute_reply":"2023-03-19T13:24:27.232887Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"complex_featlist=['Visit','Test','Medication','s_Visit','s_Age','s_YearsSinceDx','s_UPDRSIII_On','s_UPDRSIII_Off','s_NFOGQ','s_kmeans']\nmetadata_complex=metadata.merge(subjects,how='left',on='Subject').copy()\nmetadata_complex['Medication']=metadata_complex['Medication'].factorize()[0]\n\ndisplay(metadata_complex)","metadata":{"execution":{"iopub.status.busy":"2023-03-19T13:24:27.234981Z","iopub.execute_input":"2023-03-19T13:24:27.235302Z","iopub.status.idle":"2023-03-19T13:24:27.268658Z","shell.execute_reply.started":"2023-03-19T13:24:27.235268Z","shell.execute_reply":"2023-03-19T13:24:27.267508Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Create a tsflex feature collection","metadata":{}},{"cell_type":"code","source":"from seglearn.feature_functions import base_features, emg_features\n\nfrom tsflex.features import FeatureCollection, MultipleFeatureDescriptors\nfrom tsflex.features.integrations import seglearn_feature_dict_wrapper\n\n\nbasic_feats = MultipleFeatureDescriptors(\n    functions=seglearn_feature_dict_wrapper(base_features()),\n    series_names=['AccV', 'AccML', 'AccAP'],\n    windows=[5_000],\n    strides=[5_000],\n)\n\nemg_feats = emg_features()\ndel emg_feats['simple square integral'] # is same as abs_energy (which is in base_features)\n\nemg_feats = MultipleFeatureDescriptors(\n    functions=seglearn_feature_dict_wrapper(emg_feats),\n    series_names=['AccV', 'AccML', 'AccAP'],\n    windows=[5_000],\n    strides=[5_000],\n)\n\nfc = FeatureCollection([basic_feats, emg_feats])","metadata":{"execution":{"iopub.status.busy":"2023-03-19T13:24:27.270863Z","iopub.execute_input":"2023-03-19T13:24:27.271161Z","iopub.status.idle":"2023-03-19T13:24:27.324133Z","shell.execute_reply.started":"2023-03-19T13:24:27.271134Z","shell.execute_reply":"2023-03-19T13:24:27.322683Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Extract the features","metadata":{}},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pathlib\ndef reader(f):\n    try:\n        df = pd.read_csv(f, index_col=\"Time\", usecols=['Time', 'AccV', 'AccML', 'AccAP', 'StartHesitation', 'Turn' , 'Walking'])\n        df['Id'] = f.split('/')[-1].split('.')[0]\n        df['Module'] = pathlib.Path(f).parts[-2]\n#         df = pd.merge(df, tasks[['Id','t_kmeans']], how='left', on='Id').fillna(-1)\n#         df = pd.merge(df, subjects[['Id','s_kmeans']], how='left', on='Id').fillna(-1)\n        df = pd.merge(df, metadata_complex[['Id','Subject']+['Visit','Test','Medication','s_kmeans']], how='left', on='Id').fillna(-1)\n        df_feats = fc.calculate(df, return_df=True, include_final_window=True, approve_sparsity=True, window_idx=\"begin\").astype(np.float32)\n        df = df.merge(df_feats, how=\"left\", left_index=True, right_index=True)\n        df.fillna(method=\"ffill\", inplace=True)\n        return df\n    except: pass\ntrain = pd.concat([reader(f) for f in tqdm(train)]).fillna(0); print(train.shape)\ncols = [c for c in train.columns if c not in ['Id','Subject','Module', 'Time', 'StartHesitation', 'Turn' , 'Walking', 'Valid', 'Task','Event']]\npcols = ['StartHesitation', 'Turn' , 'Walking']\nscols = ['Id', 'StartHesitation', 'Turn' , 'Walking']","metadata":{"execution":{"iopub.status.busy":"2023-03-19T13:24:27.325359Z","iopub.execute_input":"2023-03-19T13:24:27.325864Z","iopub.status.idle":"2023-03-19T13:31:21.926516Z","shell.execute_reply.started":"2023-03-19T13:24:27.325835Z","shell.execute_reply":"2023-03-19T13:31:21.924826Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train=train.reset_index(drop=True)","metadata":{"execution":{"iopub.status.busy":"2023-03-19T13:31:21.928904Z","iopub.execute_input":"2023-03-19T13:31:21.929227Z","iopub.status.idle":"2023-03-19T13:31:24.561045Z","shell.execute_reply.started":"2023-03-19T13:31:21.929200Z","shell.execute_reply":"2023-03-19T13:31:24.559644Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Train the model","metadata":{}},{"cell_type":"code","source":"from sklearn.model_selection import GroupKFold\n\nN_FOLDS=5\nkfold = GroupKFold(N_FOLDS)\ngroup_var = train.Subject\ngroups=kfold.split(train, groups=group_var)\nregs=[]\ncvs=[]\nfor fold, (tr_idx,te_idx ) in enumerate(tqdm(groups, total=N_FOLDS, desc=\"Folds\")):\n    tr_idx=pd.Series(tr_idx).sample(n=2000000,random_state=100).values\n    reg = ensemble.ExtraTreesRegressor(n_estimators=100, max_depth=7, n_jobs=-1, random_state=3)\n    x_tr,y_tr=train.loc[tr_idx,cols],train.loc[tr_idx,pcols]\n    x_te,y_te=train.loc[te_idx,cols],train.loc[te_idx,pcols]\n    reg.fit(x_tr,y_tr)\n    regs.append(reg)\n    cv=metrics.average_precision_score(y_te, reg.predict(x_te).clip(0.0,1.0))\n    cvs.append(cv)\nprint(cvs)","metadata":{"execution":{"iopub.status.busy":"2023-03-19T13:31:24.562790Z","iopub.execute_input":"2023-03-19T13:31:24.563325Z","iopub.status.idle":"2023-03-19T13:56:37.698468Z","shell.execute_reply.started":"2023-03-19T13:31:24.563285Z","shell.execute_reply":"2023-03-19T13:56:37.696230Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"raw","source":"# This should be some proper cross validation..\nx1, x2, y1, y2 = model_selection.train_test_split(train[cols], train[pcols], test_size=.10, random_state=3, stratify=train[pcols])\nreg = ensemble.ExtraTreesRegressor(n_estimators=100, max_depth=7, n_jobs=-1, random_state=3)\nreg.fit(x2,y2)\nprint(metrics.average_precision_score(y1[:1_000_000], reg.predict(x1[:1_000_000]).clip(0.0,1.0)))","metadata":{"execution":{"iopub.status.busy":"2023-03-19T10:22:30.727744Z","iopub.execute_input":"2023-03-19T10:22:30.729220Z","iopub.status.idle":"2023-03-19T10:36:24.571591Z","shell.execute_reply.started":"2023-03-19T10:22:30.729165Z","shell.execute_reply":"2023-03-19T10:36:24.569535Z"}}},{"cell_type":"markdown","source":"## Predict for test","metadata":{}},{"cell_type":"code","source":"sub['t'] = 0\nsubmission = []\nfor f in test:\n    df = pd.read_csv(f)\n    df.set_index('Time', drop=True, inplace=True)\n    df['Id'] = f.split('/')[-1].split('.')[0]\n#     df = df.fillna(0).reset_index(drop=True)\n#     df = pd.merge(df, tasks[['Id','t_kmeans']], how='left', on='Id').fillna(-1)\n#     df = pd.merge(df, subjects[['Id','s_kmeans']], how='left', on='Id').fillna(-1)\n    df = pd.merge(df, metadata_complex[['Id','Subject']+['Visit','Test','Medication','s_kmeans']], how='left', on='Id').fillna(-1)\n    df_feats = fc.calculate(df, return_df=True, include_final_window=True, approve_sparsity=True, window_idx=\"begin\")\n    df = df.merge(df_feats, how=\"left\", left_index=True, right_index=True)\n    df.fillna(method=\"ffill\", inplace=True)\n#     res = pd.DataFrame(np.round(reg.predict(df[cols]).clip(0.0,1.0),3), columns=pcols)\n    \n    res_vals=[]\n    for i_fold in range(N_FOLDS):\n        res_val=np.round(regs[i_fold].predict(df[cols]).clip(0.0,1.0),3)\n        res_vals.append(np.expand_dims(res_val,axis=2))\n    res_vals=np.mean(np.concatenate(res_vals,axis=2),axis=2)\n    res = pd.DataFrame(res_vals, columns=pcols)\n    \n    df = pd.concat([df,res], axis=1)\n    df['Id'] = df['Id'].astype(str) + '_' + df.index.astype(str)\n    submission.append(df[scols])\nsubmission = pd.concat(submission)\nsubmission = pd.merge(sub[['Id','t']], submission, how='left', on='Id').fillna(0.0)\nsubmission[scols].to_csv('submission.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2023-03-19T13:56:37.700706Z","iopub.execute_input":"2023-03-19T13:56:37.701100Z","iopub.status.idle":"2023-03-19T13:56:44.303184Z","shell.execute_reply.started":"2023-03-19T13:56:37.701071Z","shell.execute_reply":"2023-03-19T13:56:44.300987Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}