{"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":"\n## Importing data","metadata":{}},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nfrom itertools import groupby\nfrom sklearn.model_selection import train_test_split\nfrom pandas.api.types import is_datetime64_ns_dtype\n\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.ensemble import GradientBoostingClassifier\nimport lightgbm as lgb\nfrom imblearn.under_sampling import RandomUnderSampler\nfrom joblib import Parallel, delayed\nimport gc\nimport plotly.express as px\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nfrom metric import score # Import event detection ap score function\n\n# These are variables to be used by the score function\ncolumn_names = {\n    'series_id_column_name': 'series_id',\n    'time_column_name': 'step',\n    'event_column_name': 'event',\n    'score_column_name': 'score',\n}\n\ntolerances = {\n    'onset': [12, 36, 60, 90, 120, 150, 180, 240, 300, 360], \n    'wakeup': [12, 36, 60, 90, 120, 150, 180, 240, 300, 360]\n}","metadata":{"execution":{"iopub.status.busy":"2023-10-16T09:22:53.275701Z","iopub.execute_input":"2023-10-16T09:22:53.276125Z","iopub.status.idle":"2023-10-16T09:22:57.502169Z","shell.execute_reply.started":"2023-10-16T09:22:53.276091Z","shell.execute_reply":"2023-10-16T09:22:57.500947Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def reduce_mem_usage(df):\n    \n    \"\"\" \n    Iterate through all numeric columns of a dataframe and modify the data type\n    to reduce memory usage.        \n    \"\"\"\n    \n    for col in df.columns:\n        col_type = df[col].dtype\n\n        if col_type != object and not is_datetime64_ns_dtype(df[col]) and not 'category':\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.int8)\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.int32)  \n            else:\n                df[col] = df[col].astype(np.float16)\n        \n    return df","metadata":{"execution":{"iopub.status.busy":"2023-10-16T09:22:57.504424Z","iopub.execute_input":"2023-10-16T09:22:57.505019Z","iopub.status.idle":"2023-10-16T09:22:57.514975Z","shell.execute_reply.started":"2023-10-16T09:22:57.504992Z","shell.execute_reply":"2023-10-16T09:22:57.513537Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def feat_eng(df):\n    \n    df['series_id'] = df['series_id'].astype('category')\n    df['timestamp'] = pd.to_datetime(df['timestamp']).apply(lambda t: t.tz_localize(None))\n    df['hour'] = df[\"timestamp\"].dt.hour\n    \n    df.sort_values(['timestamp'], inplace=True)\n    df.set_index('timestamp', inplace=True)\n    \n    df['lids'] = np.maximum(0., df['enmo'] - 0.02)\n    df['lids'] = df['lids'].rolling(f'{120*5}s', center=True, min_periods=1).agg('sum')\n    df['lids'] = 100 / (df['lids'] + 1)\n    df['lids'] = df['lids'].rolling(f'{360*5}s', center=True, min_periods=1).agg('mean').astype(np.float32)\n    \n    df[\"enmo\"] = (df[\"enmo\"]*1000).astype(np.int16)\n    df[\"anglez\"] = df[\"anglez\"].astype(np.int16)\n    df[\"anglezdiffabs\"] = df[\"anglez\"].diff().abs().astype(np.float32)\n    \n    for col in ['enmo', 'anglez', 'anglezdiffabs']:\n        \n        # periods in seconds        \n        periods = [60, 360, 720, 3600] \n        \n        for n in periods:\n            \n            rol_args = {'window':f'{n+5}s', 'min_periods':10, 'center':True}\n            \n            for agg in ['median', 'mean', 'max', 'min', 'var']:\n                df[f'{col}_{agg}_{n}'] = df[col].rolling(**rol_args).agg(agg).astype(np.float32).values\n                gc.collect()\n            \n            if n == max(periods):\n                df[f'{col}_mad_{n}'] = (df[col] - df[f'{col}_median_{n}']).abs().rolling(**rol_args).median().astype(np.float32)\n            \n            df[f'{col}_amplit_{n}'] = df[f'{col}_max_{n}']-df[f'{col}_min_{n}']\n            df[f'{col}_amplit_{n}_min'] = df[f'{col}_amplit_{n}'].rolling(**rol_args).min().astype(np.float32).values\n            \n#             if col in ['enmo', 'anglez']:\n            df[f'{col}_diff_{n}_max'] = df[f'{col}_max_{n}'].diff().abs().rolling(**rol_args).max().astype(np.float32)\n            df[f'{col}_diff_{n}_mean'] = df[f'{col}_max_{n}'].diff().abs().rolling(**rol_args).mean().astype(np.float32)\n\n    \n            gc.collect()\n    \n    df.reset_index(inplace=True)\n    df.dropna(inplace=True)\n\n    return df","metadata":{"execution":{"iopub.status.busy":"2023-10-16T09:22:57.517218Z","iopub.execute_input":"2023-10-16T09:22:57.517651Z","iopub.status.idle":"2023-10-16T09:22:57.535349Z","shell.execute_reply.started":"2023-10-16T09:22:57.517613Z","shell.execute_reply":"2023-10-16T09:22:57.534266Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"file = '/kaggle/input/zzzs-lightweight-training-dataset-target/Zzzs_train.parquet'\n\ndef feat_eng_by_id(idx):\n    \n    from warnings import simplefilter \n    simplefilter(action=\"ignore\", category=pd.errors.PerformanceWarning)\n    \n    df  = pd.read_parquet(file, filters=[('series_id','=',idx)])\n    df['awake'] = df['awake'].astype(np.int8)\n    df = feat_eng(df)\n    \n    return df","metadata":{"execution":{"iopub.status.busy":"2023-10-16T09:22:57.537622Z","iopub.execute_input":"2023-10-16T09:22:57.537930Z","iopub.status.idle":"2023-10-16T09:22:57.551909Z","shell.execute_reply.started":"2023-10-16T09:22:57.537905Z","shell.execute_reply":"2023-10-16T09:22:57.550895Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Training and validating ","metadata":{}},{"cell_type":"code","source":"DEV = False\n\nseries_id  = pd.read_parquet(file, columns=['series_id'])\nseries_id = series_id.series_id.unique()\n\nprint(len(series_id))\n\nif DEV:\n    series_id = series_id[::10]","metadata":{"execution":{"iopub.status.busy":"2023-10-16T09:22:57.555821Z","iopub.execute_input":"2023-10-16T09:22:57.556344Z","iopub.status.idle":"2023-10-16T09:22:59.938894Z","shell.execute_reply.started":"2023-10-16T09:22:57.556301Z","shell.execute_reply":"2023-10-16T09:22:59.937821Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"weird_series = ['31011ade7c0a', 'a596ad0b82aa']\n\nseries_id = [s for s in series_id if s not in weird_series]","metadata":{"execution":{"iopub.status.busy":"2023-10-16T09:22:59.940535Z","iopub.execute_input":"2023-10-16T09:22:59.941174Z","iopub.status.idle":"2023-10-16T09:22:59.946722Z","shell.execute_reply.started":"2023-10-16T09:22:59.941142Z","shell.execute_reply":"2023-10-16T09:22:59.945213Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\n\ntrain = Parallel(n_jobs=6)(delayed(feat_eng_by_id)(i) for i in series_id)\ntrain = pd.concat(train, ignore_index=True)","metadata":{"execution":{"iopub.status.busy":"2023-10-16T09:22:59.948373Z","iopub.execute_input":"2023-10-16T09:22:59.948801Z","iopub.status.idle":"2023-10-16T09:26:59.179254Z","shell.execute_reply.started":"2023-10-16T09:22:59.948773Z","shell.execute_reply":"2023-10-16T09:26:59.178185Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# REDUCE train data by half\nstep=360 if DEV else 60\ntrain = train.iloc[::step]\nstep","metadata":{"execution":{"iopub.status.busy":"2023-10-16T09:26:59.180941Z","iopub.execute_input":"2023-10-16T09:26:59.181540Z","iopub.status.idle":"2023-10-16T09:26:59.189645Z","shell.execute_reply.started":"2023-10-16T09:26:59.181510Z","shell.execute_reply":"2023-10-16T09:26:59.188501Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"drop_cols = ['series_id', 'step', 'timestamp']\n\nX, y = train.drop(columns=drop_cols+['awake']), train['awake']\n\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2023-10-16T09:26:59.190864Z","iopub.execute_input":"2023-10-16T09:26:59.191235Z","iopub.status.idle":"2023-10-16T09:26:59.713525Z","shell.execute_reply.started":"2023-10-16T09:26:59.191196Z","shell.execute_reply":"2023-10-16T09:26:59.712345Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"if not DEV:\n    del train\n    gc.collect()","metadata":{"execution":{"iopub.status.busy":"2023-10-16T09:26:59.715030Z","iopub.execute_input":"2023-10-16T09:26:59.715464Z","iopub.status.idle":"2023-10-16T09:26:59.923590Z","shell.execute_reply.started":"2023-10-16T09:26:59.715436Z","shell.execute_reply":"2023-10-16T09:26:59.922064Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Ensemble","metadata":{}},{"cell_type":"code","source":"class EnsembleAvgProba():\n    \n    def __init__(self, classifiers):\n        \n        self.classifiers = classifiers\n    \n    def fit(self,X,y):\n        \n        for classifier in self.classifiers:                \n            classifier.fit(X, y)\n            gc.collect()\n     \n    def predict_proba(self, X):\n        \n        probs = []\n        \n        for m in self.classifiers:\n            probs.append(m.predict_proba(X))\n        \n        probabilities = np.stack(probs)\n        p = np.mean(probabilities, axis=0)\n        \n        return p \n    \n    def predict(self, X):\n        \n        probs = []\n        \n        for m in self.classifiers:\n            probs.append(m.predict(X))\n        \n        probabilities = np.stack(probs)\n        p = np.mean(probabilities, axis=0)\n        \n        return p.round()","metadata":{"execution":{"iopub.status.busy":"2023-10-16T09:26:59.925548Z","iopub.execute_input":"2023-10-16T09:26:59.926001Z","iopub.status.idle":"2023-10-16T09:26:59.938162Z","shell.execute_reply.started":"2023-10-16T09:26:59.925964Z","shell.execute_reply":"2023-10-16T09:26:59.937125Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"##테스트 버전, 기존에 Catboost + ExtraTree\nfrom catboost import CatBoostClassifier\nfrom sklearn.ensemble import ExtraTreesClassifier\nimport xgboost as xgb\n\nlgb_params1 = {    \n    'boosting_type': 'gbdt',\n    'num_leaves': 31,\n    'max_depth': 6,\n    'learning_rate': 0.03,\n    'n_estimators': 850,\n    'subsample_for_bin': 200000,\n    'min_child_weight': 0.001,\n    'min_child_samples': 20,\n    'subsample': 0.9,\n    'colsample_bytree': 0.7,  # Uncommented this line\n    'reg_alpha': 0.05,\n    'reg_lambda': 0.05,\n}\n\nxgb_params = {\n    'n_estimators': 520,\n    'objective': \"binary:logistic\",\n    'learning_rate': 0.02,\n    'max_depth': 7,\n    'subsample': 0.9,\n    'colsample_bytree': 0.7,\n    'random_state': 42\n}\n\ncat_params = {\n    'iterations': 600,\n    'learning_rate': 0.03,\n    'depth': 6,\n    'random_state': 42,\n    'verbose': 0  # to prevent training output, remove or set to a larger value to see training progress\n}\n\nmodel = EnsembleAvgProba(classifiers=[\n    lgb.LGBMClassifier(random_state=42, **lgb_params1),\n    GradientBoostingClassifier(n_estimators=100, max_depth=5, min_samples_leaf=300, random_state=42),\n    RandomForestClassifier(n_estimators=500, min_samples_leaf=300, random_state=42, n_jobs=-1),\n    xgb.XGBClassifier(**xgb_params),\n    CatBoostClassifier(**cat_params),\n    ExtraTreesClassifier(n_estimators=500, min_samples_leaf=300, random_state=42, n_jobs=-1)\n])\n\n\n\n# lgb_params1 = {    \n#     'boosting_type':'gbdt',\n#     'num_leaves':31,\n#     'max_depth':6,\n#     'learning_rate':0.03,\n#     'n_estimators':850,\n#     'subsample_for_bin':200000,\n#     'min_child_weight':0.001,\n#     'min_child_samples':20,\n#     'subsample':0.9,\n# #     'colsample_bytree':0.7,\n#     'reg_alpha':0.05,\n#     'reg_lambda':0.05,\n#              }\n# import xgboost as xgb\n\n\n# # Training classifier\n\n# model = EnsembleAvgProba(classifiers=[\n#                     lgb.LGBMClassifier(random_state=42, **lgb_params1),\n#                     GradientBoostingClassifier(n_estimators=100,max_depth=5,min_samples_leaf=300,random_state=42),\n#                     RandomForestClassifier(n_estimators=500, min_samples_leaf=300, random_state=42, n_jobs=-1),\n#                     xgb.XGBClassifier(n_estimators=520,objective=\"binary:logistic\", learning_rate=0.02, max_depth=7, random_state=42)    ]\n#                 )","metadata":{"execution":{"iopub.status.busy":"2023-10-16T09:26:59.939901Z","iopub.execute_input":"2023-10-16T09:26:59.940286Z","iopub.status.idle":"2023-10-16T09:27:00.479038Z","shell.execute_reply.started":"2023-10-16T09:26:59.940258Z","shell.execute_reply":"2023-10-16T09:27:00.477865Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\n\nmodel.fit(X, y)","metadata":{"execution":{"iopub.status.busy":"2023-10-16T09:27:00.480540Z","iopub.execute_input":"2023-10-16T09:27:00.480873Z","iopub.status.idle":"2023-10-16T10:16:59.721245Z","shell.execute_reply.started":"2023-10-16T09:27:00.480847Z","shell.execute_reply":"2023-10-16T10:16:59.719870Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Plot feature importance","metadata":{}},{"cell_type":"code","source":"feats = []\n\nfeat_imp = model.classifiers[0].booster_.feature_importance(importance_type='gain')\nfeat_imp = pd.Series(model.classifiers[0].feature_importances_, index=X.columns).sort_values()\nfeats.append(feat_imp)\n\nfor m in model.classifiers[1:]:\n    feat_imp = pd.Series(m.feature_importances_, index=X.columns).sort_values()\n    feats.append(feat_imp)","metadata":{"execution":{"iopub.status.busy":"2023-10-16T10:16:59.724515Z","iopub.execute_input":"2023-10-16T10:16:59.724851Z","iopub.status.idle":"2023-10-16T10:16:59.785915Z","shell.execute_reply.started":"2023-10-16T10:16:59.724824Z","shell.execute_reply":"2023-10-16T10:16:59.784828Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"feat_imp = pd.Series(pd.concat(feats, axis=1).mean(axis=1), index=feats[0].index).sort_values()\nprint('Columns with poor contribution', feat_imp[feat_imp<0.001].index, sep='\\n')\nfig = px.bar(x=feat_imp, y=feat_imp.index, orientation='h')\nfig.show()","metadata":{"execution":{"iopub.status.busy":"2023-10-16T10:16:59.787124Z","iopub.execute_input":"2023-10-16T10:16:59.787421Z","iopub.status.idle":"2023-10-16T10:17:01.727506Z","shell.execute_reply.started":"2023-10-16T10:16:59.787397Z","shell.execute_reply":"2023-10-16T10:17:01.726097Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"feat_imp.sort_values().head(10)","metadata":{"execution":{"iopub.status.busy":"2023-10-16T10:17:01.728757Z","iopub.execute_input":"2023-10-16T10:17:01.729435Z","iopub.status.idle":"2023-10-16T10:17:01.746676Z","shell.execute_reply.started":"2023-10-16T10:17:01.729406Z","shell.execute_reply":"2023-10-16T10:17:01.738678Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# del X, y\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2023-10-16T10:17:01.749141Z","iopub.execute_input":"2023-10-16T10:17:01.750114Z","iopub.status.idle":"2023-10-16T10:17:01.919682Z","shell.execute_reply.started":"2023-10-16T10:17:01.750073Z","shell.execute_reply":"2023-10-16T10:17:01.918384Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Inference","metadata":{}},{"cell_type":"code","source":"def get_events(idx, classifier, file='test_series.parquet') :\n    \n    test  = pd.read_parquet(f'/kaggle/input/child-mind-institute-detect-sleep-states/{file}',\n                    filters=[('series_id','=',idx)])\n    test = feat_eng(test)\n    X_test = test.drop(columns=drop_cols)\n    test = test[drop_cols]\n\n    preds, probs = classifier.predict(X_test), classifier.predict_proba(X_test)[:, 1]\n    \n    test['prediction'] = preds\n    test['prediction'] = test['prediction'].rolling(360+1, center=True).median()\n    test['probability'] = probs\n    \n    test = test[test['prediction']!=2]\n    \n    test.loc[test['prediction']==0, 'probability'] = 1-test.loc[test['prediction']==0, 'probability']\n    test['score'] = test['probability'].rolling(60*12*5, center=True, min_periods=10).mean().bfill().ffill()\n\n    \n    test['pred_diff'] = test['prediction'].diff()\n    \n    test['event'] = test['pred_diff'].replace({1:'wakeup', -1:'onset', 0:np.nan})\n    \n    test_wakeup = test[test['event']=='wakeup'].groupby(test['timestamp'].dt.date).agg('first')\n    test_onset = test[test['event']=='onset'].groupby(test['timestamp'].dt.date).agg('last')\n    test = pd.concat([test_wakeup, test_onset], ignore_index=True).sort_values('timestamp')\n\n    return test","metadata":{"execution":{"iopub.status.busy":"2023-10-16T10:17:01.920951Z","iopub.execute_input":"2023-10-16T10:17:01.924499Z","iopub.status.idle":"2023-10-16T10:17:01.934883Z","shell.execute_reply.started":"2023-10-16T10:17:01.924463Z","shell.execute_reply":"2023-10-16T10:17:01.933352Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cols_sub = ['series_id','step','event','score']\n\nseries_id  = pd.read_parquet('/kaggle/input/child-mind-institute-detect-sleep-states/test_series.parquet', columns=['series_id'])\nseries_id = series_id.series_id.unique()\n\ntests = []\n\nfor idx in series_id: \n\n    test = get_events(idx, model)\n    tests.append(test[cols_sub])","metadata":{"execution":{"iopub.status.busy":"2023-10-16T10:17:01.936561Z","iopub.execute_input":"2023-10-16T10:17:01.937056Z","iopub.status.idle":"2023-10-16T10:17:37.657215Z","shell.execute_reply.started":"2023-10-16T10:17:01.937014Z","shell.execute_reply":"2023-10-16T10:17:37.655819Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Submit","metadata":{}},{"cell_type":"code","source":"submission = pd.concat(tests, ignore_index=True).reset_index(names='row_id')\nsubmission.to_csv('submission.csv', index=False)\nsubmission","metadata":{"execution":{"iopub.status.busy":"2023-10-16T10:17:37.659089Z","iopub.execute_input":"2023-10-16T10:17:37.659683Z","iopub.status.idle":"2023-10-16T10:17:37.689407Z","shell.execute_reply.started":"2023-10-16T10:17:37.659633Z","shell.execute_reply":"2023-10-16T10:17:37.688153Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}