{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"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":"none","dataSources":[{"sourceId":71710,"databundleVersionId":7843531,"sourceType":"competition"}],"dockerImageVersionId":30673,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"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":"2024-04-01T01:40:52.907938Z","iopub.execute_input":"2024-04-01T01:40:52.908248Z","iopub.status.idle":"2024-04-01T01:40:52.916455Z","shell.execute_reply.started":"2024-04-01T01:40:52.908220Z","shell.execute_reply":"2024-04-01T01:40:52.915370Z"},"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 gc\nimport time\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\nfrom lightgbm import log_evaluation, early_stopping","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def reduce_mem_usage(df, verbose=True):\n    numerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']\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 in numerics:\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                c_prec = df[col].apply(lambda x: np.finfo(x).precision).max()\n                if c_min > np.finfo(np.float16).min and c_max < np.finfo(np.float16).max and c_prec == np.finfo(np.float16).precision:\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 and c_prec == np.finfo(np.float32).precision:\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    if verbose: print('Mem. usage decreased to {:5.2f} Mb ({:.1f}% reduction)'.format(end_mem, 100 * (start_mem - end_mem) / start_mem))\n    return df","metadata":{"execution":{"iopub.status.busy":"2024-04-01T01:40:52.929258Z","iopub.execute_input":"2024-04-01T01:40:52.929592Z","iopub.status.idle":"2024-04-01T01:40:52.947021Z","shell.execute_reply.started":"2024-04-01T01:40:52.929568Z","shell.execute_reply":"2024-04-01T01:40:52.945825Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df = pd.read_csv('/kaggle/input/deepshare-basic-competition/train_data.csv')\ntest_df = pd.read_csv('/kaggle/input/deepshare-basic-competition/test_data.csv')\n\n# label转成int32\ntrain_df['label'] = train_df['label'].astype('int32')","metadata":{"execution":{"iopub.status.busy":"2024-04-01T01:41:20.324238Z","iopub.execute_input":"2024-04-01T01:41:20.325117Z","iopub.status.idle":"2024-04-01T01:42:04.571900Z","shell.execute_reply.started":"2024-04-01T01:41:20.325080Z","shell.execute_reply":"2024-04-01T01:42:04.570531Z"},"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":"2024-04-01T01:42:04.573913Z","iopub.execute_input":"2024-04-01T01:42:04.574337Z","iopub.status.idle":"2024-04-01T01:42:08.558582Z","shell.execute_reply.started":"2024-04-01T01:42:04.574294Z","shell.execute_reply":"2024-04-01T01:42:08.557202Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df = reduce_mem_usage(df)","metadata":{"execution":{"iopub.status.busy":"2024-04-01T01:42:08.560925Z","iopub.execute_input":"2024-04-01T01:42:08.561831Z","iopub.status.idle":"2024-04-01T01:45:37.153406Z","shell.execute_reply.started":"2024-04-01T01:42:08.561789Z","shell.execute_reply":"2024-04-01T01:45:37.152131Z"},"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":"2024-04-01T01:45:37.156440Z","iopub.execute_input":"2024-04-01T01:45:37.156790Z","iopub.status.idle":"2024-04-01T01:45:37.162977Z","shell.execute_reply.started":"2024-04-01T01:45:37.156762Z","shell.execute_reply":"2024-04-01T01:45:37.161848Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 离散特征编码","metadata":{}},{"cell_type":"code","source":"# 原生离散特征编码\nfor col in tqdm(cate_cols):\n    map_dict = dict(zip(df[col].unique(), range(df[col].nunique())))\n    # label enc\n    df[col] = df[col].map(map_dict)\n    # count enc\n    df[f'{col}_count'] = df[col].map(df[col].value_counts())\ndf = reduce_mem_usage(df)","metadata":{"execution":{"iopub.status.busy":"2024-04-01T01:45:37.164566Z","iopub.execute_input":"2024-04-01T01:45:37.164943Z","iopub.status.idle":"2024-04-01T01:49:54.744606Z","shell.execute_reply.started":"2024-04-01T01:45:37.164903Z","shell.execute_reply":"2024-04-01T01:49:54.743473Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 交叉特征","metadata":{}},{"cell_type":"code","source":"item_cate_feature = ['item_fea1']\nuser_cate_feature = [f'user_fea{i}' for i in range(1,6)] + ['user_fea9']\ncross_feature_pair=[\n    ['user_id','item_id']\n]\n# cross_feature_pair += [['user_id',fea] for fea in item_cate_feature]\n# cross_feature_pair += [['item_id',fea] for fea in user_cate_feature]\n\nfor [f1,f2] in tqdm(cross_feature_pair):\n    df[f'cross_{f1}_{f2}'] = df[f1].astype('str') + '_' + df[f2].astype('str')\n    \n    df[f'cross_{f1}_{f2}_count'] = df[f'cross_{f1}_{f2}'].map(df[f'cross_{f1}_{f2}'].value_counts())\n    \n    df[f'cross_{f1}_{f2}/{f1}'] = df[f'cross_{f1}_{f2}_count'] / (df[f'{f1}_count']+df[f'{f1}_count'].mean())\n    df[f'cross_{f1}_{f2}/{f2}'] = df[f'cross_{f1}_{f2}_count'] / (df[f'{f2}_count']+df[f'{f2}_count'].mean())\n    \n    del df[f'cross_{f1}_{f2}']\ndf = reduce_mem_usage(df)","metadata":{"execution":{"iopub.status.busy":"2024-04-01T01:49:54.746058Z","iopub.execute_input":"2024-04-01T01:49:54.746790Z","iopub.status.idle":"2024-04-01T01:55:16.289794Z","shell.execute_reply.started":"2024-04-01T01:49:54.746750Z","shell.execute_reply":"2024-04-01T01:55:16.288662Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 全局统计特征","metadata":{}},{"cell_type":"code","source":"global_cate_group_feature = [['user_id',fea] for fea in item_cate_feature]+[['item_id',fea] for fea in user_cate_feature]\n# 离散特征-离散特征\nfor [key,value] in tqdm(global_cate_group_feature):\n    tmp = df.groupby([key])[value].nunique().reset_index()\n    tmp.columns = [key, value+'_nunique']\n    df = df.merge(tmp, on=key, how='left')\n    \n#离散特征-连续特征\nglobal_dense_group_feature =[['item_id',f'user_fea{i}']  for i in range(6,9) ]\nfor [key,value] in tqdm(global_dense_group_feature):\n    tmp = df.groupby([key])[value].describe().reset_index()\n    tmp.columns = [key] + ['group_'+ x for x in ['count', 'mean', 'std', 'min', '25%', '50%', '75%', 'max']]\n    df = df.merge(tmp[[key] + ['group_'+ x for x in ['mean', 'std', '25%', '50%', '75%']]], on=key, how='left')\n\ndf = reduce_mem_usage(df)","metadata":{"execution":{"iopub.status.busy":"2024-04-01T01:55:16.291281Z","iopub.execute_input":"2024-04-01T01:55:16.291664Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 点击率/目标编码","metadata":{}},{"cell_type":"code","source":"train_df = df[df['label'].notna()].reset_index(drop=True)\ntest_df = df[df['label'].isna()].reset_index(drop=True)\n\ndel df\ngc.collect()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"## 五折目标编码\nskf = StratifiedKFold(n_splits=5, shuffle=True, random_state=2020)\nfor f in tqdm(cate_cols):\n    train_df[f + '_target_enc'] = 0\n    test_df[f + '_target_enc'] = 0\n    for i, (trn_idx, val_idx) in enumerate(skf.split(train_df, train_df['label'])):\n        trn_x = train_df[[f, 'label']].iloc[trn_idx].reset_index(drop=True)\n        val_x = train_df[[f]].iloc[val_idx].reset_index(drop=True)\n        \n        enc_df = trn_x.groupby(f, as_index=False)['label'].agg({f + '_target_enc': 'mean'})\n        \n        val_x = val_x.merge(enc_df, on=f, how='left')\n        test_x = test_df[[f]].merge(enc_df, on=f, how='left')\n        \n        val_x[f + '_target_enc'] = val_x[f + '_target_enc'].fillna(train_df['label'].mean())\n        test_x[f + '_target_enc'] = test_x[f + '_target_enc'].fillna(train_df['label'].mean())\n        # 前面的可以类比做交叉验证的模型训练\n        train_df.loc[val_idx, f + '_target_enc'] = val_x[f + '_target_enc'].values # 相当于oof_pre的赋值\n        test_df[f + '_target_enc'] += test_x[f + '_target_enc'].values / skf.n_splits # 相当于test_df的均值操作\n\ntrain_df = reduce_mem_usage(train_df)\ntest_df = reduce_mem_usage(test_df)","metadata":{"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":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 模型训练","metadata":{}},{"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\ncallbacks = [log_evaluation(period=50), early_stopping(stopping_rounds=50)]\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                    callbacks=callbacks)\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":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fea_imp = pd.DataFrame()\nfea_imp['imp'] = clf.feature_importance()\nfea_imp['fea_name'] = clf.feature_name()\nfea_imp = fea_imp.sort_values('imp')[:30]\nplt.figure(figsize=(10, 10))\nplt.barh(fea_imp['fea_name'],fea_imp['imp'],height =0.5)","metadata":{"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-feature-eng.csv',index=False)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}