{"metadata":{"kernelspec":{"name":"python3","display_name":"Python 3","language":"python"},"language_info":{"name":"python","version":"3.10.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":50160,"databundleVersionId":7921029,"sourceType":"competition"}],"dockerImageVersionId":30665,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import sys\nfrom pathlib import Path\nimport subprocess\nimport os\nimport gc\nfrom glob import glob\n\nimport numpy as np\nimport pandas as pd\nimport polars as pl\nfrom datetime import datetime\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\nROOT = '/kaggle/input/home-credit-credit-risk-model-stability'\n\nfrom sklearn.model_selection import TimeSeriesSplit, GroupKFold, StratifiedGroupKFold\nfrom sklearn.base import BaseEstimator, RegressorMixin\nfrom sklearn.metrics import roc_auc_score\nimport lightgbm as lgb\n\nfrom imblearn.over_sampling import SMOTE\nfrom sklearn.preprocessing import OrdinalEncoder\nfrom sklearn.impute import KNNImputer","metadata":{"execution":{"iopub.status.busy":"2024-05-18T14:21:10.357109Z","iopub.execute_input":"2024-05-18T14:21:10.357466Z","iopub.status.idle":"2024-05-18T14:21:18.738011Z","shell.execute_reply.started":"2024-05-18T14:21:10.357435Z","shell.execute_reply":"2024-05-18T14:21:18.737147Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class Pipeline:\n\n    def set_table_dtypes(df):\n        for col in df.columns:\n            if col in [\"case_id\", \"WEEK_NUM\", \"num_group1\", \"num_group2\"]:\n                df = df.with_columns(pl.col(col).cast(pl.Int64))\n            elif col in [\"date_decision\"]:\n                df = df.with_columns(pl.col(col).cast(pl.Date))\n            elif col[-1] in (\"P\", \"A\"):\n                df = df.with_columns(pl.col(col).cast(pl.Float64))\n            elif col[-1] in (\"M\",):\n                df = df.with_columns(pl.col(col).cast(pl.String))\n            elif col[-1] in (\"D\",):\n                df = df.with_columns(pl.col(col).cast(pl.Date))\n        return df\n\n    def handle_dates(df):\n        for col in df.columns:\n            if col[-1] in (\"D\",):\n                df = df.with_columns(pl.col(col) - pl.col(\"date_decision\"))  #!!?\n                df = df.with_columns(pl.col(col).dt.total_days()) # t - t-1\n        df = df.drop(\"date_decision\", \"MONTH\")\n        return df\n\n    def filter_cols(df):\n        for col in df.columns:\n            if col not in [\"target\", \"case_id\", \"WEEK_NUM\"]:\n                isnull = df[col].is_null().mean()\n                if isnull > 0.7:\n                    df = df.drop(col)\n        \n        for col in df.columns:\n            if (col not in [\"target\", \"case_id\", \"WEEK_NUM\"]) & (df[col].dtype == pl.String):\n                freq = df[col].n_unique()\n                if (freq == 1) | (freq > 200):\n                    df = df.drop(col)\n        \n        return df\n\n\nclass Aggregator:\n    #Please add or subtract features yourself, be aware that too many features will take up too much space.\n    def num_expr(df):\n        cols = [col for col in df.columns if col[-1] in (\"P\", \"A\")]\n        expr_max = [pl.max(col).alias(f\"max_{col}\") for col in cols]\n        \n        expr_last = [pl.last(col).alias(f\"last_{col}\") for col in cols]\n        #expr_first = [pl.first(col).alias(f\"first_{col}\") for col in cols]\n        expr_mean = [pl.mean(col).alias(f\"mean_{col}\") for col in cols]\n        return expr_max +expr_last+expr_mean\n    \n    def date_expr(df):\n        cols = [col for col in df.columns if col[-1] in (\"D\")]\n        expr_max = [pl.max(col).alias(f\"max_{col}\") for col in cols]\n        #expr_min = [pl.min(col).alias(f\"min_{col}\") for col in cols]\n        expr_last = [pl.last(col).alias(f\"last_{col}\") for col in cols]\n        #expr_first = [pl.first(col).alias(f\"first_{col}\") for col in cols]\n        expr_mean = [pl.mean(col).alias(f\"mean_{col}\") for col in cols]\n        return  expr_max +expr_last+expr_mean\n    \n    def str_expr(df):\n        cols = [col for col in df.columns if col[-1] in (\"M\",)]\n        expr_max = [pl.max(col).alias(f\"max_{col}\") for col in cols]\n        #expr_min = [pl.min(col).alias(f\"min_{col}\") for col in cols]\n        expr_last = [pl.last(col).alias(f\"last_{col}\") for col in cols]\n        #expr_first = [pl.first(col).alias(f\"first_{col}\") for col in cols]\n        #expr_count = [pl.count(col).alias(f\"count_{col}\") for col in cols]\n        return  expr_max +expr_last#+expr_count\n    \n    def other_expr(df):\n        cols = [col for col in df.columns if col[-1] in (\"T\", \"L\")]\n        expr_max = [pl.max(col).alias(f\"max_{col}\") for col in cols]\n        #expr_min = [pl.min(col).alias(f\"min_{col}\") for col in cols]\n        expr_last = [pl.last(col).alias(f\"last_{col}\") for col in cols]\n        #expr_first = [pl.first(col).alias(f\"first_{col}\") for col in cols]\n        return  expr_max +expr_last\n    \n    def count_expr(df):\n        cols = [col for col in df.columns if \"num_group\" in col]\n        expr_max = [pl.max(col).alias(f\"max_{col}\") for col in cols] \n        #expr_min = [pl.min(col).alias(f\"min_{col}\") for col in cols]\n        expr_last = [pl.last(col).alias(f\"last_{col}\") for col in cols]\n        #expr_first = [pl.first(col).alias(f\"first_{col}\") for col in cols]\n        return  expr_max +expr_last\n    \n    def get_exprs(df):\n        exprs = Aggregator.num_expr(df) + \\\n                Aggregator.date_expr(df) + \\\n                Aggregator.str_expr(df) + \\\n                Aggregator.other_expr(df) + \\\n                Aggregator.count_expr(df)\n\n        return exprs\n\ndef read_file(path, depth=None):\n    df = pl.read_parquet(path)\n    df = df.pipe(Pipeline.set_table_dtypes)\n    if depth in [1,2]:\n        df = df.group_by(\"case_id\").agg(Aggregator.get_exprs(df)) \n    return df\n\ndef read_files(regex_path, depth=None):\n    chunks = []\n    \n    for path in glob(str(regex_path)):\n        df = pl.read_parquet(path)\n        df = df.pipe(Pipeline.set_table_dtypes)\n        if depth in [1, 2]:\n            df = df.group_by(\"case_id\").agg(Aggregator.get_exprs(df))\n        chunks.append(df)\n    \n    df = pl.concat(chunks, how=\"vertical_relaxed\")\n    df = df.unique(subset=[\"case_id\"])\n    return df\n\ndef feature_eng(df_base, depth_0, depth_1, depth_2):\n    df_base = (\n        df_base\n        .with_columns(\n            month_decision = pl.col(\"date_decision\").dt.month(),\n            weekday_decision = pl.col(\"date_decision\").dt.weekday(),\n        )\n    )\n    for i, df in enumerate(depth_0 + depth_1 + depth_2):\n        df_base = df_base.join(df, how=\"left\", on=\"case_id\", suffix=f\"_{i}\")\n    df_base = df_base.pipe(Pipeline.handle_dates)\n    return df_base\n\ndef to_pandas(df_data, cat_cols=None):\n    df_data = df_data.to_pandas()\n    if cat_cols is None:\n        cat_cols = list(df_data.select_dtypes(\"object\").columns)\n    df_data[cat_cols] = df_data[cat_cols].astype(\"category\")\n    return df_data, cat_cols\n\ndef reduce_mem_usage(df):\n    \"\"\" iterate through all the columns of a dataframe and modify the data type\n        to reduce memory usage.        \n    \"\"\"\n    start_mem = df.memory_usage().sum() / 1024**2\n    print('Memory usage of dataframe is {:.2f} MB'.format(start_mem))\n    \n    for col in df.columns:\n        col_type = df[col].dtype\n        if str(col_type)==\"category\":\n            continue\n        \n        if col_type != object:\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.int64)  \n            else:\n                if c_min > np.finfo(np.float16).min and c_max < np.finfo(np.float16).max:\n                    df[col] = df[col].astype(np.float16)\n                elif c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max:\n                    df[col] = df[col].astype(np.float32)\n                else:\n                    df[col] = df[col].astype(np.float64)\n        else:\n            continue\n    end_mem = df.memory_usage().sum() / 1024**2\n    print('Memory usage after optimization is: {:.2f} MB'.format(end_mem))\n    print('Decreased by {:.1f}%'.format(100 * (start_mem - end_mem) / start_mem))\n    \n    return df","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ROOT            = Path(\"/kaggle/input/home-credit-credit-risk-model-stability\")\n\nTRAIN_DIR       = ROOT / \"parquet_files\" / \"train\"\nTEST_DIR        = ROOT / \"parquet_files\" / \"test\"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\ndata_store = {\n    \"df_base\": read_file(TRAIN_DIR / \"train_base.parquet\"),\n    \"depth_0\": [\n        read_file(TRAIN_DIR / \"train_static_cb_0.parquet\"),\n        read_files(TRAIN_DIR / \"train_static_0_*.parquet\"),\n    ],\n    \"depth_1\": [\n        read_files(TRAIN_DIR / \"train_applprev_1_*.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_tax_registry_a_1.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_tax_registry_b_1.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_tax_registry_c_1.parquet\", 1),\n        read_files(TRAIN_DIR / \"train_credit_bureau_a_1_*.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_credit_bureau_b_1.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_other_1.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_person_1.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_deposit_1.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_debitcard_1.parquet\", 1),\n    ],\n    \"depth_2\": [\n        read_file(TRAIN_DIR / \"train_credit_bureau_b_2.parquet\", 2),\n        read_files(TRAIN_DIR / \"train_credit_bureau_a_2_*.parquet\", 2),\n        read_file(TRAIN_DIR / \"train_applprev_2.parquet\", 2),\n        read_file(TRAIN_DIR / \"train_person_2.parquet\", 2)\n    ]\n}","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\ndf_train = feature_eng(**data_store)\nprint(\"train data shape:\\t\", df_train.shape)\ndel data_store\ngc.collect()\ndf_train = df_train.pipe(Pipeline.filter_cols)\ndf_train, cat_cols = to_pandas(df_train)\ndf_train = reduce_mem_usage(df_train)\nprint(\"train data shape:\\t\", df_train.shape)\nnums=df_train.select_dtypes(exclude='category').columns\nfrom itertools import combinations, permutations\n#df_train=df_train[nums]\nnans_df = df_train[nums].isna()\nnans_groups={}\nfor col in nums:\n    cur_group = nans_df[col].sum()\n    try:\n        nans_groups[cur_group].append(col)\n    except:\n        nans_groups[cur_group]=[col]\ndel nans_df; x=gc.collect()\n\ndef reduce_group(grps):\n    use = []\n    for g in grps:\n        mx = 0; vx = g[0]\n        for gg in g:\n            n = df_train[gg].nunique()\n            if n>mx:\n                mx = n\n                vx = gg\n            #print(str(gg)+'-'+str(n),', ',end='')\n        use.append(vx)\n        #print()\n    print('Use these',use)\n    return use\n\ndef group_columns_by_correlation(matrix, threshold=0.8):\n    # 计算列之间的相关性\n    correlation_matrix = matrix.corr()\n\n    # 分组列\n    groups = []\n    remaining_cols = list(matrix.columns)\n    while remaining_cols:\n        col = remaining_cols.pop(0)\n        group = [col]\n        correlated_cols = [col]\n        for c in remaining_cols:\n            if correlation_matrix.loc[col, c] >= threshold:\n                group.append(c)\n                correlated_cols.append(c)\n        groups.append(group)\n        remaining_cols = [c for c in remaining_cols if c not in correlated_cols]\n    \n    return groups\n\nuses=[]\nfor k,v in nans_groups.items():\n    if len(v)>1:\n            Vs = nans_groups[k]\n            #cross_features=list(combinations(Vs, 2))\n            #make_corr(Vs)\n            grps= group_columns_by_correlation(df_train[Vs], threshold=0.8)\n            use=reduce_group(grps)\n            uses=uses+use\n            #make_corr(use)\n    else:\n        uses=uses+v\n    print('####### NAN count =',k)\nprint(uses)\nprint(len(uses))\nuses=uses+list(df_train.select_dtypes(include='category').columns)\nprint(len(uses))\ndf_train=df_train[uses]","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample = pd.read_csv(ROOT / \"sample_submission.csv\")\ndevice='gpu'\n#n_samples=200000\nn_est=6000\nDRY_RUN = True if sample.shape[0] == 10 else False   \nif DRY_RUN:\n    device='cpu'\n    df_train = df_train.iloc[:50000]\n    #n_samples=10000\n    n_est=600\nprint(device)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data_store = {\n    \"df_base\": read_file(TEST_DIR / \"test_base.parquet\"),\n    \"depth_0\": [\n        read_file(TEST_DIR / \"test_static_cb_0.parquet\"),\n        read_files(TEST_DIR / \"test_static_0_*.parquet\"),\n    ],\n    \"depth_1\": [\n        read_files(TEST_DIR / \"test_applprev_1_*.parquet\", 1),\n        read_file(TEST_DIR / \"test_tax_registry_a_1.parquet\", 1),\n        read_file(TEST_DIR / \"test_tax_registry_b_1.parquet\", 1),\n        read_file(TEST_DIR / \"test_tax_registry_c_1.parquet\", 1),\n        read_files(TEST_DIR / \"test_credit_bureau_a_1_*.parquet\", 1),\n        read_file(TEST_DIR / \"test_credit_bureau_b_1.parquet\", 1),\n        read_file(TEST_DIR / \"test_other_1.parquet\", 1),\n        read_file(TEST_DIR / \"test_person_1.parquet\", 1),\n        read_file(TEST_DIR / \"test_deposit_1.parquet\", 1),\n        read_file(TEST_DIR / \"test_debitcard_1.parquet\", 1),\n    ],\n    \"depth_2\": [\n        read_file(TEST_DIR / \"test_credit_bureau_b_2.parquet\", 2),\n        read_files(TEST_DIR / \"test_credit_bureau_a_2_*.parquet\", 2),\n        read_file(TEST_DIR / \"test_applprev_2.parquet\", 2),\n        read_file(TEST_DIR / \"test_person_2.parquet\", 2)\n    ]\n}","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test = feature_eng(**data_store)\nprint(\"test data shape:\\t\", df_test.shape)\ndel data_store\ngc.collect()\ndf_test = df_test.select([col for col in df_train.columns if col != \"target\"])\nprint(\"train data shape:\\t\", df_train.shape)\nprint(\"test data shape:\\t\", df_test.shape)\n\ndf_test, cat_cols = to_pandas(df_test, cat_cols)\ndf_test = reduce_mem_usage(df_test)\n\ngc.collect()","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y = df_train[\"target\"]\nweeks = df_train[\"WEEK_NUM\"]\ndf_train= df_train.drop(columns=[\"target\", \"case_id\", \"WEEK_NUM\"])\ncv = StratifiedGroupKFold(n_splits=5, shuffle=False)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train[cat_cols] = df_train[cat_cols].astype(str)\ndf_test[cat_cols] = df_test[cat_cols].astype(str)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"params = {\n    \"boosting_type\": \"gbdt\",\n    \"objective\": \"binary\",\n    \"metric\": \"auc\",\n    \"max_depth\": 10,  \n    \"learning_rate\": 0.02,\n    \"n_estimators\": 3000,  \n    \"colsample_bytree\": 0.8,\n    \"colsample_bynode\": 0.8,\n    \"verbose\": -1,\n    \"random_state\": 0,\n    \"reg_alpha\": 0.1,\n    \"reg_lambda\": 10,\n    \"extra_trees\":True,\n    'num_leaves':64,\n    \"device\": device, \n    \"verbose\": -1,\n}","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\nfrom catboost import CatBoostClassifier, Pool\n\nfitted_models_cat = []\nfitted_models_lgb = []\n\ncv_scores_cat = []\ncv_scores_lgb = []\n\n\nfor idx_train, idx_valid in cv.split(df_train, y, groups=weeks):#\n    X_train, y_train = df_train.iloc[idx_train], y.iloc[idx_train]# \n    X_valid, y_valid = df_train.iloc[idx_valid], y.iloc[idx_valid]\n    train_pool = Pool(X_train, y_train,cat_features=cat_cols)\n    val_pool = Pool(X_valid, y_valid,cat_features=cat_cols)\n    clf = CatBoostClassifier(\n    eval_metric='AUC',\n    task_type='GPU',\n    learning_rate=0.03,\n    iterations=n_est)\n    random_seed=42\n    clf.fit(train_pool, eval_set=val_pool,verbose=300)\n    fitted_models_cat.append(clf)\n    y_pred_valid = clf.predict_proba(X_valid)[:,1]\n    auc_score = roc_auc_score(y_valid, y_pred_valid)\n    cv_scores_cat.append(auc_score)\n    \n    \n    X_train[cat_cols] = X_train[cat_cols].astype(\"category\")\n    X_valid[cat_cols] = X_valid[cat_cols].astype(\"category\")\n    \n    model = lgb.LGBMClassifier(**params)\n    model.fit(\n        X_train, y_train,\n        eval_set = [(X_valid, y_valid)],\n        callbacks = [lgb.log_evaluation(200), lgb.early_stopping(100)] )\n    \n    fitted_models_lgb.append(model)\n    y_pred_valid = model.predict_proba(X_valid)[:,1]\n    auc_score = roc_auc_score(y_valid, y_pred_valid)\n    cv_scores_lgb.append(auc_score)\n    \n    \nprint(\"CV AUC scores: \", cv_scores_cat)\nprint(\"Maximum CV AUC score: \", max(cv_scores_cat))\n\n\nprint(\"CV AUC scores: \", cv_scores_lgb)\nprint(\"Maximum CV AUC score: \", max(cv_scores_lgb))","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, LSTM, Dropout\nimport xgboost as xgb\nfrom sklearn.model_selection import StratifiedGroupKFold\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.preprocessing import LabelEncoder\n","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### DNN Model","metadata":{}},{"cell_type":"code","source":"# # Function to build DNN model\n# def build_dnn(input_shape):\n#     model = Sequential()\n#     model.add(Dense(128, input_dim=input_shape, activation='relu'))\n#     model.add(Dropout(0.5))\n#     model.add(Dense(64, activation='relu'))\n#     model.add(Dropout(0.5))\n#     model.add(Dense(1, activation='sigmoid'))\n#     model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['AUC'])\n#     return model","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### LSTM Model","metadata":{}},{"cell_type":"code","source":"\n# # Function to build LSTM model\n# def build_lstm(input_shape):\n#     model = Sequential()\n#     model.add(LSTM(128, input_shape=input_shape, return_sequences=True))\n#     model.add(Dropout(0.5))\n#     model.add(LSTM(64, return_sequences=False))\n#     model.add(Dropout(0.5))\n#     model.add(Dense(1, activation='sigmoid'))\n#     model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['AUC'])\n#     return model","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### XGBoost Model","metadata":{}},{"cell_type":"code","source":"# Function to train XGBoost model\ndef train_xgboost(X_train, y_train, X_valid, y_valid):\n    params = {\n        'objective': 'binary:logistic',\n        'eval_metric': 'auc',\n        'max_depth': 10,\n        'learning_rate': 0.02,\n        'n_estimators': 3000,\n        'colsample_bytree': 0.8,\n        'reg_alpha': 0.1,\n        'reg_lambda': 10,\n        'random_state': 0\n    }\n    dtrain = xgb.DMatrix(X_train, label=y_train)\n    dvalid = xgb.DMatrix(X_valid, label=y_valid)\n    watchlist = [(dtrain, 'train'), (dvalid, 'eval')]\n    model = xgb.train(params, dtrain, num_boost_round=3000, evals=watchlist, early_stopping_rounds=100, verbose_eval=200)\n    return model","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Ensure categorical columns are properly encoded\ndef encode_categorical(df, cat_cols):\n    for col in cat_cols:\n        le = LabelEncoder()\n        df[col] = le.fit_transform(df[col])\n    return df\n\n# Convert DataFrame to numpy arrays\ndef df_to_numpy(df):\n    return df.values\n","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Cross-validation setup\ncv = StratifiedGroupKFold(n_splits=5, shuffle=False)\n# fitted_models_dnn = []\n# fitted_models_lstm = []\nfitted_models_xgb = []\n# cv_scores_dnn = []\n# cv_scores_lstm = []\ncv_scores_xgb = []","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Encode categorical columns\ndf_train = encode_categorical(df_train, cat_cols)\ndf_test = encode_categorical(df_test, cat_cols)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# for idx_train, idx_valid in cv.split(df_train, y, groups=weeks):\n#     X_train, y_train = df_to_numpy(df_train.iloc[idx_train]), y.iloc[idx_train]\n#     X_valid, y_valid = df_to_numpy(df_train.iloc[idx_valid]), y.iloc[idx_valid]\n\n#     # DNN\n#     dnn = build_dnn(X_train.shape[1])\n#     dnn.fit(X_train, y_train, validation_data=(X_valid, y_valid), epochs=10, batch_size=32, verbose=2)\n#     y_pred_valid = dnn.predict(X_valid).ravel()\n#     auc_score = roc_auc_score(y_valid, y_pred_valid)\n#     cv_scores_dnn.append(auc_score)\n#     fitted_models_dnn.append(dnn)\n","metadata":{"scrolled":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# for idx_train, idx_valid in cv.split(df_train, y, groups=weeks):\n#     X_train, y_train = df_to_numpy(df_train.iloc[idx_train]), y.iloc[idx_train]\n#     X_valid, y_valid = df_to_numpy(df_train.iloc[idx_valid]), y.iloc[idx_valid]\n# # LSTM\n#     X_train_lstm = np.expand_dims(X_train, axis=2)\n#     X_valid_lstm = np.expand_dims(X_valid, axis=2)\n#     lstm = build_lstm((X_train_lstm.shape[1], 1))\n#     lstm.fit(X_train_lstm, y_train, validation_data=(X_valid_lstm, y_valid), epochs=10, batch_size=32, verbose=2)\n#     y_pred_valid = lstm.predict(X_valid_lstm).ravel()\n#     auc_score = roc_auc_score(y_valid, y_pred_valid)\n#     cv_scores_lstm.append(auc_score)\n#     fitted_models_lstm.append(lstm)","metadata":{"execution":{"iopub.status.busy":"2024-05-18T14:22:01.883701Z","iopub.execute_input":"2024-05-18T14:22:01.884348Z","iopub.status.idle":"2024-05-18T14:22:01.888689Z","shell.execute_reply.started":"2024-05-18T14:22:01.884305Z","shell.execute_reply":"2024-05-18T14:22:01.887614Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for idx_train, idx_valid in cv.split(df_train, y, groups=weeks):\n    X_train, y_train = df_to_numpy(df_train.iloc[idx_train]), y.iloc[idx_train]\n    X_valid, y_valid = df_to_numpy(df_train.iloc[idx_valid]), y.iloc[idx_valid]\n\n# XGBoost\n    model = train_xgboost(X_train, y_train, X_valid, y_valid)\n    dvalid = xgb.DMatrix(X_valid)\n    y_pred_valid = model.predict(dvalid)\n    auc_score = roc_auc_score(y_valid, y_pred_valid)\n    cv_scores_xgb.append(auc_score)\n    fitted_models_xgb.append(model)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# print(\"CV AUC scores for DNN: \", cv_scores_dnn)\n# print(\"Maximum CV AUC score for DNN: \", max(cv_scores_dnn))","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n# print(\"CV AUC scores for LSTM: \", cv_scores_lstm)\n# print(\"Maximum CV AUC score for LSTM: \", max(cv_scores_lstm))","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"CV AUC scores for XGBoost: \", cv_scores_xgb)\nprint(\"Maximum CV AUC score for XGBoost: \", max(cv_scores_xgb))","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# import numpy as np\n# from sklearn.metrics import roc_auc_score\n# from sklearn.model_selection import GroupKFold\n# from tensorflow.keras.models import Sequential\n# from tensorflow.keras.layers import LSTM, Dense\n# from tensorflow.keras.optimizers import Adam\n# from sklearn.preprocessing import StandardScaler\n\n# # 假设 df_train, y 和 weeks 是已经定义好的数据\n# # cv 是 GroupKFold 实例\n# cv = GroupKFold(n_splits=5)\n\n# def df_to_numpy(df):\n#     return df.values\n\n# def build_lstm(input_shape):\n#     model = Sequential()\n#     model.add(LSTM(50, input_shape=input_shape))\n#     model.add(Dense(1, activation='sigmoid'))\n#     model.compile(optimizer=Adam(learning_rate=0.001), loss='binary_crossentropy', metrics=['AUC'])\n#     return model\n\n# cv_scores_lstm = []\n# fitted_models_lstm = []\n\n# for idx_train, idx_valid in cv.split(df_train, y, groups=weeks):\n#     X_train, y_train = df_to_numpy(df_train.iloc[idx_train]), y.iloc[idx_train]\n#     X_valid, y_valid = df_to_numpy(df_train.iloc[idx_valid]), y.iloc[idx_valid]\n    \n#     # 检查并移除NaN值\n#     if np.isnan(X_train).any() or np.isnan(X_valid).any():\n#         raise ValueError(\"数据集中包含NaN值，请检查数据预处理步骤。\")\n    \n#     # 数据标准化\n#     scaler = StandardScaler()\n#     X_train = scaler.fit_transform(X_train)\n#     X_valid = scaler.transform(X_valid)\n    \n#     # 检查标签数据，确保没有问题\n#     assert len(np.unique(y_train)) > 1, \"训练标签中只有一个类别\"\n    \n#     # LSTM\n#     X_train_lstm = np.expand_dims(X_train, axis=2)\n#     X_valid_lstm = np.expand_dims(X_valid, axis=2)\n#     lstm = build_lstm((X_train_lstm.shape[1], 1))\n    \n#     # 训练模型，捕捉异常\n#     try:\n#         lstm.fit(X_train_lstm, y_train, validation_data=(X_valid_lstm, y_valid), epochs=10, batch_size=32, verbose=2)\n#     except Exception as e:\n#         print(f\"训练过程中出现异常：{e}\")\n#         continue\n    \n#     y_pred_valid = lstm.predict(X_valid_lstm).ravel()\n    \n#     try:\n#         auc_score = roc_auc_score(y_valid, y_pred_valid)\n#     except ValueError as e:\n#         print(f\"AUC计算过程中出现异常：{e}\")\n#         auc_score = 0.0\n    \n#     cv_scores_lstm.append(auc_score)\n#     fitted_models_lstm.append(lstm)\n\n# print(f\"交叉验证AUC分数：{cv_scores_lstm}\")\n","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Define gini_stability function\ndef gini_stability(base, w_fallingrate=88.0, w_resstd=-0.5):\n    gini_in_time = base.loc[:, [\"WEEK_NUM\", \"target\", \"score\"]]\\\n        .sort_values(\"WEEK_NUM\")\\\n        .groupby(\"WEEK_NUM\")[[\"target\", \"score\"]]\\\n        .apply(lambda x: 2*roc_auc_score(x[\"target\"], x[\"score\"])-1).tolist()\n    \n    x = np.arange(len(gini_in_time))\n    y = gini_in_time\n    a, b = np.polyfit(x, y, 1)\n    y_hat = a*x + b\n    residuals = y - y_hat\n    res_std = np.std(residuals)\n    avg_gini = np.mean(gini_in_time)\n    return avg_gini + w_fallingrate * min(0, a) + w_resstd * res_std\n","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Generate predictions for train, valid, and test sets\ndef generate_predictions(model, X):\n    if isinstance(model, Sequential):\n        return model.predict(X).ravel()\n    elif isinstance(model, xgb.Booster):\n        dmatrix = xgb.DMatrix(X)\n        return model.predict(dmatrix)\n\nbase_train = df_train.copy()\nbase_valid = df_train.copy()  # assuming you have separate validation data\nbase_test = df_test.copy()\n\n# Assuming you have the WEEK_NUM and target columns in your train and test sets\nbase_train[\"WEEK_NUM\"] = weeks\nbase_train[\"target\"] = y\n\n# Assuming the same WEEK_NUM and target columns exist in base_valid and base_test\n# Replace these with actual data if necessary\n\n# Calculate the stability score for each model\nstability_scores = {\n#        \"DNN\": [],\n#     \"LSTM\": [],\n    \"XGBoost\": []\n}\n\n# for model in fitted_models_dnn:\n#     base_train[\"score\"] = generate_predictions(model, df_to_numpy(df_train))\n#     stability_score_train = gini_stability(base_train)\n#     stability_scores[\"DNN\"].append(stability_score_train)\n\n# for model in fitted_models_lstm:\n#     base_train[\"score\"] = generate_predictions(model, np.expand_dims(df_to_numpy(df_train), axis=2))\n#     stability_score_train = gini_stability(base_train)\n#     stability_scores[\"LSTM\"].append(stability_score_train)\n\nfor model in fitted_models_xgb:\n    base_train[\"score\"] = generate_predictions(model, df_to_numpy(df_train))\n    stability_score_train = gini_stability(base_train)\n    stability_scores[\"XGBoost\"].append(stability_score_train)\n\n# print(\"Stability scores for DNN: \", stability_scores[\"DNN\"])\n# print(\"Maximum stability score for DNN: \", max(stability_scores[\"DNN\"]))\n\n# print(\"Stability scores for LSTM: \", stability_scores[\"LSTM\"])\n# print(\"Maximum stability score for LSTM: \", max(stability_scores[\"LSTM\"]))\n\nprint(\"Stability scores for XGBoost: \", stability_scores[\"XGBoost\"])\nprint(\"Maximum stability score for XGBoost: \", max(stability_scores[\"XGBoost\"]))","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport lightgbm as lgb\nimport xgboost as xgb\nfrom sklearn.base import BaseEstimator, RegressorMixin\nfrom sklearn.metrics import roc_auc_score\n\nclass VotingModel(BaseEstimator, RegressorMixin):\n    def __init__(self, estimators):\n        super().__init__()\n        self.estimators = estimators\n        \n    def fit(self, X, y=None):\n        for estimator in self.estimators:\n            estimator.fit(X, y)\n        return self\n    \n    def predict(self, X):\n        y_preds = [estimator.predict(X) for estimator in self.estimators]\n        return np.mean(y_preds, axis=0)\n    \n    def predict_proba(self, X):\n        y_preds = []\n        for estimator in self.estimators:\n            if isinstance(estimator, lgb.LGBMClassifier) or isinstance(estimator, xgb.XGBClassifier):\n                y_preds.append(estimator.predict_proba(X))\n            else:\n                y_preds.append(estimator.predict_proba(X))\n        return np.mean(y_preds, axis=0)\n","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 训练LightGBM模型\nparams_lgb = {\n    \"boosting_type\": \"gbdt\",\n    \"objective\": \"binary\",\n    \"metric\": \"auc\",\n    \"max_depth\": 10,  \n    \"learning_rate\": 0.02,\n    \"n_estimators\": 3000,  \n    \"colsample_bytree\": 0.8,\n    \"colsample_bynode\": 0.8,\n    \"verbose\": -1,\n    \"random_state\": 0,\n    \"reg_alpha\": 0.1,\n    \"reg_lambda\": 10,\n    \"extra_trees\": True,\n    \"num_leaves\": 64,\n}\n\nfitted_models_lgb = []\ncv = StratifiedGroupKFold(n_splits=5, shuffle=False)\n\nfor idx_train, idx_valid in cv.split(df_train, y, groups=weeks):\n    X_train, y_train = df_train.iloc[idx_train], y.iloc[idx_train]\n    X_valid, y_valid = df_train.iloc[idx_valid], y.iloc[idx_valid]\n\n    model_lgb = lgb.LGBMClassifier(**params_lgb)\n    model_lgb.fit(\n        X_train, y_train,\n        eval_set=[(X_valid, y_valid)],\n        callbacks=[lgb.log_evaluation(200), lgb.early_stopping(100)]\n    )\n    fitted_models_lgb.append(model_lgb)\n\n# 训练XGBoost模型\nparams_xgb = {\n    'objective': 'binary:logistic',\n    'eval_metric': 'auc',\n    'max_depth': 10,\n    'learning_rate': 0.02,\n    'n_estimators': 3000,\n    'colsample_bytree': 0.8,\n    'reg_alpha': 0.1,\n    'reg_lambda': 10,\n    'random_state': 0\n}\n\nfitted_models_xgb = []\n\nfor idx_train, idx_valid in cv.split(df_train, y, groups=weeks):\n    X_train, y_train = df_train.iloc[idx_train], y.iloc[idx_train]\n    X_valid, y_valid = df_train.iloc[idx_valid], y.iloc[idx_valid]\n\n    model_xgb = xgb.XGBClassifier(**params_xgb)\n    model_xgb.fit(X_train, y_train, eval_set=[(X_valid, y_valid)], early_stopping_rounds=100, verbose=200)\n    fitted_models_xgb.append(model_xgb)\n\n# 创建投票模型\nmodel = VotingModel(fitted_models_lgb + fitted_models_xgb)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test = df_test.drop(columns=[\"WEEK_NUM\"])\ndf_test = df_test.set_index(\"case_id\")\n\n\ny_pred = pd.Series(model.predict_proba(df_test)[:, 1], index=df_test.index)\ndf_subm = pd.read_csv(ROOT / \"sample_submission.csv\")\ndf_subm = df_subm.set_index(\"case_id\")\n\ndf_subm[\"score\"] = y_pred\ndf_subm.to_csv(\"submission.csv\")\ndf_subm","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}