{"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":"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":"2023-09-15T16:18:11.232092Z","iopub.execute_input":"2023-09-15T16:18:11.232518Z","iopub.status.idle":"2023-09-15T16:18:11.673365Z","shell.execute_reply.started":"2023-09-15T16:18:11.232488Z","shell.execute_reply":"2023-09-15T16:18:11.672368Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport plotly.express as px\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport random\nimport os\nimport gc\nfrom copy import deepcopy\nfrom functools import partial\nfrom itertools import combinations\nfrom itertools import groupby\n\n# Import sklearn classes for model selection, cross validation, and performance evaluation\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import StratifiedKFold, KFold\nfrom sklearn.metrics import roc_auc_score, accuracy_score, log_loss\nfrom sklearn.model_selection import cross_validate\nfrom sklearn.metrics import RocCurveDisplay\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import ConfusionMatrixDisplay\nfrom sklearn.metrics import precision_score\nfrom sklearn.metrics import average_precision_score\n\n# Import libraries for Hypertuning\nimport optuna\n\n#Import libraries for gradient boosting\nimport xgboost as xgb\nimport lightgbm as lgb\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.pipeline import Pipeline\nfrom catboost import Pool\n\n\n\n# Useful line of code to set the display option so we could see all the columns in pd dataframe\npd.set_option('display.max_columns', None)\n\n# Suppress warnings\nimport warnings\nwarnings.filterwarnings(\"ignore\", category=UserWarning)","metadata":{"execution":{"iopub.status.busy":"2023-09-15T16:18:11.675185Z","iopub.execute_input":"2023-09-15T16:18:11.675654Z","iopub.status.idle":"2023-09-15T16:18:17.294271Z","shell.execute_reply.started":"2023-09-15T16:18:11.675625Z","shell.execute_reply":"2023-09-15T16:18:17.292998Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install --upgrade wandb","metadata":{"execution":{"iopub.status.busy":"2023-09-15T16:18:17.295642Z","iopub.execute_input":"2023-09-15T16:18:17.296038Z","iopub.status.idle":"2023-09-15T16:18:37.517414Z","shell.execute_reply.started":"2023-09-15T16:18:17.296008Z","shell.execute_reply":"2023-09-15T16:18:37.516141Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import wandb\n\ntry:\n    from kaggle_secrets import UserSecretsClient\n    user_secrets = UserSecretsClient()\n    api_key = user_secrets.get_secret(\"wandb_api\")\n    wandb.login(key=api_key)\n    anony = None\nexcept:\n    anony = \"must\"\n    print('If you want to use your W&B account, go to Add-ons -> Secrets and provide your W&B access token. Use the Label name as wandb_api. \\nGet your W&B access token from here: https://wandb.ai/authorize')","metadata":{"execution":{"iopub.status.busy":"2023-09-15T16:18:37.521565Z","iopub.execute_input":"2023-09-15T16:18:37.522084Z","iopub.status.idle":"2023-09-15T16:18:41.298333Z","shell.execute_reply.started":"2023-09-15T16:18:37.522044Z","shell.execute_reply":"2023-09-15T16:18:41.297273Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_events=pd.read_csv('/kaggle/input/child-mind-institute-detect-sleep-states/train_events.csv')","metadata":{"execution":{"iopub.status.busy":"2023-09-15T16:18:41.299777Z","iopub.execute_input":"2023-09-15T16:18:41.300786Z","iopub.status.idle":"2023-09-15T16:18:41.361205Z","shell.execute_reply.started":"2023-09-15T16:18:41.300747Z","shell.execute_reply":"2023-09-15T16:18:41.360243Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_events.head()","metadata":{"execution":{"iopub.status.busy":"2023-09-15T16:18:41.362794Z","iopub.execute_input":"2023-09-15T16:18:41.363406Z","iopub.status.idle":"2023-09-15T16:18:41.391483Z","shell.execute_reply.started":"2023-09-15T16:18:41.363373Z","shell.execute_reply":"2023-09-15T16:18:41.390199Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_events = df_events.dropna()","metadata":{"execution":{"iopub.status.busy":"2023-09-15T16:18:41.393473Z","iopub.execute_input":"2023-09-15T16:18:41.393968Z","iopub.status.idle":"2023-09-15T16:18:41.409888Z","shell.execute_reply.started":"2023-09-15T16:18:41.393928Z","shell.execute_reply":"2023-09-15T16:18:41.408441Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_events.event = df_events.event.replace({'onset':'0', 'wakeup':'1'})","metadata":{"execution":{"iopub.status.busy":"2023-09-15T16:18:41.414217Z","iopub.execute_input":"2023-09-15T16:18:41.414893Z","iopub.status.idle":"2023-09-15T16:18:41.431037Z","shell.execute_reply.started":"2023-09-15T16:18:41.414858Z","shell.execute_reply":"2023-09-15T16:18:41.429768Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_events","metadata":{"execution":{"iopub.status.busy":"2023-09-15T16:18:41.432481Z","iopub.execute_input":"2023-09-15T16:18:41.432901Z","iopub.status.idle":"2023-09-15T16:18:41.458872Z","shell.execute_reply.started":"2023-09-15T16:18:41.432868Z","shell.execute_reply":"2023-09-15T16:18:41.457602Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train = pd.read_parquet(\"/kaggle/input/zzzs-lightweight-training-dataset-target/Zzzs_train.parquet\")\ntest  = pd.read_parquet(\"/kaggle/input/child-mind-institute-detect-sleep-states/test_series.parquet\")","metadata":{"execution":{"iopub.status.busy":"2023-09-15T16:18:41.463863Z","iopub.execute_input":"2023-09-15T16:18:41.464534Z","iopub.status.idle":"2023-09-15T16:18:52.204094Z","shell.execute_reply.started":"2023-09-15T16:18:41.464496Z","shell.execute_reply":"2023-09-15T16:18:52.202951Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.describe()","metadata":{"execution":{"iopub.status.busy":"2023-09-15T16:18:52.205566Z","iopub.execute_input":"2023-09-15T16:18:52.205911Z","iopub.status.idle":"2023-09-15T16:18:54.212748Z","shell.execute_reply.started":"2023-09-15T16:18:52.205882Z","shell.execute_reply":"2023-09-15T16:18:54.211485Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def create_wandb_hist(x_data=None, x_name=None, title=None, log=None):\n    \n    data = [[x] for x in x_data]\n    table = wandb.Table(data=data, columns=[x_name])\n    wandb.log({log : wandb.plot.histogram(table, x_name, title=title)})","metadata":{"execution":{"iopub.status.busy":"2023-09-15T16:18:54.214485Z","iopub.execute_input":"2023-09-15T16:18:54.214999Z","iopub.status.idle":"2023-09-15T16:18:54.222545Z","shell.execute_reply.started":"2023-09-15T16:18:54.214956Z","shell.execute_reply":"2023-09-15T16:18:54.221355Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.isnull().sum()","metadata":{"execution":{"iopub.status.busy":"2023-09-15T16:18:54.224135Z","iopub.execute_input":"2023-09-15T16:18:54.224482Z","iopub.status.idle":"2023-09-15T16:18:57.014826Z","shell.execute_reply.started":"2023-09-15T16:18:54.224455Z","shell.execute_reply":"2023-09-15T16:18:57.013480Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"periods=60\nfor df in (train, test):\n    df[\"anglez_times_enmo\"] = np.abs(df[\"anglez\"]) * df[\"enmo\"]\n    df[\"hour\"] = pd.to_datetime(df[\"timestamp\"], utc=True).dt.hour\n# Calculate the rolling mean for \"anglez\" with the specified number of periods\n    df[\"anglez_rolling\"] = df[\"anglez\"].rolling(window=periods, center=True).mean()\n\n# Fill missing values using forward fill (\"ffill\") and backward fill (\"bfill\")\n    df[\"anglez_rolling\"].fillna(method=\"bfill\", inplace=True)\n    df[\"anglez_rolling\"].fillna(method=\"ffill\", inplace=True)\n# Calculate the difference within each group and assign it to a new column\n    df['anglez_diff'] = df.groupby('series_id')['anglez'].transform(lambda x: x.diff(periods=periods))\n    df['anglez_diff'].fillna(method='bfill', inplace=True)\n    df['enmo_diff'] = df.groupby('series_id')['enmo'].transform(lambda x: x.diff(periods=periods))\n    df['enmo_diff'].fillna(method='bfill', inplace=True)\n#Calculate the rolling mean within each group and fill missing values\n    df[\"enmo_rolling\"] = df.groupby('series_id')['enmo'].transform(lambda x: x.rolling(periods, center=True).mean()).fillna(method=\"bfill\").fillna(method=\"ffill\")\n    window_size = periods\n#Calculate the rolling mean and fill missing values\n    df[\"anglez_diff_rolling\"] = df[\"anglez_diff\"].rolling(window=window_size, center=True).mean().bfill().ffill()\n# Calculate the rolling mean of 'enmo_diff' with a specified window size\n    df[\"enmo_diff_rolling\"] = df[\"enmo_diff\"].rolling(window=periods, center=True).mean()\n\n# Fill missing values with backward fill and forward fill\n    df[\"enmo_diff_rolling\"].fillna(method=\"bfill\", inplace=True)\n    df[\"enmo_diff_rolling\"].fillna(method=\"ffill\", inplace=True)","metadata":{"execution":{"iopub.status.busy":"2023-09-15T16:18:57.016189Z","iopub.execute_input":"2023-09-15T16:18:57.016520Z","iopub.status.idle":"2023-09-15T16:21:00.001975Z","shell.execute_reply.started":"2023-09-15T16:18:57.016493Z","shell.execute_reply":"2023-09-15T16:21:00.000775Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"features = [\"hour\",\"anglez_times_enmo\",\n           \"anglez\",\"anglez_diff\",\"anglez_rolling\",\"anglez_diff_rolling\",\n           \"enmo\",\"enmo_diff\",\"enmo_rolling\",\"enmo_diff_rolling\"]","metadata":{"execution":{"iopub.status.busy":"2023-09-15T16:21:00.003503Z","iopub.execute_input":"2023-09-15T16:21:00.004093Z","iopub.status.idle":"2023-09-15T16:21:00.009606Z","shell.execute_reply.started":"2023-09-15T16:21:00.004060Z","shell.execute_reply":"2023-09-15T16:21:00.008580Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X = train[features]\ny = train[\"awake\"]","metadata":{"execution":{"iopub.status.busy":"2023-09-15T16:21:00.011066Z","iopub.execute_input":"2023-09-15T16:21:00.011617Z","iopub.status.idle":"2023-09-15T16:21:00.640572Z","shell.execute_reply.started":"2023-09-15T16:21:00.011585Z","shell.execute_reply":"2023-09-15T16:21:00.639536Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import wandb\nwandb.init(project=\"visualize-sklearn\")","metadata":{"execution":{"iopub.status.busy":"2023-09-15T16:21:00.642001Z","iopub.execute_input":"2023-09-15T16:21:00.642498Z","iopub.status.idle":"2023-09-15T16:21:32.192559Z","shell.execute_reply.started":"2023-09-15T16:21:00.642456Z","shell.execute_reply":"2023-09-15T16:21:32.191408Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\nX_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2,random_state=42)\nX_train.shape,X_test.shape,y_train.shape,y_test.shape","metadata":{"execution":{"iopub.status.busy":"2023-09-15T16:21:32.194114Z","iopub.execute_input":"2023-09-15T16:21:32.194460Z","iopub.status.idle":"2023-09-15T16:21:38.660385Z","shell.execute_reply.started":"2023-09-15T16:21:32.194430Z","shell.execute_reply":"2023-09-15T16:21:38.659426Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"config = wandb.config\nconfig.seed = 42\nconfig.test_size = 0.2\nconfig.colsample_bytree = 0.3\nconfig.learning_rate = 0.01\nconfig.max_depth = 5\nconfig.alpha = 10\nconfig.n_estimators = 50\nconfig.min_samples_leaf=100","metadata":{"execution":{"iopub.status.busy":"2023-09-15T16:21:38.661916Z","iopub.execute_input":"2023-09-15T16:21:38.662861Z","iopub.status.idle":"2023-09-15T16:21:38.678356Z","shell.execute_reply.started":"2023-09-15T16:21:38.662817Z","shell.execute_reply":"2023-09-15T16:21:38.677138Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}