{"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-02-27T13:59:07.980360Z","iopub.execute_input":"2023-02-27T13:59:07.980841Z","iopub.status.idle":"2023-02-27T13:59:07.989819Z","shell.execute_reply.started":"2023-02-27T13:59:07.980797Z","shell.execute_reply":"2023-02-27T13:59:07.988703Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tqdm.notebook import tqdm\nfrom matplotlib import pyplot as plt\nimport seaborn as sns\nimport lightgbm as lgb\nimport multiprocessing\nimport time\nimport gc\n\nfrom sklearn.preprocessing import LabelEncoder, MinMaxScaler, StandardScaler\nfrom sklearn.model_selection import KFold, ShuffleSplit, StratifiedKFold\nfrom sklearn.metrics import roc_auc_score, log_loss","metadata":{"execution":{"iopub.status.busy":"2023-02-27T14:05:13.517402Z","iopub.execute_input":"2023-02-27T14:05:13.517885Z","iopub.status.idle":"2023-02-27T14:05:13.525435Z","shell.execute_reply.started":"2023-02-27T14:05:13.517842Z","shell.execute_reply":"2023-02-27T14:05:13.523951Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def reduce_mem(df):\n    start_mem = df.memory_usage().sum() / 1024 ** 2\n    for col in df.columns:\n        col_type = df[col].dtypes\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    end_mem = df.memory_usage().sum() / 1024 ** 2\n    print('{:.2f} Mb, {:.2f} Mb ({:.2f} %)'.format(start_mem, end_mem, 100 * (start_mem - end_mem) / start_mem))\n    gc.collect()\n    return df\n","metadata":{"execution":{"iopub.status.busy":"2023-02-27T14:00:10.681478Z","iopub.execute_input":"2023-02-27T14:00:10.681817Z","iopub.status.idle":"2023-02-27T14:00:10.698189Z","shell.execute_reply.started":"2023-02-27T14:00:10.681784Z","shell.execute_reply":"2023-02-27T14:00:10.696732Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df = pd.read_csv('/kaggle/input/deepshare-playground-series2/train_data.csv')\ntest_df = pd.read_csv('/kaggle/input/deepshare-playground-series2/test_data.csv')\n\n# label转成int32\ntrain_df['label'] = train_df['label'].astype('int32')","metadata":{"execution":{"iopub.status.busy":"2023-02-27T13:59:12.140644Z","iopub.execute_input":"2023-02-27T13:59:12.141856Z","iopub.status.idle":"2023-02-27T14:00:04.264811Z","shell.execute_reply.started":"2023-02-27T13:59:12.141797Z","shell.execute_reply":"2023-02-27T14:00:04.263381Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"num_cols  =  [f'user_fea{i}' for i in range(6,9)] \ncate_cols = ['user_id','item_id']+ [f'user_fea{i}' for i in range(1,6)] + ['item_fea1']+['user_fea9']","metadata":{"execution":{"iopub.status.busy":"2023-02-27T14:00:52.540916Z","iopub.execute_input":"2023-02-27T14:00:52.542390Z","iopub.status.idle":"2023-02-27T14:00:52.548478Z","shell.execute_reply.started":"2023-02-27T14:00:52.542341Z","shell.execute_reply":"2023-02-27T14:00:52.547210Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 把train&test拼在一起，方便后续的数据编码\ndf = pd.concat([train_df,test_df],axis=0).reset_index(drop=True)","metadata":{"execution":{"iopub.status.busy":"2023-02-27T14:00:04.267616Z","iopub.execute_input":"2023-02-27T14:00:04.268441Z","iopub.status.idle":"2023-02-27T14:00:10.680094Z","shell.execute_reply.started":"2023-02-27T14:00:04.268384Z","shell.execute_reply":"2023-02-27T14:00:10.678904Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 原生离散特征编码\nfor col in tqdm(cate_cols):\n    df[col] = df[col].fillna('-1')\n    map_dict = dict(zip(df[col].unique(), range(df[col].nunique())))\n    \n    df[col] = df[col].map(map_dict)\n    df[f'{col}_count'] = df[col].map(df[col].value_counts())","metadata":{"execution":{"iopub.status.busy":"2023-02-27T14:00:54.402287Z","iopub.execute_input":"2023-02-27T14:00:54.402776Z","iopub.status.idle":"2023-02-27T14:01:18.961698Z","shell.execute_reply.started":"2023-02-27T14:00:54.402733Z","shell.execute_reply":"2023-02-27T14:01:18.960687Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df = df.sort_values(by=['user_id','ts']).reset_index(drop=True)\nfor f in tqdm(cate_cols):\n    tmp = df[[f] + ['ts']].groupby(f)\n    # 前x次、后x次曝光到当前的时间差\n    for gap in [1,2,3,5,9]:\n        df['{}_prev{}_ts_gap'.format('_'.join(f), gap)] = tmp['ts'].shift(0) - tmp['ts'].shift(gap)\n        df['{}_next{}_ts_gap'.format('_'.join(f), gap)] = tmp['ts'].shift(-gap) - tmp['ts'].shift(0)\n\n    df = reduce_mem(df)","metadata":{"execution":{"iopub.status.busy":"2023-02-27T14:05:16.294273Z","iopub.execute_input":"2023-02-27T14:05:16.294746Z","iopub.status.idle":"2023-02-27T14:06:56.927074Z","shell.execute_reply.started":"2023-02-27T14:05:16.294702Z","shell.execute_reply":"2023-02-27T14:06:56.925611Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df = df[df['label'].notna()].reset_index(drop=True)\ntest_df = df[df['label'].isna()].reset_index(drop=True)","metadata":{"execution":{"iopub.status.busy":"2023-02-27T14:07:08.403789Z","iopub.execute_input":"2023-02-27T14:07:08.405701Z","iopub.status.idle":"2023-02-27T14:07:17.605395Z","shell.execute_reply.started":"2023-02-27T14:07:08.405585Z","shell.execute_reply":"2023-02-27T14:07:17.603718Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df.shape,test_df.shape","metadata":{"execution":{"iopub.status.busy":"2023-02-27T14:07:17.607618Z","iopub.execute_input":"2023-02-27T14:07:17.608038Z","iopub.status.idle":"2023-02-27T14:07:17.616420Z","shell.execute_reply.started":"2023-02-27T14:07:17.607997Z","shell.execute_reply":"2023-02-27T14:07:17.615028Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"drop_feature = ['ID','label','lng','lat','ts','user_tag']\nfeature = [x for x in train_df.columns if x not in drop_feature]\nprint(len(feature),feature)","metadata":{"execution":{"iopub.status.busy":"2023-02-27T14:07:41.778423Z","iopub.execute_input":"2023-02-27T14:07:41.778986Z","iopub.status.idle":"2023-02-27T14:07:41.786322Z","shell.execute_reply.started":"2023-02-27T14:07:41.778930Z","shell.execute_reply":"2023-02-27T14:07:41.785074Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"params = {'num_leaves': 63, #结果对最终效果影响较大，越大值越好，太大会出现过拟合\n          'objective': 'binary', #定义的目标函数\n          'max_depth': 8,\n          'learning_rate': 0.1,\n          \"min_sum_hessian_in_leaf\": 6,\n          \"boosting\": \"gbdt\",\n          \"feature_fraction\": 1,  #提取的特征比率\n          \"bagging_freq\": 1,\n          \"bagging_fraction\": 1,\n          \"bagging_seed\": 11,\n#           \"lambda_l1\": 0.1,             #l1正则\n          # 'lambda_l2': 0.001,     #l2正则\n          \"verbosity\": -1,\n          \"nthread\": multiprocessing.cpu_count(),                #线程数量，-1表示全部线程，线程越多，运行的速度越快\n          'metric': {'binary_logloss', 'auc'},  ##评价函数选择\n          \"random_state\": 2077, #随机数种子，可以防止每次运行的结果不一致\n          # 'device': 'gpu' ##如果安装的事gpu版本的lightgbm,可以加快运算\n          }\n\nn_fold = 5\noof_pre = np.zeros(len(train_df))\ny_pre = np.zeros(len(test_df))\n\nkf = KFold(n_splits=n_fold)\nfor fold_, (trn_idx, val_idx) in enumerate(kf.split(train_df)):\n\n    trn_data = lgb.Dataset(train_df[feature].iloc[trn_idx], label=train_df['label'].iloc[trn_idx])\n    val_data = lgb.Dataset(train_df[feature].iloc[val_idx], label=train_df['label'].iloc[val_idx])\n\n    clf = lgb.train(params,\n                    trn_data,\n                    2000,\n                    valid_sets=[trn_data, val_data],\n                    verbose_eval=50,\n                    early_stopping_rounds=50)\n    # out of fold\n    oof_pre[val_idx] = clf.predict(train_df[feature].iloc[val_idx], num_iteration=clf.best_iteration)\n\n    y_pre += clf.predict(test_df[feature], num_iteration=clf.best_iteration) / n_fold","metadata":{"execution":{"iopub.status.busy":"2023-02-27T14:07:53.454288Z","iopub.execute_input":"2023-02-27T14:07:53.454795Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"local_auc = roc_auc_score(train_df['label'], oof_pre)\nprint(f'Local AUC :{local_auc}')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"res_df = pd.DataFrame()\nres_df['ID'] = test_df['ID']\nres_df['label'] = y_pre\nres_df.to_csv('/kaggle/working/lgb-baseline.csv',index=False)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}