{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import numpy as np \nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport polars as pl\nimport datetime \nfrom tqdm import tqdm\n\nimport plotly.express as px\nfrom plotly.subplots import make_subplots\nimport plotly.graph_objects as go\nimport gc\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":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-10-27T02:12:11.21672Z","iopub.execute_input":"2023-10-27T02:12:11.217604Z","iopub.status.idle":"2023-10-27T02:12:12.539734Z","shell.execute_reply.started":"2023-10-27T02:12:11.217553Z","shell.execute_reply":"2023-10-27T02:12:12.538896Z"},"trusted":true},"execution_count":1,"outputs":[]},{"cell_type":"markdown","source":"\n## Importing data","metadata":{}},{"cell_type":"code","source":"# Importing data \n\n# Column transformations\n\ndt_transforms = [\n    pl.col('timestamp').str.to_datetime(), \n    (pl.col('timestamp').str.to_datetime().dt.year()-2000).cast(pl.UInt8).alias('year'), \n    pl.col('timestamp').str.to_datetime().dt.month().cast(pl.UInt8).alias('month'),\n    pl.col('timestamp').str.to_datetime().dt.day().cast(pl.UInt8).alias('day'), \n    pl.col('timestamp').str.to_datetime().dt.hour().cast(pl.UInt8).alias('hour')\n]\n\ndata_transforms = [\n    pl.col('anglez').cast(pl.Int16), # Casting anglez to 16 bit integer\n    (pl.col('enmo')*1000).cast(pl.UInt16), # Convert enmo to 16 bit uint\n]\n\ntrain_series = pl.scan_parquet('/kaggle/input/child-mind-institute-detect-sleep-states/train_series.parquet').with_columns(\n    dt_transforms + data_transforms\n    )\n\ntrain_events = pl.read_csv('/kaggle/input/child-mind-institute-detect-sleep-states/train_events.csv').with_columns(\n    dt_transforms\n    ).drop_nulls()\n\ntest_series = pl.scan_parquet('/kaggle/input/child-mind-institute-detect-sleep-states/test_series.parquet').with_columns(\n    dt_transforms + data_transforms\n    )\n\n# Removing null events and nights with mismatched counts from series_events\nmismatches = train_events.drop_nulls().group_by(['series_id', 'night']).agg([\n    ((pl.col('event') == 'onset').sum() == (pl.col('event') == 'wakeup').sum()).alias('balanced')\n    ]).sort(by=['series_id', 'night']).filter(~pl.col('balanced'))\n\nfor mm in mismatches.to_numpy(): \n    train_events = train_events.filter(~((pl.col('series_id') == mm[0]) & (pl.col('night') == mm[1])))\n\n\n# Getting series ids as a list for convenience\nseries_ids = train_events['series_id'].unique(maintain_order=True).to_list()\n\n# Updating train_series to only keep these series ids\ntrain_series = train_series.filter(pl.col('series_id').is_in(series_ids))","metadata":{"execution":{"iopub.status.busy":"2023-10-27T02:12:12.541168Z","iopub.execute_input":"2023-10-27T02:12:12.542309Z","iopub.status.idle":"2023-10-27T02:12:12.921226Z","shell.execute_reply.started":"2023-10-27T02:12:12.542276Z","shell.execute_reply":"2023-10-27T02:12:12.920306Z"},"trusted":true},"execution_count":2,"outputs":[]},{"cell_type":"markdown","source":"## Feature Engineering\n\nThe features in this model will consist of\n- The current`hour`.\n- Rolling aggregates (mean, max, std) of `anglez` and `enmo` over a variety of window sizes, from 5 minutes to 8 hours. \n- Rolling aggregates (mean, max, std) of `anglez` and `enmo` [**total variation**](https://en.wikipedia.org/wiki/Total_variation) (or *first variation*, i.e. 1v) over a variety of window sizes, from 5 minutes to 8 hours.\n\n#### Motivation for using total variation \n\nFrom my earlier [Data Exploration](https://www.kaggle.com/code/lccburk/sleep-data-exploration) we observe that during sleeping periods `anglez` resembles a pure [jump process](https://en.wikipedia.org/wiki/Jump_process), while during wakeful periods it resembles a [diffusion process](https://en.wikipedia.org/wiki/Diffusion_process), as shown in the following data sample:\n\n<img src=\"https://media.licdn.com/dms/image/D5612AQHondzoUGc1tA/article-inline_image-shrink_1000_1488/0/1695767830342?e=1701907200&v=beta&t=3Zf5RuZpGNGHUyAl7g-B7J9ftZaQrGPze4l1XegKkpU\" width=\"800\" />\n\nImportantly, jump and diffusion processes can be distinguished by what is known as their [**total variation**](https://en.wikipedia.org/wiki/Total_variation) - essentially, the sum total of the absolute differences between the points. For diffusion processes, which jiggle around constantly, the total variation is infinite, while for jump processes, which only change by finite amounts a countable number of times, the total variation is finite.\n\n<img src=\"https://media.licdn.com/dms/image/D5612AQGNsJtKsGREyQ/article-inline_image-shrink_1500_2232/0/1696293678614?e=1701907200&v=beta&t=iTZutqlUHm7pvv-d1pKAHoAYO5Va9Z_1Tjjee3B4dgg\" width=\"650\" />\n\nFor non-continuous, evenly sampled functions such as our time series, the total variation of a function $f(t)$ on an interval $[a,b]$ can be defined simply as\n\n$$V_a^b(f) := \\sum_{j=0}^{n-1} |f(t_{j+1}) - f(t_j)|$$\n\nwhere $t_0=a$, $t_n=b$, and $\\forall j: t_{j+1}-t_j = \\frac{a-b}{n}$. This can be calculated efficiently using Polars' built in `.diff()` and `.abs()` functions. \n\nThese features will give the classification model information which characterizes the stochastic behavior of the variable in the recent past, which can be much more useful for classifying sleep state than the variable value itself.","metadata":{}},{"cell_type":"code","source":"features, feature_cols = [pl.col('hour')], ['hour']\n\nfor mins in [5, 30, 60*2, 60*8] :\n    features += [\n        pl.col('enmo').rolling_mean(12 * mins, center=True, min_periods=1).abs().cast(pl.UInt16).alias(f'enmo_{mins}m_mean'),\n        pl.col('enmo').rolling_max(12 * mins, center=True, min_periods=1).abs().cast(pl.UInt16).alias(f'enmo_{mins}m_max'),\n        pl.col('enmo').rolling_std(12 * mins, center=True, min_periods=1).abs().cast(pl.UInt16).alias(f'enmo_{mins}m_std')\n    ]\n\n    feature_cols += [ \n        f'enmo_{mins}m_mean', f'enmo_{mins}m_max', f'enmo_{mins}m_std'\n    ]\n    \n\n    # Getting first variations\n    for var in ['enmo', 'anglez'] :\n        features += [\n            (pl.col(var).diff().abs().rolling_mean(12 * mins, center=True, min_periods=1)*10).abs().cast(pl.UInt32).alias(f'{var}_1v_{mins}m_mean'),\n            (pl.col(var).diff().abs().rolling_max(12 * mins, center=True, min_periods=1)*10).abs().cast(pl.UInt32).alias(f'{var}_1v_{mins}m_max'),\n            (pl.col(var).diff().abs().rolling_std(12 * mins, center=True, min_periods=1)*10).abs().cast(pl.UInt32).alias(f'{var}_1v_{mins}m_std')\n        ]\n\n        feature_cols += [ \n            f'{var}_1v_{mins}m_mean', f'{var}_1v_{mins}m_max', f'{var}_1v_{mins}m_std'\n        ]\n\nid_cols = ['series_id', 'step', 'timestamp']\n\ntrain_series = train_series.with_columns(\n    features\n).select(id_cols + feature_cols)\n\ntest_series = test_series.with_columns(\n    features\n).select(id_cols + feature_cols)","metadata":{"execution":{"iopub.status.busy":"2023-10-27T02:12:12.922837Z","iopub.execute_input":"2023-10-27T02:12:12.923156Z","iopub.status.idle":"2023-10-27T02:12:12.936721Z","shell.execute_reply.started":"2023-10-27T02:12:12.923129Z","shell.execute_reply":"2023-10-27T02:12:12.935815Z"},"trusted":true},"execution_count":3,"outputs":[]},{"cell_type":"code","source":"def make_train_dataset(train_data, train_events, drop_nulls=False) :\n    \n    series_ids = train_data['series_id'].unique(maintain_order=True).to_list()\n    X, y = pl.DataFrame(), pl.DataFrame()\n    for idx in tqdm(series_ids) : \n        \n        # Normalizing sample features\n        sample = train_data.filter(pl.col('series_id')==idx).with_columns(\n            [(pl.col(col) / pl.col(col).std()).cast(pl.Float32) for col in feature_cols if col != 'hour']\n        )\n        \n        events = train_events.filter(pl.col('series_id')==idx)\n        \n        if drop_nulls : \n            # Removing datapoints on dates where no data was recorded\n            sample = sample.filter(\n                pl.col('timestamp').dt.date().is_in(events['timestamp'].dt.date())\n            )\n        \n        X = X.vstack(sample[id_cols + feature_cols])\n\n        onsets = events.filter((pl.col('event') == 'onset') & (pl.col('step') != None))['step'].to_list()\n        wakeups = events.filter((pl.col('event') == 'wakeup') & (pl.col('step') != None))['step'].to_list()\n\n        # NOTE: This will break if there are event series without any recorded onsets or wakeups\n        y = y.vstack(sample.with_columns(\n            sum([(onset <= pl.col('step')) & (pl.col('step') <= wakeup) for onset, wakeup in zip(onsets, wakeups)]).cast(pl.Boolean).alias('asleep')\n            ).select('asleep')\n            )\n    \n    y = y.to_numpy().ravel()\n    \n    return X, y","metadata":{"execution":{"iopub.status.busy":"2023-10-27T02:12:12.938883Z","iopub.execute_input":"2023-10-27T02:12:12.939432Z","iopub.status.idle":"2023-10-27T02:12:12.953656Z","shell.execute_reply.started":"2023-10-27T02:12:12.9394Z","shell.execute_reply":"2023-10-27T02:12:12.952729Z"},"trusted":true},"execution_count":4,"outputs":[]},{"cell_type":"code","source":"def get_events(series, classifier) :\n    '''\n    Takes a time series and a classifier and returns a formatted submission dataframe.\n    '''\n    \n    series_ids = series['series_id'].unique(maintain_order=True).to_list()\n    events = pl.DataFrame(schema={'series_id':str, 'step':int, 'event':str, 'score':float})\n\n    for idx in tqdm(series_ids) : \n\n        # Collecting sample and normalizing features\n        scale_cols = [col for col in feature_cols if (col != 'hour') & (series[col].std() !=0)]\n        X = series.filter(pl.col('series_id') == idx).select(id_cols + feature_cols).with_columns(\n            [(pl.col(col) / series[col].std()).cast(pl.Float32) for col in scale_cols]\n        )\n\n        # Applying classifier to get predictions and scores\n        preds, probs = classifier.predict(X[feature_cols]), classifier.predict_proba(X[feature_cols])[:, 1]\n\n        #NOTE: Considered using rolling max to get sleep periods excluding <30 min interruptions, but ended up decreasing performance\n        X = X.with_columns(\n            pl.lit(preds).cast(pl.Int8).alias('prediction'), \n            pl.lit(probs).alias('probability')\n                        )\n        \n        # Getting predicted onset and wakeup time steps\n        pred_onsets = X.filter(X['prediction'].diff() > 0)['step'].to_list()\n        pred_wakeups = X.filter(X['prediction'].diff() < 0)['step'].to_list()\n        \n        if len(pred_onsets) > 0 : \n            \n            # Ensuring all predicted sleep periods begin and end\n            if min(pred_wakeups) < min(pred_onsets) : \n                pred_wakeups = pred_wakeups[1:]\n\n            if max(pred_onsets) > max(pred_wakeups) :\n                pred_onsets = pred_onsets[:-1]\n\n            # Keeping sleep periods longer than 30 minutes\n            sleep_periods = [(onset, wakeup) for onset, wakeup in zip(pred_onsets, pred_wakeups) if wakeup - onset >= 12 * 30]\n\n            for onset, wakeup in sleep_periods :\n                # Scoring using mean probability over period\n                score = X.filter((pl.col('step') >= onset) & (pl.col('step') <= wakeup))['probability'].mean()\n\n                # Adding sleep event to dataframe\n                events = events.vstack(pl.DataFrame().with_columns(\n                    pl.Series([idx, idx]).alias('series_id'), \n                    pl.Series([onset, wakeup]).alias('step'),\n                    pl.Series(['onset', 'wakeup']).alias('event'),\n                    pl.Series([score, score]).alias('score')\n                ))\n\n    # Adding row id column\n    events = events.to_pandas().reset_index().rename(columns={'index':'row_id'})\n\n    return events","metadata":{"execution":{"iopub.status.busy":"2023-10-27T02:12:12.955046Z","iopub.execute_input":"2023-10-27T02:12:12.955658Z","iopub.status.idle":"2023-10-27T02:12:12.971307Z","shell.execute_reply.started":"2023-10-27T02:12:12.95562Z","shell.execute_reply":"2023-10-27T02:12:12.970194Z"},"trusted":true},"execution_count":5,"outputs":[]},{"cell_type":"markdown","source":"## Training Models","metadata":{}},{"cell_type":"code","source":"'''\nfrom sklearn.model_selection import train_test_split\n\ntrain_ids, val_ids = train_test_split(series_ids, train_size=0.7, random_state=42)\n\n# We will collect datapoints at 10 minute intervals for training for validating\ntrain_data = train_series.filter(pl.col('series_id').is_in(train_ids)).take_every(12 * 10).collect()\n\nval_data = train_series.filter(pl.col('series_id').is_in(val_ids)).collect()\nval_solution = train_events.filter(pl.col('series_id').is_in(val_ids)).select(['series_id', 'event', 'step']).to_pandas()\n'''\n# Collecting datapoints at every 5 minutes\ntrain_data = train_series.filter(pl.col('series_id').is_in(series_ids)).take_every(12 * 5).collect()\n","metadata":{"execution":{"iopub.status.busy":"2023-10-27T02:12:12.972677Z","iopub.execute_input":"2023-10-27T02:12:12.973071Z","iopub.status.idle":"2023-10-27T02:15:21.557957Z","shell.execute_reply.started":"2023-10-27T02:12:12.973036Z","shell.execute_reply":"2023-10-27T02:15:21.556702Z"},"trusted":true},"execution_count":6,"outputs":[]},{"cell_type":"code","source":"train_data.head(10)","metadata":{"execution":{"iopub.status.busy":"2023-10-27T02:15:21.559368Z","iopub.execute_input":"2023-10-27T02:15:21.559696Z","iopub.status.idle":"2023-10-27T02:15:21.578777Z","shell.execute_reply.started":"2023-10-27T02:15:21.559668Z","shell.execute_reply":"2023-10-27T02:15:21.577607Z"},"trusted":true},"execution_count":7,"outputs":[{"execution_count":7,"output_type":"execute_result","data":{"text/plain":"shape: (10, 40)\n┌─────────────┬──────┬─────────────┬──────┬───┬─────────────┬────────────┬────────────┬────────────┐\n│ series_id   ┆ step ┆ timestamp   ┆ hour ┆ … ┆ enmo_1v_480 ┆ anglez_1v_ ┆ anglez_1v_ ┆ anglez_1v_ │\n│ ---         ┆ ---  ┆ ---         ┆ ---  ┆   ┆ m_std       ┆ 480m_mean  ┆ 480m_max   ┆ 480m_std   │\n│ str         ┆ u32  ┆ datetime[μs ┆ u8   ┆   ┆ ---         ┆ ---        ┆ ---        ┆ ---        │\n│             ┆      ┆ , UTC]      ┆      ┆   ┆ u32         ┆ u32        ┆ u32        ┆ u32        │\n╞═════════════╪══════╪═════════════╪══════╪═══╪═════════════╪════════════╪════════════╪════════════╡\n│ 038441c925b ┆ 0    ┆ 2018-08-14  ┆ 19   ┆ … ┆ 825         ┆ 101        ┆ 1040       ┆ 137        │\n│ b           ┆      ┆ 19:30:00    ┆      ┆   ┆             ┆            ┆            ┆            │\n│             ┆      ┆ UTC         ┆      ┆   ┆             ┆            ┆            ┆            │\n│ 038441c925b ┆ 60   ┆ 2018-08-14  ┆ 19   ┆ … ┆ 817         ┆ 102        ┆ 1040       ┆ 140        │\n│ b           ┆      ┆ 19:35:00    ┆      ┆   ┆             ┆            ┆            ┆            │\n│             ┆      ┆ UTC         ┆      ┆   ┆             ┆            ┆            ┆            │\n│ 038441c925b ┆ 120  ┆ 2018-08-14  ┆ 19   ┆ … ┆ 810         ┆ 101        ┆ 1040       ┆ 139        │\n│ b           ┆      ┆ 19:40:00    ┆      ┆   ┆             ┆            ┆            ┆            │\n│             ┆      ┆ UTC         ┆      ┆   ┆             ┆            ┆            ┆            │\n│ 038441c925b ┆ 180  ┆ 2018-08-14  ┆ 19   ┆ … ┆ 803         ┆ 99         ┆ 1040       ┆ 139        │\n│ b           ┆      ┆ 19:45:00    ┆      ┆   ┆             ┆            ┆            ┆            │\n│             ┆      ┆ UTC         ┆      ┆   ┆             ┆            ┆            ┆            │\n│ …           ┆ …    ┆ …           ┆ …    ┆ … ┆ …           ┆ …          ┆ …          ┆ …          │\n│ 038441c925b ┆ 360  ┆ 2018-08-14  ┆ 20   ┆ … ┆ 784         ┆ 95         ┆ 1040       ┆ 136        │\n│ b           ┆      ┆ 20:00:00    ┆      ┆   ┆             ┆            ┆            ┆            │\n│             ┆      ┆ UTC         ┆      ┆   ┆             ┆            ┆            ┆            │\n│ 038441c925b ┆ 420  ┆ 2018-08-14  ┆ 20   ┆ … ┆ 778         ┆ 93         ┆ 1040       ┆ 135        │\n│ b           ┆      ┆ 20:05:00    ┆      ┆   ┆             ┆            ┆            ┆            │\n│             ┆      ┆ UTC         ┆      ┆   ┆             ┆            ┆            ┆            │\n│ 038441c925b ┆ 480  ┆ 2018-08-14  ┆ 20   ┆ … ┆ 772         ┆ 92         ┆ 1040       ┆ 134        │\n│ b           ┆      ┆ 20:10:00    ┆      ┆   ┆             ┆            ┆            ┆            │\n│             ┆      ┆ UTC         ┆      ┆   ┆             ┆            ┆            ┆            │\n│ 038441c925b ┆ 540  ┆ 2018-08-14  ┆ 20   ┆ … ┆ 766         ┆ 91         ┆ 1040       ┆ 134        │\n│ b           ┆      ┆ 20:15:00    ┆      ┆   ┆             ┆            ┆            ┆            │\n│             ┆      ┆ UTC         ┆      ┆   ┆             ┆            ┆            ┆            │\n└─────────────┴──────┴─────────────┴──────┴───┴─────────────┴────────────┴────────────┴────────────┘","text/html":"<div><style>\n.dataframe > thead > tr > th,\n.dataframe > tbody > tr > td {\n  text-align: right;\n  white-space: pre-wrap;\n}\n</style>\n<small>shape: (10, 40)</small><table border=\"1\" class=\"dataframe\"><thead><tr><th>series_id</th><th>step</th><th>timestamp</th><th>hour</th><th>enmo_5m_mean</th><th>enmo_5m_max</th><th>enmo_5m_std</th><th>enmo_1v_5m_mean</th><th>enmo_1v_5m_max</th><th>enmo_1v_5m_std</th><th>anglez_1v_5m_mean</th><th>anglez_1v_5m_max</th><th>anglez_1v_5m_std</th><th>enmo_30m_mean</th><th>enmo_30m_max</th><th>enmo_30m_std</th><th>enmo_1v_30m_mean</th><th>enmo_1v_30m_max</th><th>enmo_1v_30m_std</th><th>anglez_1v_30m_mean</th><th>anglez_1v_30m_max</th><th>anglez_1v_30m_std</th><th>enmo_120m_mean</th><th>enmo_120m_max</th><th>enmo_120m_std</th><th>enmo_1v_120m_mean</th><th>enmo_1v_120m_max</th><th>enmo_1v_120m_std</th><th>anglez_1v_120m_mean</th><th>anglez_1v_120m_max</th><th>anglez_1v_120m_std</th><th>enmo_480m_mean</th><th>enmo_480m_max</th><th>enmo_480m_std</th><th>enmo_1v_480m_mean</th><th>enmo_1v_480m_max</th><th>enmo_1v_480m_std</th><th>anglez_1v_480m_mean</th><th>anglez_1v_480m_max</th><th>anglez_1v_480m_std</th></tr><tr><td>str</td><td>u32</td><td>datetime[μs, UTC]</td><td>u8</td><td>u16</td><td>u16</td><td>u16</td><td>u32</td><td>u32</td><td>u32</td><td>u32</td><td>u32</td><td>u32</td><td>u16</td><td>u16</td><td>u16</td><td>u32</td><td>u32</td><td>u32</td><td>u32</td><td>u32</td><td>u32</td><td>u16</td><td>u16</td><td>u16</td><td>u32</td><td>u32</td><td>u32</td><td>u32</td><td>u32</td><td>u32</td><td>u16</td><td>u16</td><td>u16</td><td>u32</td><td>u32</td><td>u32</td><td>u32</td><td>u32</td><td>u32</td></tr></thead><tbody><tr><td>&quot;038441c925bb&quot;</td><td>0</td><td>2018-08-14 19:30:00 UTC</td><td>19</td><td>20</td><td>69</td><td>10</td><td>68</td><td>580</td><td>151</td><td>81</td><td>730</td><td>173</td><td>14</td><td>69</td><td>5</td><td>13</td><td>580</td><td>65</td><td>14</td><td>730</td><td>75</td><td>19</td><td>440</td><td>25</td><td>59</td><td>4180</td><td>269</td><td>30</td><td>880</td><td>106</td><td>75</td><td>1223</td><td>104</td><td>375</td><td>11420</td><td>825</td><td>101</td><td>1040</td><td>137</td></tr><tr><td>&quot;038441c925bb&quot;</td><td>60</td><td>2018-08-14 19:35:00 UTC</td><td>19</td><td>13</td><td>14</td><td>0</td><td>2</td><td>10</td><td>4</td><td>2</td><td>10</td><td>4</td><td>14</td><td>69</td><td>5</td><td>14</td><td>580</td><td>65</td><td>13</td><td>730</td><td>69</td><td>23</td><td>550</td><td>36</td><td>86</td><td>4650</td><td>337</td><td>38</td><td>890</td><td>115</td><td>74</td><td>1223</td><td>103</td><td>372</td><td>11420</td><td>817</td><td>102</td><td>1040</td><td>140</td></tr><tr><td>&quot;038441c925bb&quot;</td><td>120</td><td>2018-08-14 19:40:00 UTC</td><td>19</td><td>12</td><td>13</td><td>0</td><td>3</td><td>10</td><td>4</td><td>1</td><td>10</td><td>3</td><td>14</td><td>69</td><td>5</td><td>15</td><td>580</td><td>63</td><td>11</td><td>730</td><td>62</td><td>26</td><td>550</td><td>40</td><td>111</td><td>4650</td><td>368</td><td>48</td><td>890</td><td>123</td><td>74</td><td>1223</td><td>103</td><td>368</td><td>11420</td><td>810</td><td>101</td><td>1040</td><td>139</td></tr><tr><td>&quot;038441c925bb&quot;</td><td>180</td><td>2018-08-14 19:45:00 UTC</td><td>19</td><td>13</td><td>14</td><td>0</td><td>2</td><td>10</td><td>4</td><td>1</td><td>30</td><td>4</td><td>14</td><td>69</td><td>5</td><td>15</td><td>580</td><td>61</td><td>9</td><td>730</td><td>56</td><td>40</td><td>1184</td><td>92</td><td>178</td><td>8250</td><td>598</td><td>53</td><td>890</td><td>125</td><td>72</td><td>1223</td><td>102</td><td>362</td><td>11420</td><td>803</td><td>99</td><td>1040</td><td>139</td></tr><tr><td>&quot;038441c925bb&quot;</td><td>240</td><td>2018-08-14 19:50:00 UTC</td><td>19</td><td>15</td><td>56</td><td>6</td><td>21</td><td>430</td><td>68</td><td>10</td><td>310</td><td>48</td><td>13</td><td>56</td><td>3</td><td>10</td><td>430</td><td>40</td><td>2</td><td>310</td><td>20</td><td>47</td><td>1223</td><td>105</td><td>222</td><td>11420</td><td>768</td><td>57</td><td>890</td><td>127</td><td>71</td><td>1223</td><td>101</td><td>356</td><td>11420</td><td>796</td><td>98</td><td>1040</td><td>138</td></tr><tr><td>&quot;038441c925bb&quot;</td><td>300</td><td>2018-08-14 19:55:00 UTC</td><td>19</td><td>15</td><td>47</td><td>6</td><td>23</td><td>330</td><td>69</td><td>0</td><td>20</td><td>3</td><td>14</td><td>56</td><td>4</td><td>13</td><td>430</td><td>50</td><td>2</td><td>310</td><td>20</td><td>56</td><td>1223</td><td>115</td><td>266</td><td>11420</td><td>821</td><td>62</td><td>890</td><td>128</td><td>70</td><td>1223</td><td>101</td><td>350</td><td>11420</td><td>790</td><td>96</td><td>1040</td><td>137</td></tr><tr><td>&quot;038441c925bb&quot;</td><td>360</td><td>2018-08-14 20:00:00 UTC</td><td>20</td><td>13</td><td>20</td><td>1</td><td>9</td><td>60</td><td>11</td><td>1</td><td>10</td><td>3</td><td>15</td><td>78</td><td>6</td><td>21</td><td>540</td><td>73</td><td>8</td><td>880</td><td>61</td><td>56</td><td>1223</td><td>112</td><td>260</td><td>11420</td><td>799</td><td>62</td><td>890</td><td>126</td><td>69</td><td>1223</td><td>100</td><td>345</td><td>11420</td><td>784</td><td>95</td><td>1040</td><td>136</td></tr><tr><td>&quot;038441c925bb&quot;</td><td>420</td><td>2018-08-14 20:05:00 UTC</td><td>20</td><td>15</td><td>55</td><td>5</td><td>19</td><td>420</td><td>74</td><td>1</td><td>10</td><td>3</td><td>15</td><td>78</td><td>6</td><td>19</td><td>540</td><td>67</td><td>6</td><td>880</td><td>58</td><td>58</td><td>1223</td><td>109</td><td>256</td><td>11420</td><td>779</td><td>63</td><td>890</td><td>123</td><td>68</td><td>1223</td><td>99</td><td>339</td><td>11420</td><td>778</td><td>93</td><td>1040</td><td>135</td></tr><tr><td>&quot;038441c925bb&quot;</td><td>480</td><td>2018-08-14 20:10:00 UTC</td><td>20</td><td>16</td><td>78</td><td>10</td><td>26</td><td>540</td><td>97</td><td>29</td><td>880</td><td>137</td><td>18</td><td>123</td><td>14</td><td>37</td><td>830</td><td>105</td><td>26</td><td>880</td><td>104</td><td>60</td><td>1223</td><td>112</td><td>278</td><td>11420</td><td>832</td><td>66</td><td>890</td><td>124</td><td>67</td><td>1223</td><td>99</td><td>334</td><td>11420</td><td>772</td><td>92</td><td>1040</td><td>134</td></tr><tr><td>&quot;038441c925bb&quot;</td><td>540</td><td>2018-08-14 20:15:00 UTC</td><td>20</td><td>16</td><td>68</td><td>7</td><td>29</td><td>530</td><td>87</td><td>8</td><td>200</td><td>34</td><td>24</td><td>440</td><td>34</td><td>103</td><td>4180</td><td>371</td><td>51</td><td>880</td><td>136</td><td>61</td><td>1223</td><td>111</td><td>298</td><td>11420</td><td>847</td><td>69</td><td>890</td><td>125</td><td>66</td><td>1223</td><td>98</td><td>329</td><td>11420</td><td>766</td><td>91</td><td>1040</td><td>134</td></tr></tbody></table></div>"},"metadata":{}}]},{"cell_type":"code","source":"train_data.shape","metadata":{"execution":{"iopub.status.busy":"2023-10-27T02:15:21.580162Z","iopub.execute_input":"2023-10-27T02:15:21.580586Z","iopub.status.idle":"2023-10-27T02:15:21.594588Z","shell.execute_reply.started":"2023-10-27T02:15:21.58055Z","shell.execute_reply":"2023-10-27T02:15:21.593746Z"},"trusted":true},"execution_count":8,"outputs":[{"execution_count":8,"output_type":"execute_result","data":{"text/plain":"(2080368, 40)"},"metadata":{}}]},{"cell_type":"code","source":"# Creating train dataset\nX_train, y_train = make_train_dataset(train_data, train_events)","metadata":{"execution":{"iopub.status.busy":"2023-10-27T02:15:21.596169Z","iopub.execute_input":"2023-10-27T02:15:21.596836Z","iopub.status.idle":"2023-10-27T02:15:29.319248Z","shell.execute_reply.started":"2023-10-27T02:15:21.596789Z","shell.execute_reply":"2023-10-27T02:15:29.318033Z"},"trusted":true},"execution_count":9,"outputs":[{"name":"stderr","text":"100%|██████████| 269/269 [00:07<00:00, 35.10it/s]\n","output_type":"stream"}]},{"cell_type":"code","source":"X_train.head()","metadata":{"execution":{"iopub.status.busy":"2023-10-27T02:15:29.323827Z","iopub.execute_input":"2023-10-27T02:15:29.324181Z","iopub.status.idle":"2023-10-27T02:15:29.336383Z","shell.execute_reply.started":"2023-10-27T02:15:29.324153Z","shell.execute_reply":"2023-10-27T02:15:29.334947Z"},"trusted":true},"execution_count":10,"outputs":[{"execution_count":10,"output_type":"execute_result","data":{"text/plain":"shape: (5, 40)\n┌─────────────┬──────┬─────────────┬──────┬───┬─────────────┬────────────┬────────────┬────────────┐\n│ series_id   ┆ step ┆ timestamp   ┆ hour ┆ … ┆ enmo_1v_480 ┆ anglez_1v_ ┆ anglez_1v_ ┆ anglez_1v_ │\n│ ---         ┆ ---  ┆ ---         ┆ ---  ┆   ┆ m_std       ┆ 480m_mean  ┆ 480m_max   ┆ 480m_std   │\n│ str         ┆ u32  ┆ datetime[μs ┆ u8   ┆   ┆ ---         ┆ ---        ┆ ---        ┆ ---        │\n│             ┆      ┆ , UTC]      ┆      ┆   ┆ f32         ┆ f32        ┆ f32        ┆ f32        │\n╞═════════════╪══════╪═════════════╪══════╪═══╪═════════════╪════════════╪════════════╪════════════╡\n│ 038441c925b ┆ 0    ┆ 2018-08-14  ┆ 19   ┆ … ┆ 2.138996    ┆ 3.048498   ┆ 2.878486   ┆ 3.754352   │\n│ b           ┆      ┆ 19:30:00    ┆      ┆   ┆             ┆            ┆            ┆            │\n│             ┆      ┆ UTC         ┆      ┆   ┆             ┆            ┆            ┆            │\n│ 038441c925b ┆ 60   ┆ 2018-08-14  ┆ 19   ┆ … ┆ 2.118255    ┆ 3.078681   ┆ 2.878486   ┆ 3.836564   │\n│ b           ┆      ┆ 19:35:00    ┆      ┆   ┆             ┆            ┆            ┆            │\n│             ┆      ┆ UTC         ┆      ┆   ┆             ┆            ┆            ┆            │\n│ 038441c925b ┆ 120  ┆ 2018-08-14  ┆ 19   ┆ … ┆ 2.100106    ┆ 3.048498   ┆ 2.878486   ┆ 3.80916    │\n│ b           ┆      ┆ 19:40:00    ┆      ┆   ┆             ┆            ┆            ┆            │\n│             ┆      ┆ UTC         ┆      ┆   ┆             ┆            ┆            ┆            │\n│ 038441c925b ┆ 180  ┆ 2018-08-14  ┆ 19   ┆ … ┆ 2.081956    ┆ 2.988132   ┆ 2.878486   ┆ 3.80916    │\n│ b           ┆      ┆ 19:45:00    ┆      ┆   ┆             ┆            ┆            ┆            │\n│             ┆      ┆ UTC         ┆      ┆   ┆             ┆            ┆            ┆            │\n│ 038441c925b ┆ 240  ┆ 2018-08-14  ┆ 19   ┆ … ┆ 2.063807    ┆ 2.957948   ┆ 2.878486   ┆ 3.781756   │\n│ b           ┆      ┆ 19:50:00    ┆      ┆   ┆             ┆            ┆            ┆            │\n│             ┆      ┆ UTC         ┆      ┆   ┆             ┆            ┆            ┆            │\n└─────────────┴──────┴─────────────┴──────┴───┴─────────────┴────────────┴────────────┴────────────┘","text/html":"<div><style>\n.dataframe > thead > tr > th,\n.dataframe > tbody > tr > td {\n  text-align: right;\n  white-space: pre-wrap;\n}\n</style>\n<small>shape: (5, 40)</small><table border=\"1\" class=\"dataframe\"><thead><tr><th>series_id</th><th>step</th><th>timestamp</th><th>hour</th><th>enmo_5m_mean</th><th>enmo_5m_max</th><th>enmo_5m_std</th><th>enmo_1v_5m_mean</th><th>enmo_1v_5m_max</th><th>enmo_1v_5m_std</th><th>anglez_1v_5m_mean</th><th>anglez_1v_5m_max</th><th>anglez_1v_5m_std</th><th>enmo_30m_mean</th><th>enmo_30m_max</th><th>enmo_30m_std</th><th>enmo_1v_30m_mean</th><th>enmo_1v_30m_max</th><th>enmo_1v_30m_std</th><th>anglez_1v_30m_mean</th><th>anglez_1v_30m_max</th><th>anglez_1v_30m_std</th><th>enmo_120m_mean</th><th>enmo_120m_max</th><th>enmo_120m_std</th><th>enmo_1v_120m_mean</th><th>enmo_1v_120m_max</th><th>enmo_1v_120m_std</th><th>anglez_1v_120m_mean</th><th>anglez_1v_120m_max</th><th>anglez_1v_120m_std</th><th>enmo_480m_mean</th><th>enmo_480m_max</th><th>enmo_480m_std</th><th>enmo_1v_480m_mean</th><th>enmo_1v_480m_max</th><th>enmo_1v_480m_std</th><th>anglez_1v_480m_mean</th><th>anglez_1v_480m_max</th><th>anglez_1v_480m_std</th></tr><tr><td>str</td><td>u32</td><td>datetime[μs, UTC]</td><td>u8</td><td>f32</td><td>f32</td><td>f32</td><td>f32</td><td>f32</td><td>f32</td><td>f32</td><td>f32</td><td>f32</td><td>f32</td><td>f32</td><td>f32</td><td>f32</td><td>f32</td><td>f32</td><td>f32</td><td>f32</td><td>f32</td><td>f32</td><td>f32</td><td>f32</td><td>f32</td><td>f32</td><td>f32</td><td>f32</td><td>f32</td><td>f32</td><td>f32</td><td>f32</td><td>f32</td><td>f32</td><td>f32</td><td>f32</td><td>f32</td><td>f32</td><td>f32</td></tr></thead><tbody><tr><td>&quot;038441c925bb&quot;</td><td>0</td><td>2018-08-14 19:30:00 UTC</td><td>19</td><td>0.482106</td><td>0.236557</td><td>0.189618</td><td>0.215839</td><td>0.229409</td><td>0.303443</td><td>1.451803</td><td>2.473755</td><td>2.88798</td><td>0.407513</td><td>0.139588</td><td>0.097473</td><td>0.051146</td><td>0.132048</td><td>0.135593</td><td>0.279549</td><td>2.062542</td><td>1.458054</td><td>0.661598</td><td>0.641424</td><td>0.513826</td><td>0.275377</td><td>0.681005</td><td>0.595805</td><td>0.671359</td><td>2.342899</td><td>2.325479</td><td>3.615566</td><td>1.517537</td><td>2.467519</td><td>2.409008</td><td>1.53725</td><td>2.138996</td><td>3.048498</td><td>2.878486</td><td>3.754352</td></tr><tr><td>&quot;038441c925bb&quot;</td><td>60</td><td>2018-08-14 19:35:00 UTC</td><td>19</td><td>0.313369</td><td>0.047997</td><td>0.0</td><td>0.006348</td><td>0.003955</td><td>0.008038</td><td>0.035847</td><td>0.033887</td><td>0.066774</td><td>0.407513</td><td>0.139588</td><td>0.097473</td><td>0.05508</td><td>0.132048</td><td>0.135593</td><td>0.259581</td><td>2.062542</td><td>1.341409</td><td>0.800882</td><td>0.801781</td><td>0.739909</td><td>0.401397</td><td>0.757577</td><td>0.746417</td><td>0.850387</td><td>2.369523</td><td>2.522925</td><td>3.567358</td><td>1.517537</td><td>2.443793</td><td>2.389736</td><td>1.53725</td><td>2.118255</td><td>3.078681</td><td>2.878486</td><td>3.836564</td></tr><tr><td>&quot;038441c925bb&quot;</td><td>120</td><td>2018-08-14 19:40:00 UTC</td><td>19</td><td>0.289264</td><td>0.044569</td><td>0.0</td><td>0.009522</td><td>0.003955</td><td>0.008038</td><td>0.017923</td><td>0.033887</td><td>0.050081</td><td>0.407513</td><td>0.139588</td><td>0.097473</td><td>0.059015</td><td>0.132048</td><td>0.131421</td><td>0.219646</td><td>2.062542</td><td>1.205324</td><td>0.905345</td><td>0.801781</td><td>0.822122</td><td>0.518082</td><td>0.757577</td><td>0.815078</td><td>1.074174</td><td>2.369523</td><td>2.698433</td><td>3.567358</td><td>1.517537</td><td>2.443793</td><td>2.36404</td><td>1.53725</td><td>2.100106</td><td>3.048498</td><td>2.878486</td><td>3.80916</td></tr><tr><td>&quot;038441c925bb&quot;</td><td>180</td><td>2018-08-14 19:45:00 UTC</td><td>19</td><td>0.313369</td><td>0.047997</td><td>0.0</td><td>0.006348</td><td>0.003955</td><td>0.008038</td><td>0.017923</td><td>0.101661</td><td>0.066774</td><td>0.407513</td><td>0.139588</td><td>0.097473</td><td>0.059015</td><td>0.132048</td><td>0.127249</td><td>0.17971</td><td>2.062542</td><td>1.08868</td><td>1.392838</td><td>1.726015</td><td>1.89088</td><td>0.830798</td><td>1.344089</td><td>1.324503</td><td>1.186067</td><td>2.369523</td><td>2.74231</td><td>3.470943</td><td>1.517537</td><td>2.420067</td><td>2.325496</td><td>1.53725</td><td>2.081956</td><td>2.988132</td><td>2.878486</td><td>3.80916</td></tr><tr><td>&quot;038441c925bb&quot;</td><td>240</td><td>2018-08-14 19:50:00 UTC</td><td>19</td><td>0.36158</td><td>0.191988</td><td>0.113771</td><td>0.066656</td><td>0.170079</td><td>0.13665</td><td>0.179235</td><td>1.050499</td><td>0.801289</td><td>0.378405</td><td>0.113289</td><td>0.058484</td><td>0.039343</td><td>0.097898</td><td>0.083442</td><td>0.039936</td><td>0.875874</td><td>0.388814</td><td>1.636585</td><td>1.782868</td><td>2.158069</td><td>1.036164</td><td>1.860545</td><td>1.701033</td><td>1.275581</td><td>2.369523</td><td>2.786187</td><td>3.422736</td><td>1.517537</td><td>2.396341</td><td>2.286952</td><td>1.53725</td><td>2.063807</td><td>2.957948</td><td>2.878486</td><td>3.781756</td></tr></tbody></table></div>"},"metadata":{}}]},{"cell_type":"code","source":"from sklearn.preprocessing import LabelEncoder\nencoder= LabelEncoder()\ny_train=encoder.fit_transform(y_train)\ny_train","metadata":{"execution":{"iopub.status.busy":"2023-10-27T02:15:29.338094Z","iopub.execute_input":"2023-10-27T02:15:29.338973Z","iopub.status.idle":"2023-10-27T02:15:30.647546Z","shell.execute_reply.started":"2023-10-27T02:15:29.338929Z","shell.execute_reply":"2023-10-27T02:15:30.646435Z"},"trusted":true},"execution_count":11,"outputs":[{"execution_count":11,"output_type":"execute_result","data":{"text/plain":"array([0, 0, 0, ..., 0, 0, 0])"},"metadata":{}}]},{"cell_type":"code","source":"from sklearn.preprocessing import MinMaxScaler\nscaler = MinMaxScaler()\nX_train = scaler.fit_transform(X_train[feature_cols])\nX_train","metadata":{"execution":{"iopub.status.busy":"2023-10-27T02:15:30.648974Z","iopub.execute_input":"2023-10-27T02:15:30.649926Z","iopub.status.idle":"2023-10-27T02:15:32.38098Z","shell.execute_reply.started":"2023-10-27T02:15:30.649895Z","shell.execute_reply":"2023-10-27T02:15:32.379885Z"},"trusted":true},"execution_count":12,"outputs":[{"execution_count":12,"output_type":"execute_result","data":{"text/plain":"array([[0.82608696, 0.00971357, 0.00688995, ..., 0.25819878, 0.21838284,\n        0.35095448],\n       [0.82608696, 0.00631382, 0.00139796, ..., 0.2607552 , 0.21838284,\n        0.35885524],\n       [0.82608696, 0.00582814, 0.00129811, ..., 0.25819878, 0.21838284,\n        0.35622165],\n       ...,\n       [0.17391304, 0.        , 0.        , ..., 0.16999629, 0.63680883,\n        0.41163726],\n       [0.17391304, 0.        , 0.        , ..., 0.16999629, 0.63680883,\n        0.41500911],\n       [0.17391304, 0.00167456, 0.00815378, ..., 0.16797252, 0.63680883,\n        0.41163726]])"},"metadata":{}}]},{"cell_type":"markdown","source":"### Training and validating XGBoost","metadata":{}},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split","metadata":{"execution":{"iopub.status.busy":"2023-10-27T02:15:32.382106Z","iopub.execute_input":"2023-10-27T02:15:32.382419Z","iopub.status.idle":"2023-10-27T02:15:32.483375Z","shell.execute_reply.started":"2023-10-27T02:15:32.382392Z","shell.execute_reply":"2023-10-27T02:15:32.482283Z"},"trusted":true},"execution_count":13,"outputs":[]},{"cell_type":"code","source":"xtrain,xtest,ytrain,ytest=train_test_split(X_train,y_train,test_size=0.3,random_state=42)","metadata":{"execution":{"iopub.status.busy":"2023-10-27T02:15:32.484772Z","iopub.execute_input":"2023-10-27T02:15:32.485095Z","iopub.status.idle":"2023-10-27T02:15:32.912287Z","shell.execute_reply.started":"2023-10-27T02:15:32.485067Z","shell.execute_reply":"2023-10-27T02:15:32.911152Z"},"trusted":true},"execution_count":14,"outputs":[]},{"cell_type":"code","source":"import xgboost as xgb\n\n\n# Training classifier\ngbc =xgb.XGBClassifier(n_estimators=500,objective=\"binary:logistic\", learning_rate=0.2, max_depth=11, random_state=42)\n\ngbc.fit(xtrain, ytrain)","metadata":{"execution":{"iopub.status.busy":"2023-10-27T02:15:32.913835Z","iopub.execute_input":"2023-10-27T02:15:32.914182Z","iopub.status.idle":"2023-10-27T03:39:32.318316Z","shell.execute_reply.started":"2023-10-27T02:15:32.914152Z","shell.execute_reply":"2023-10-27T03:39:32.316317Z"},"trusted":true},"execution_count":15,"outputs":[{"execution_count":15,"output_type":"execute_result","data":{"text/plain":"XGBClassifier(base_score=None, booster=None, callbacks=None,\n              colsample_bylevel=None, colsample_bynode=None,\n              colsample_bytree=None, early_stopping_rounds=None,\n              enable_categorical=False, eval_metric=None, feature_types=None,\n              gamma=None, gpu_id=None, grow_policy=None, importance_type=None,\n              interaction_constraints=None, learning_rate=0.2, max_bin=None,\n              max_cat_threshold=None, max_cat_to_onehot=None,\n              max_delta_step=None, max_depth=11, max_leaves=None,\n              min_child_weight=None, missing=nan, monotone_constraints=None,\n              n_estimators=500, n_jobs=None, num_parallel_tree=None,\n              predictor=None, random_state=42, ...)","text/html":"<style>#sk-container-id-1 {color: black;background-color: white;}#sk-container-id-1 pre{padding: 0;}#sk-container-id-1 div.sk-toggleable {background-color: white;}#sk-container-id-1 label.sk-toggleable__label {cursor: pointer;display: block;width: 100%;margin-bottom: 0;padding: 0.3em;box-sizing: border-box;text-align: center;}#sk-container-id-1 label.sk-toggleable__label-arrow:before {content: \"▸\";float: left;margin-right: 0.25em;color: #696969;}#sk-container-id-1 label.sk-toggleable__label-arrow:hover:before {color: black;}#sk-container-id-1 div.sk-estimator:hover label.sk-toggleable__label-arrow:before {color: black;}#sk-container-id-1 div.sk-toggleable__content {max-height: 0;max-width: 0;overflow: hidden;text-align: left;background-color: #f0f8ff;}#sk-container-id-1 div.sk-toggleable__content pre {margin: 0.2em;color: black;border-radius: 0.25em;background-color: #f0f8ff;}#sk-container-id-1 input.sk-toggleable__control:checked~div.sk-toggleable__content {max-height: 200px;max-width: 100%;overflow: auto;}#sk-container-id-1 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before {content: \"▾\";}#sk-container-id-1 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-1 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-1 input.sk-hidden--visually {border: 0;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);height: 1px;margin: -1px;overflow: hidden;padding: 0;position: absolute;width: 1px;}#sk-container-id-1 div.sk-estimator {font-family: monospace;background-color: #f0f8ff;border: 1px dotted black;border-radius: 0.25em;box-sizing: border-box;margin-bottom: 0.5em;}#sk-container-id-1 div.sk-estimator:hover {background-color: #d4ebff;}#sk-container-id-1 div.sk-parallel-item::after {content: \"\";width: 100%;border-bottom: 1px solid gray;flex-grow: 1;}#sk-container-id-1 div.sk-label:hover label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-1 div.sk-serial::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: 0;}#sk-container-id-1 div.sk-serial {display: flex;flex-direction: column;align-items: center;background-color: white;padding-right: 0.2em;padding-left: 0.2em;position: relative;}#sk-container-id-1 div.sk-item {position: relative;z-index: 1;}#sk-container-id-1 div.sk-parallel {display: flex;align-items: stretch;justify-content: center;background-color: white;position: relative;}#sk-container-id-1 div.sk-item::before, #sk-container-id-1 div.sk-parallel-item::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: -1;}#sk-container-id-1 div.sk-parallel-item {display: flex;flex-direction: column;z-index: 1;position: relative;background-color: white;}#sk-container-id-1 div.sk-parallel-item:first-child::after {align-self: flex-end;width: 50%;}#sk-container-id-1 div.sk-parallel-item:last-child::after {align-self: flex-start;width: 50%;}#sk-container-id-1 div.sk-parallel-item:only-child::after {width: 0;}#sk-container-id-1 div.sk-dashed-wrapped {border: 1px dashed gray;margin: 0 0.4em 0.5em 0.4em;box-sizing: border-box;padding-bottom: 0.4em;background-color: white;}#sk-container-id-1 div.sk-label label {font-family: monospace;font-weight: bold;display: inline-block;line-height: 1.2em;}#sk-container-id-1 div.sk-label-container {text-align: center;}#sk-container-id-1 div.sk-container {/* jupyter's `normalize.less` sets `[hidden] { display: none; }` but bootstrap.min.css set `[hidden] { display: none !important; }` so we also need the `!important` here to be able to override the default hidden behavior on the sphinx rendered scikit-learn.org. See: https://github.com/scikit-learn/scikit-learn/issues/21755 */display: inline-block !important;position: relative;}#sk-container-id-1 div.sk-text-repr-fallback {display: none;}</style><div id=\"sk-container-id-1\" class=\"sk-top-container\"><div class=\"sk-text-repr-fallback\"><pre>XGBClassifier(base_score=None, booster=None, callbacks=None,\n              colsample_bylevel=None, colsample_bynode=None,\n              colsample_bytree=None, early_stopping_rounds=None,\n              enable_categorical=False, eval_metric=None, feature_types=None,\n              gamma=None, gpu_id=None, grow_policy=None, importance_type=None,\n              interaction_constraints=None, learning_rate=0.2, max_bin=None,\n              max_cat_threshold=None, max_cat_to_onehot=None,\n              max_delta_step=None, max_depth=11, max_leaves=None,\n              min_child_weight=None, missing=nan, monotone_constraints=None,\n              n_estimators=500, n_jobs=None, num_parallel_tree=None,\n              predictor=None, random_state=42, ...)</pre><b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.</b></div><div class=\"sk-container\" hidden><div class=\"sk-item\"><div class=\"sk-estimator sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-1\" type=\"checkbox\" checked><label for=\"sk-estimator-id-1\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">XGBClassifier</label><div class=\"sk-toggleable__content\"><pre>XGBClassifier(base_score=None, booster=None, callbacks=None,\n              colsample_bylevel=None, colsample_bynode=None,\n              colsample_bytree=None, early_stopping_rounds=None,\n              enable_categorical=False, eval_metric=None, feature_types=None,\n              gamma=None, gpu_id=None, grow_policy=None, importance_type=None,\n              interaction_constraints=None, learning_rate=0.2, max_bin=None,\n              max_cat_threshold=None, max_cat_to_onehot=None,\n              max_delta_step=None, max_depth=11, max_leaves=None,\n              min_child_weight=None, missing=nan, monotone_constraints=None,\n              n_estimators=500, n_jobs=None, num_parallel_tree=None,\n              predictor=None, random_state=42, ...)</pre></div></div></div></div></div>"},"metadata":{}}]},{"cell_type":"code","source":"gbc.score(xtest,ytest)","metadata":{"execution":{"iopub.status.busy":"2023-10-27T03:39:32.321986Z","iopub.execute_input":"2023-10-27T03:39:32.322521Z","iopub.status.idle":"2023-10-27T03:39:40.226768Z","shell.execute_reply.started":"2023-10-27T03:39:32.322479Z","shell.execute_reply":"2023-10-27T03:39:40.225524Z"},"trusted":true},"execution_count":16,"outputs":[{"execution_count":16,"output_type":"execute_result","data":{"text/plain":"0.9927128347361287"},"metadata":{}}]},{"cell_type":"code","source":"# Plotting feature importances\npx.bar(x=feature_cols, \n       y=gbc.feature_importances_,\n       title='XGB feature importances'\n      )","metadata":{"execution":{"iopub.status.busy":"2023-10-27T03:39:40.228333Z","iopub.execute_input":"2023-10-27T03:39:40.228649Z","iopub.status.idle":"2023-10-27T03:39:42.258867Z","shell.execute_reply.started":"2023-10-27T03:39:40.228622Z","shell.execute_reply":"2023-10-27T03:39:42.257779Z"},"trusted":true},"execution_count":17,"outputs":[{"output_type":"display_data","data":{"text/html":"        <script type=\"text/javascript\">\n        window.PlotlyConfig = {MathJaxConfig: 'local'};\n        if (window.MathJax && window.MathJax.Hub && window.MathJax.Hub.Config) {window.MathJax.Hub.Config({SVG: {font: \"STIX-Web\"}});}\n        if (typeof require !== 'undefined') {\n        require.undef(\"plotly\");\n        requirejs.config({\n            paths: {\n                'plotly': ['https://cdn.plot.ly/plotly-2.24.1.min']\n            }\n        });\n        require(['plotly'], function(Plotly) {\n            window._Plotly = Plotly;\n        });\n        }\n        </script>\n        "},"metadata":{}},{"output_type":"display_data","data":{"text/html":"<div>                            <div id=\"2c9fb070-7c3e-40b6-9405-30134cc26a57\" class=\"plotly-graph-div\" style=\"height:525px; width:100%;\"></div>            <script type=\"text/javascript\">                require([\"plotly\"], function(Plotly) {                    window.PLOTLYENV=window.PLOTLYENV || {};                                    if (document.getElementById(\"2c9fb070-7c3e-40b6-9405-30134cc26a57\")) {                    Plotly.newPlot(                        \"2c9fb070-7c3e-40b6-9405-30134cc26a57\",                        [{\"alignmentgroup\":\"True\",\"hovertemplate\":\"x=%{x}\\u003cbr\\u003ey=%{y}\\u003cextra\\u003e\\u003c\\u002fextra\\u003e\",\"legendgroup\":\"\",\"marker\":{\"color\":\"#636efa\",\"pattern\":{\"shape\":\"\"}},\"name\":\"\",\"offsetgroup\":\"\",\"orientation\":\"v\",\"showlegend\":false,\"textposition\":\"auto\",\"x\":[\"hour\",\"enmo_5m_mean\",\"enmo_5m_max\",\"enmo_5m_std\",\"enmo_1v_5m_mean\",\"enmo_1v_5m_max\",\"enmo_1v_5m_std\",\"anglez_1v_5m_mean\",\"anglez_1v_5m_max\",\"anglez_1v_5m_std\",\"enmo_30m_mean\",\"enmo_30m_max\",\"enmo_30m_std\",\"enmo_1v_30m_mean\",\"enmo_1v_30m_max\",\"enmo_1v_30m_std\",\"anglez_1v_30m_mean\",\"anglez_1v_30m_max\",\"anglez_1v_30m_std\",\"enmo_120m_mean\",\"enmo_120m_max\",\"enmo_120m_std\",\"enmo_1v_120m_mean\",\"enmo_1v_120m_max\",\"enmo_1v_120m_std\",\"anglez_1v_120m_mean\",\"anglez_1v_120m_max\",\"anglez_1v_120m_std\",\"enmo_480m_mean\",\"enmo_480m_max\",\"enmo_480m_std\",\"enmo_1v_480m_mean\",\"enmo_1v_480m_max\",\"enmo_1v_480m_std\",\"anglez_1v_480m_mean\",\"anglez_1v_480m_max\",\"anglez_1v_480m_std\"],\"xaxis\":\"x\",\"y\":[0.034701973,0.0026366557,0.0022038089,0.002070175,0.0035111583,0.006071964,0.002098989,0.04284623,0.0069813943,0.0039798743,0.0047257715,0.0032687674,0.0037064073,0.60507417,0.0039099874,0.011138651,0.009543532,0.0059280037,0.005213143,0.009540045,0.005090206,0.0059960936,0.027112413,0.005585583,0.0063154846,0.022443892,0.09272707,0.00754907,0.005546823,0.0055474984,0.0043712547,0.0038762793,0.0054532695,0.0045336476,0.0068016755,0.014276923,0.0076221125],\"yaxis\":\"y\",\"type\":\"bar\"}],                        {\"template\":{\"data\":{\"histogram2dcontour\":[{\"type\":\"histogram2dcontour\",\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"colorscale\":[[0.0,\"#0d0887\"],[0.1111111111111111,\"#46039f\"],[0.2222222222222222,\"#7201a8\"],[0.3333333333333333,\"#9c179e\"],[0.4444444444444444,\"#bd3786\"],[0.5555555555555556,\"#d8576b\"],[0.6666666666666666,\"#ed7953\"],[0.7777777777777778,\"#fb9f3a\"],[0.8888888888888888,\"#fdca26\"],[1.0,\"#f0f921\"]]}],\"choropleth\":[{\"type\":\"choropleth\",\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}}],\"histogram2d\":[{\"type\":\"histogram2d\",\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"colorscale\":[[0.0,\"#0d0887\"],[0.1111111111111111,\"#46039f\"],[0.2222222222222222,\"#7201a8\"],[0.3333333333333333,\"#9c179e\"],[0.4444444444444444,\"#bd3786\"],[0.5555555555555556,\"#d8576b\"],[0.6666666666666666,\"#ed7953\"],[0.7777777777777778,\"#fb9f3a\"],[0.8888888888888888,\"#fdca26\"],[1.0,\"#f0f921\"]]}],\"heatmap\":[{\"type\":\"heatmap\",\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"colorscale\":[[0.0,\"#0d0887\"],[0.1111111111111111,\"#46039f\"],[0.2222222222222222,\"#7201a8\"],[0.3333333333333333,\"#9c179e\"],[0.4444444444444444,\"#bd3786\"],[0.5555555555555556,\"#d8576b\"],[0.6666666666666666,\"#ed7953\"],[0.7777777777777778,\"#fb9f3a\"],[0.8888888888888888,\"#fdca26\"],[1.0,\"#f0f921\"]]}],\"heatmapgl\":[{\"type\":\"heatmapgl\",\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"colorscale\":[[0.0,\"#0d0887\"],[0.1111111111111111,\"#46039f\"],[0.2222222222222222,\"#7201a8\"],[0.3333333333333333,\"#9c179e\"],[0.4444444444444444,\"#bd3786\"],[0.5555555555555556,\"#d8576b\"],[0.6666666666666666,\"#ed7953\"],[0.7777777777777778,\"#fb9f3a\"],[0.8888888888888888,\"#fdca26\"],[1.0,\"#f0f921\"]]}],\"contourcarpet\":[{\"type\":\"contourcarpet\",\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}}],\"contour\":[{\"type\":\"contour\",\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"colorscale\":[[0.0,\"#0d0887\"],[0.1111111111111111,\"#46039f\"],[0.2222222222222222,\"#7201a8\"],[0.3333333333333333,\"#9c179e\"],[0.4444444444444444,\"#bd3786\"],[0.5555555555555556,\"#d8576b\"],[0.6666666666666666,\"#ed7953\"],[0.7777777777777778,\"#fb9f3a\"],[0.8888888888888888,\"#fdca26\"],[1.0,\"#f0f921\"]]}],\"surface\":[{\"type\":\"surface\",\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"},\"colorscale\":[[0.0,\"#0d0887\"],[0.1111111111111111,\"#46039f\"],[0.2222222222222222,\"#7201a8\"],[0.3333333333333333,\"#9c179e\"],[0.4444444444444444,\"#bd3786\"],[0.5555555555555556,\"#d8576b\"],[0.6666666666666666,\"#ed7953\"],[0.7777777777777778,\"#fb9f3a\"],[0.8888888888888888,\"#fdca26\"],[1.0,\"#f0f921\"]]}],\"mesh3d\":[{\"type\":\"mesh3d\",\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}}],\"scatter\":[{\"fillpattern\":{\"fillmode\":\"overlay\",\"size\":10,\"solidity\":0.2},\"type\":\"scatter\"}],\"parcoords\":[{\"type\":\"parcoords\",\"line\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}}}],\"scatterpolargl\":[{\"type\":\"scatterpolargl\",\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}}}],\"bar\":[{\"error_x\":{\"color\":\"#2a3f5f\"},\"error_y\":{\"color\":\"#2a3f5f\"},\"marker\":{\"line\":{\"color\":\"#E5ECF6\",\"width\":0.5},\"pattern\":{\"fillmode\":\"overlay\",\"size\":10,\"solidity\":0.2}},\"type\":\"bar\"}],\"scattergeo\":[{\"type\":\"scattergeo\",\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}}}],\"scatterpolar\":[{\"type\":\"scatterpolar\",\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}}}],\"histogram\":[{\"marker\":{\"pattern\":{\"fillmode\":\"overlay\",\"size\":10,\"solidity\":0.2}},\"type\":\"histogram\"}],\"scattergl\":[{\"type\":\"scattergl\",\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}}}],\"scatter3d\":[{\"type\":\"scatter3d\",\"line\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}}}],\"scattermapbox\":[{\"type\":\"scattermapbox\",\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}}}],\"scatterternary\":[{\"type\":\"scatterternary\",\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}}}],\"scattercarpet\":[{\"type\":\"scattercarpet\",\"marker\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}}}],\"carpet\":[{\"aaxis\":{\"endlinecolor\":\"#2a3f5f\",\"gridcolor\":\"white\",\"linecolor\":\"white\",\"minorgridcolor\":\"white\",\"startlinecolor\":\"#2a3f5f\"},\"baxis\":{\"endlinecolor\":\"#2a3f5f\",\"gridcolor\":\"white\",\"linecolor\":\"white\",\"minorgridcolor\":\"white\",\"startlinecolor\":\"#2a3f5f\"},\"type\":\"carpet\"}],\"table\":[{\"cells\":{\"fill\":{\"color\":\"#EBF0F8\"},\"line\":{\"color\":\"white\"}},\"header\":{\"fill\":{\"color\":\"#C8D4E3\"},\"line\":{\"color\":\"white\"}},\"type\":\"table\"}],\"barpolar\":[{\"marker\":{\"line\":{\"color\":\"#E5ECF6\",\"width\":0.5},\"pattern\":{\"fillmode\":\"overlay\",\"size\":10,\"solidity\":0.2}},\"type\":\"barpolar\"}],\"pie\":[{\"automargin\":true,\"type\":\"pie\"}]},\"layout\":{\"autotypenumbers\":\"strict\",\"colorway\":[\"#636efa\",\"#EF553B\",\"#00cc96\",\"#ab63fa\",\"#FFA15A\",\"#19d3f3\",\"#FF6692\",\"#B6E880\",\"#FF97FF\",\"#FECB52\"],\"font\":{\"color\":\"#2a3f5f\"},\"hovermode\":\"closest\",\"hoverlabel\":{\"align\":\"left\"},\"paper_bgcolor\":\"white\",\"plot_bgcolor\":\"#E5ECF6\",\"polar\":{\"bgcolor\":\"#E5ECF6\",\"angularaxis\":{\"gridcolor\":\"white\",\"linecolor\":\"white\",\"ticks\":\"\"},\"radialaxis\":{\"gridcolor\":\"white\",\"linecolor\":\"white\",\"ticks\":\"\"}},\"ternary\":{\"bgcolor\":\"#E5ECF6\",\"aaxis\":{\"gridcolor\":\"white\",\"linecolor\":\"white\",\"ticks\":\"\"},\"baxis\":{\"gridcolor\":\"white\",\"linecolor\":\"white\",\"ticks\":\"\"},\"caxis\":{\"gridcolor\":\"white\",\"linecolor\":\"white\",\"ticks\":\"\"}},\"coloraxis\":{\"colorbar\":{\"outlinewidth\":0,\"ticks\":\"\"}},\"colorscale\":{\"sequential\":[[0.0,\"#0d0887\"],[0.1111111111111111,\"#46039f\"],[0.2222222222222222,\"#7201a8\"],[0.3333333333333333,\"#9c179e\"],[0.4444444444444444,\"#bd3786\"],[0.5555555555555556,\"#d8576b\"],[0.6666666666666666,\"#ed7953\"],[0.7777777777777778,\"#fb9f3a\"],[0.8888888888888888,\"#fdca26\"],[1.0,\"#f0f921\"]],\"sequentialminus\":[[0.0,\"#0d0887\"],[0.1111111111111111,\"#46039f\"],[0.2222222222222222,\"#7201a8\"],[0.3333333333333333,\"#9c179e\"],[0.4444444444444444,\"#bd3786\"],[0.5555555555555556,\"#d8576b\"],[0.6666666666666666,\"#ed7953\"],[0.7777777777777778,\"#fb9f3a\"],[0.8888888888888888,\"#fdca26\"],[1.0,\"#f0f921\"]],\"diverging\":[[0,\"#8e0152\"],[0.1,\"#c51b7d\"],[0.2,\"#de77ae\"],[0.3,\"#f1b6da\"],[0.4,\"#fde0ef\"],[0.5,\"#f7f7f7\"],[0.6,\"#e6f5d0\"],[0.7,\"#b8e186\"],[0.8,\"#7fbc41\"],[0.9,\"#4d9221\"],[1,\"#276419\"]]},\"xaxis\":{\"gridcolor\":\"white\",\"linecolor\":\"white\",\"ticks\":\"\",\"title\":{\"standoff\":15},\"zerolinecolor\":\"white\",\"automargin\":true,\"zerolinewidth\":2},\"yaxis\":{\"gridcolor\":\"white\",\"linecolor\":\"white\",\"ticks\":\"\",\"title\":{\"standoff\":15},\"zerolinecolor\":\"white\",\"automargin\":true,\"zerolinewidth\":2},\"scene\":{\"xaxis\":{\"backgroundcolor\":\"#E5ECF6\",\"gridcolor\":\"white\",\"linecolor\":\"white\",\"showbackground\":true,\"ticks\":\"\",\"zerolinecolor\":\"white\",\"gridwidth\":2},\"yaxis\":{\"backgroundcolor\":\"#E5ECF6\",\"gridcolor\":\"white\",\"linecolor\":\"white\",\"showbackground\":true,\"ticks\":\"\",\"zerolinecolor\":\"white\",\"gridwidth\":2},\"zaxis\":{\"backgroundcolor\":\"#E5ECF6\",\"gridcolor\":\"white\",\"linecolor\":\"white\",\"showbackground\":true,\"ticks\":\"\",\"zerolinecolor\":\"white\",\"gridwidth\":2}},\"shapedefaults\":{\"line\":{\"color\":\"#2a3f5f\"}},\"annotationdefaults\":{\"arrowcolor\":\"#2a3f5f\",\"arrowhead\":0,\"arrowwidth\":1},\"geo\":{\"bgcolor\":\"white\",\"landcolor\":\"#E5ECF6\",\"subunitcolor\":\"white\",\"showland\":true,\"showlakes\":true,\"lakecolor\":\"white\"},\"title\":{\"x\":0.05},\"mapbox\":{\"style\":\"light\"}}},\"xaxis\":{\"anchor\":\"y\",\"domain\":[0.0,1.0],\"title\":{\"text\":\"x\"}},\"yaxis\":{\"anchor\":\"x\",\"domain\":[0.0,1.0],\"title\":{\"text\":\"y\"}},\"legend\":{\"tracegroupgap\":0},\"title\":{\"text\":\"XGB feature importances\"},\"barmode\":\"relative\"},                        {\"responsive\": true}                    ).then(function(){\n                            \nvar gd = document.getElementById('2c9fb070-7c3e-40b6-9405-30134cc26a57');\nvar x = new MutationObserver(function (mutations, observer) {{\n        var display = window.getComputedStyle(gd).display;\n        if (!display || display === 'none') {{\n            console.log([gd, 'removed!']);\n            Plotly.purge(gd);\n            observer.disconnect();\n        }}\n}});\n\n// Listen for the removal of the full notebook cells\nvar notebookContainer = gd.closest('#notebook-container');\nif (notebookContainer) {{\n    x.observe(notebookContainer, {childList: true});\n}}\n\n// Listen for the clearing of the current output cell\nvar outputEl = gd.closest('.output');\nif (outputEl) {{\n    x.observe(outputEl, {childList: true});\n}}\n\n                        })                };                });            </script>        </div>"},"metadata":{}}]},{"cell_type":"code","source":"# Saving classifier \nimport pickle\nwith open('rf_classifier_5m_8h.pkl', 'wb') as f:\n    pickle.dump(gbc, f)\n\n#with open('rf_classifier.pkl', 'rb') as f:\n#    rf_classifier = pickle.load(f)","metadata":{"execution":{"iopub.status.busy":"2023-10-27T03:39:42.260481Z","iopub.execute_input":"2023-10-27T03:39:42.2615Z","iopub.status.idle":"2023-10-27T03:39:42.336878Z","shell.execute_reply.started":"2023-10-27T03:39:42.261458Z","shell.execute_reply":"2023-10-27T03:39:42.335756Z"},"trusted":true},"execution_count":18,"outputs":[]},{"cell_type":"markdown","source":"## Applying to test data","metadata":{}},{"cell_type":"code","source":"# Getting event predictions for test set and saving submission\nsubmission = get_events(test_series.collect(), gbc)\n# submission.to_csv('submission.csv', index=False)\nsubmission","metadata":{"execution":{"iopub.status.busy":"2023-10-27T03:39:42.338472Z","iopub.execute_input":"2023-10-27T03:39:42.338874Z","iopub.status.idle":"2023-10-27T03:39:42.569741Z","shell.execute_reply.started":"2023-10-27T03:39:42.338833Z","shell.execute_reply":"2023-10-27T03:39:42.56862Z"},"trusted":true},"execution_count":19,"outputs":[{"name":"stderr","text":"100%|██████████| 3/3 [00:00<00:00, 18.42it/s]\n","output_type":"stream"},{"execution_count":19,"output_type":"execute_result","data":{"text/plain":"Empty DataFrame\nColumns: [row_id, series_id, step, event, score]\nIndex: []","text/html":"<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>row_id</th>\n      <th>series_id</th>\n      <th>step</th>\n      <th>event</th>\n      <th>score</th>\n    </tr>\n  </thead>\n  <tbody>\n  </tbody>\n</table>\n</div>"},"metadata":{}}]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}