{"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":"2022-10-20T13:26:13.269606Z","iopub.execute_input":"2022-10-20T13:26:13.270087Z","iopub.status.idle":"2022-10-20T13:26:13.280993Z","shell.execute_reply.started":"2022-10-20T13:26:13.270048Z","shell.execute_reply":"2022-10-20T13:26:13.278938Z"},"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 gc\nimport multiprocessing \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":"2022-10-20T13:26:13.803102Z","iopub.execute_input":"2022-10-20T13:26:13.803710Z","iopub.status.idle":"2022-10-20T13:26:15.682203Z","shell.execute_reply.started":"2022-10-20T13:26:13.803663Z","shell.execute_reply":"2022-10-20T13:26:15.680865Z"},"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":"2022-10-20T13:26:15.683717Z","iopub.execute_input":"2022-10-20T13:26:15.684049Z","iopub.status.idle":"2022-10-20T13:26:15.700648Z","shell.execute_reply.started":"2022-10-20T13:26:15.684020Z","shell.execute_reply":"2022-10-20T13:26:15.699203Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df = pd.read_csv('/kaggle/input/deepshare-playground/train_behaviour.csv')\ntest_df = pd.read_csv('/kaggle/input/deepshare-playground/test_behaviour.csv')\nuser_df = pd.read_csv('/kaggle/input/deepshare-playground/user_info.csv')\nitem_df = pd.read_csv('/kaggle/input/deepshare-playground/item_info.csv')","metadata":{"execution":{"iopub.status.busy":"2022-10-20T13:26:17.132490Z","iopub.execute_input":"2022-10-20T13:26:17.132996Z","iopub.status.idle":"2022-10-20T13:26:21.715952Z","shell.execute_reply.started":"2022-10-20T13:26:17.132956Z","shell.execute_reply":"2022-10-20T13:26:21.714783Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"item_df = item_df.drop_duplicates(subset=['item_id'], keep='last', inplace=False)\nuser_df = user_df.drop_duplicates(subset=['user_id'], keep='last', inplace=False)","metadata":{"execution":{"iopub.status.busy":"2022-10-20T13:26:21.718504Z","iopub.execute_input":"2022-10-20T13:26:21.718974Z","iopub.status.idle":"2022-10-20T13:26:21.757940Z","shell.execute_reply.started":"2022-10-20T13:26:21.718927Z","shell.execute_reply":"2022-10-20T13:26:21.756600Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\ndf = pd.concat([train_df,test_df],axis=0).reset_index(drop=True)\ndf = df.merge(user_df,on='user_id',how='left').reset_index(drop=True)\ndf = df.merge(item_df,on='item_id',how='left').reset_index(drop=True)\n\ndel user_df,item_df\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2022-10-20T13:26:21.759396Z","iopub.execute_input":"2022-10-20T13:26:21.759765Z","iopub.status.idle":"2022-10-20T13:26:26.493129Z","shell.execute_reply.started":"2022-10-20T13:26:21.759733Z","shell.execute_reply":"2022-10-20T13:26:26.492008Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"num_cols  =  ['user_fea4']\ncate_cols = ['user_id','item_id']+[f'user_fea{i}' for i in range(1,4)] + [f'item_fea{i}' for i in range(1,10)]\nuser_cate_feature = [f'user_fea{i}' for i in range(1,4)]\nitem_cate_feature = [f'item_fea{i}' for i in range(1,10)]","metadata":{"execution":{"iopub.status.busy":"2022-10-20T13:27:01.054204Z","iopub.execute_input":"2022-10-20T13:27:01.054645Z","iopub.status.idle":"2022-10-20T13:27:01.060947Z","shell.execute_reply.started":"2022-10-20T13:27:01.054613Z","shell.execute_reply":"2022-10-20T13:27:01.059975Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 离散特征编码\n","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":"2022-10-20T13:27:44.668608Z","iopub.execute_input":"2022-10-20T13:27:44.668990Z","iopub.status.idle":"2022-10-20T13:28:09.540135Z","shell.execute_reply.started":"2022-10-20T13:27:44.668961Z","shell.execute_reply":"2022-10-20T13:28:09.538922Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 交叉特征","metadata":{}},{"cell_type":"code","source":"[['user_id',fea] for fea in item_cate_feature]","metadata":{"execution":{"iopub.status.busy":"2022-10-20T13:29:15.393994Z","iopub.execute_input":"2022-10-20T13:29:15.394453Z","iopub.status.idle":"2022-10-20T13:29:15.403150Z","shell.execute_reply.started":"2022-10-20T13:29:15.394418Z","shell.execute_reply":"2022-10-20T13:29:15.401966Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cross_feature_pair=[\n    ['user_id','item_id']\n]\ncross_feature_pair += [['user_id',fea] for fea in item_cate_feature]\ncross_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    # 出bug啦！已修改！\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}']\n# df = reduce_mem_usage(df)","metadata":{"execution":{"iopub.status.busy":"2022-10-20T13:32:16.210365Z","iopub.execute_input":"2022-10-20T13:32:16.210799Z","iopub.status.idle":"2022-10-20T13:34:11.291936Z","shell.execute_reply.started":"2022-10-20T13:32:16.210764Z","shell.execute_reply":"2022-10-20T13:34:11.290366Z"},"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#离散特征-连续特征\nglobal_dense_group_feature =[['item_id','user_fea4']]\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\n# df = reduce_mem_usage(df)","metadata":{"execution":{"iopub.status.busy":"2022-10-20T13:34:49.401328Z","iopub.execute_input":"2022-10-20T13:34:49.401823Z","iopub.status.idle":"2022-10-20T13:37:11.679533Z","shell.execute_reply.started":"2022-10-20T13:34:49.401789Z","shell.execute_reply":"2022-10-20T13:37:11.678232Z"},"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":{"execution":{"iopub.status.busy":"2022-10-20T13:37:11.682073Z","iopub.execute_input":"2022-10-20T13:37:11.682589Z","iopub.status.idle":"2022-10-20T13:37:15.329508Z","shell.execute_reply.started":"2022-10-20T13:37:11.682542Z","shell.execute_reply":"2022-10-20T13:37:15.328323Z"},"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":{"execution":{"iopub.status.busy":"2022-10-20T13:37:15.330850Z","iopub.execute_input":"2022-10-20T13:37:15.331201Z","iopub.status.idle":"2022-10-20T13:47:24.710256Z","shell.execute_reply.started":"2022-10-20T13:37:15.331170Z","shell.execute_reply":"2022-10-20T13:47:24.708895Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 删掉无用特征\nfeature = [x for x in train_df.columns]\ndrop_feature = drop_feature = ['ID','label', 'day', 'item_desc']\nfeature = [x for x in feature if x not in drop_feature]\nfeature = list(set(feature))\nprint(len(feature),feature)","metadata":{"execution":{"iopub.status.busy":"2022-10-20T13:47:24.712610Z","iopub.execute_input":"2022-10-20T13:47:24.712971Z","iopub.status.idle":"2022-10-20T13:47:24.720485Z","shell.execute_reply.started":"2022-10-20T13:47:24.712939Z","shell.execute_reply":"2022-10-20T13:47:24.719137Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"params = {'num_leaves': 63, #结果对最终效果影响较大，越大值越好，太大会出现过拟合\n          'objective': 'binary', #定义的目标函数\n          'max_depth': -1,\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":"2022-10-20T13:47:24.721897Z","iopub.execute_input":"2022-10-20T13:47:24.722310Z"},"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":{"execution":{"iopub.status.busy":"2022-10-19T06:03:30.284436Z","iopub.execute_input":"2022-10-19T06:03:30.285008Z","iopub.status.idle":"2022-10-19T06:03:30.305626Z","shell.execute_reply.started":"2022-10-19T06:03:30.284963Z","shell.execute_reply":"2022-10-19T06:03:30.304610Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"res_df = pd.DataFrame()\nres_df['ID'] = test_df['ID']\nres_df['predict'] = y_pre\nres_df.to_csv('/kaggle/working/feature_eng.csv',index=False)","metadata":{"execution":{"iopub.status.busy":"2022-10-19T06:03:36.291484Z","iopub.execute_input":"2022-10-19T06:03:36.291842Z","iopub.status.idle":"2022-10-19T06:03:36.713776Z","shell.execute_reply.started":"2022-10-19T06:03:36.291811Z","shell.execute_reply":"2022-10-19T06:03:36.712662Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}