{"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-16T12:46:25.775974Z","iopub.execute_input":"2022-10-16T12:46:25.776371Z","iopub.status.idle":"2022-10-16T12:46:25.805703Z","shell.execute_reply.started":"2022-10-16T12:46:25.776264Z","shell.execute_reply":"2022-10-16T12:46:25.804783Z"},"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\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-16T12:46:36.096928Z","iopub.execute_input":"2022-10-16T12:46:36.097311Z","iopub.status.idle":"2022-10-16T12:46:37.619766Z","shell.execute_reply.started":"2022-10-16T12:46:36.097282Z","shell.execute_reply":"2022-10-16T12:46:37.618732Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Course-2 主要内容\n## 1.数据处理\n* 数据读取\n* 数据预处理\n* Pandas 处理一列数据的逻辑(map/apply)\n\n## 2.模型调用\n* scikit-learn 经典模型使用\n* lightgbm/xgboost/catboost 模型使用\n\n## 3.模型验证\n* hold out验证\n* 交叉验证","metadata":{}},{"cell_type":"markdown","source":"# 1.数据处理","metadata":{}},{"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-16T12:48:18.222233Z","iopub.execute_input":"2022-10-16T12:48:18.222705Z","iopub.status.idle":"2022-10-16T12:48:22.440840Z","shell.execute_reply.started":"2022-10-16T12:48:18.222667Z","shell.execute_reply":"2022-10-16T12:48:22.439716Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df.shape,test_df.shape","metadata":{"execution":{"iopub.status.busy":"2022-10-16T12:48:24.849983Z","iopub.execute_input":"2022-10-16T12:48:24.850402Z","iopub.status.idle":"2022-10-16T12:48:24.859903Z","shell.execute_reply.started":"2022-10-16T12:48:24.850366Z","shell.execute_reply":"2022-10-16T12:48:24.858379Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Pandas 处理一列数据的逻辑\n\n# map： 传入一个K：V对(可以是字典)，map方法会将这个字典挨个映射一遍\nmap_dict = item_df['item_fea4'].value_counts()\nitem_df['item_fea4'].map(map_dict)\n# apply: 传入一个函数，这个函数的入参是这一列的值，返回是你修改之后的值\ndef map_fun(x):\n    return x+999999\nitem_df['item_fea4'].apply(map_fun)","metadata":{"execution":{"iopub.status.busy":"2022-10-16T12:55:58.580078Z","iopub.execute_input":"2022-10-16T12:55:58.580468Z","iopub.status.idle":"2022-10-16T12:55:58.612170Z","shell.execute_reply.started":"2022-10-16T12:55:58.580434Z","shell.execute_reply":"2022-10-16T12:55:58.611116Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"item_df['item_count'] = item_df['item_id'].map(item_df['item_id'].value_counts())\nitem_df[item_df['item_count']>1]","metadata":{"execution":{"iopub.status.busy":"2022-10-15T11:20:34.383324Z","iopub.execute_input":"2022-10-15T11:20:34.383914Z","iopub.status.idle":"2022-10-15T11:20:34.417298Z","shell.execute_reply.started":"2022-10-15T11:20:34.383880Z","shell.execute_reply":"2022-10-15T11:20:34.416068Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 发现item_df中有脏数据，需要对其进行去重\nitem_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-16T13:05:10.460329Z","iopub.execute_input":"2022-10-16T13:05:10.460865Z","iopub.status.idle":"2022-10-16T13:05:10.486917Z","shell.execute_reply.started":"2022-10-16T13:05:10.460818Z","shell.execute_reply":"2022-10-16T13:05:10.486082Z"},"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)\n# 把user/item侧的特征进行merge，以扩充宽表特征\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)","metadata":{"execution":{"iopub.status.busy":"2022-10-16T13:05:10.797405Z","iopub.execute_input":"2022-10-16T13:05:10.798308Z","iopub.status.idle":"2022-10-16T13:05:15.304472Z","shell.execute_reply.started":"2022-10-16T13:05:10.798262Z","shell.execute_reply":"2022-10-16T13:05:15.303128Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.info(verbose=True,null_counts=True)","metadata":{"execution":{"iopub.status.busy":"2022-10-15T11:20:38.530095Z","iopub.execute_input":"2022-10-15T11:20:38.531133Z","iopub.status.idle":"2022-10-15T11:20:38.982231Z","shell.execute_reply.started":"2022-10-15T11:20:38.531094Z","shell.execute_reply":"2022-10-15T11:20:38.981099Z"},"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)]","metadata":{"execution":{"iopub.status.busy":"2022-10-16T13:09:28.601920Z","iopub.execute_input":"2022-10-16T13:09:28.602325Z","iopub.status.idle":"2022-10-16T13:09:28.608458Z","shell.execute_reply.started":"2022-10-16T13:09:28.602288Z","shell.execute_reply":"2022-10-16T13:09:28.607269Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 连续特征\nfor col in tqdm(num_cols):\n    plt.figure(dpi=150)\n    sns.distplot(df[col])","metadata":{"execution":{"iopub.status.busy":"2022-10-15T11:20:38.992378Z","iopub.execute_input":"2022-10-15T11:20:38.992658Z","iopub.status.idle":"2022-10-15T11:20:53.583795Z","shell.execute_reply.started":"2022-10-15T11:20:38.992632Z","shell.execute_reply":"2022-10-15T11:20:53.582645Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 原生数据编码\nfor col in tqdm(num_cols):\n    # min-max\n#     df[col] = (df[col] - df[col].min()) / (df[col].max() - df[col].min())\n    # z-score\n    df[col] = df[col].fillna(0)\n    df[col] = (df[col] - df[col].mean()) / df[col].std()","metadata":{"execution":{"iopub.status.busy":"2022-10-16T13:12:39.936072Z","iopub.execute_input":"2022-10-16T13:12:39.936515Z","iopub.status.idle":"2022-10-16T13:12:40.099786Z","shell.execute_reply.started":"2022-10-16T13:12:39.936470Z","shell.execute_reply":"2022-10-16T13:12:40.098651Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# sklearn 数据编码\n# scaler = StandardScaler()\n# scaler = MinMaxScaler()\n# df[num_cols] = scaler.fit_transform(df[num_cols])\n\n# train_df[num_cols] = scaler.fit(train_df[num_cols])\n\n# train_df[num_cols] = scaler.transform(train_df[num_cols])\n# test_df[num_cols] = scaler.transform(test_df[num_cols])","metadata":{"execution":{"iopub.status.busy":"2022-10-15T11:20:54.181547Z","iopub.execute_input":"2022-10-15T11:20:54.181844Z","iopub.status.idle":"2022-10-15T11:20:54.186408Z","shell.execute_reply.started":"2022-10-15T11:20:54.181816Z","shell.execute_reply":"2022-10-15T11:20:54.185270Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 离散特征\nfor col in tqdm(['user_fea1','user_fea2','user_fea3']):\n    plt.figure(dpi=150)\n    sns.countplot(user_df[col])","metadata":{"execution":{"iopub.status.busy":"2022-10-15T11:19:46.970238Z","iopub.execute_input":"2022-10-15T11:19:46.970669Z","iopub.status.idle":"2022-10-15T11:19:47.762067Z","shell.execute_reply.started":"2022-10-15T11:19:46.970634Z","shell.execute_reply":"2022-10-15T11:19:47.760926Z"},"collapsed":true,"jupyter":{"outputs_hidden":true},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 原生离散特征编码\nfor col in tqdm(cate_cols):\n    map_dict = dict(zip(df[col].unique(), range(df[col].nunique())))\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":"2022-10-16T13:14:43.693121Z","iopub.execute_input":"2022-10-16T13:14:43.693563Z","iopub.status.idle":"2022-10-16T13:14:46.608763Z","shell.execute_reply.started":"2022-10-16T13:14:43.693526Z","shell.execute_reply":"2022-10-16T13:14:46.607625Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# sklearn 离散特征编码\n# for col in tqdm(cate_cols):\n#     scale = LabelEncoder()\n#     scale.fit(df[col])\n#     df[col] = scale.transform(df[col])","metadata":{"execution":{"iopub.status.busy":"2022-10-15T11:20:56.831399Z","iopub.execute_input":"2022-10-15T11:20:56.831840Z","iopub.status.idle":"2022-10-15T11:20:56.836800Z","shell.execute_reply.started":"2022-10-15T11:20:56.831797Z","shell.execute_reply":"2022-10-15T11:20:56.836074Z"},"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":"2022-10-16T13:18:14.165954Z","iopub.execute_input":"2022-10-16T13:18:14.166376Z","iopub.status.idle":"2022-10-16T13:18:14.821482Z","shell.execute_reply.started":"2022-10-16T13:18:14.166321Z","shell.execute_reply":"2022-10-16T13:18:14.820352Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df.shape,test_df.shape","metadata":{"execution":{"iopub.status.busy":"2022-10-16T13:18:53.011239Z","iopub.execute_input":"2022-10-16T13:18:53.012084Z","iopub.status.idle":"2022-10-16T13:18:53.018298Z","shell.execute_reply.started":"2022-10-16T13:18:53.012046Z","shell.execute_reply":"2022-10-16T13:18:53.017518Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"drop_feature = ['ID','label', 'day', 'item_desc']\nfeature = [x for x in train_df.columns if x not in drop_feature]\nprint(len(feature),feature)","metadata":{"execution":{"iopub.status.busy":"2022-10-16T13:20:33.211874Z","iopub.execute_input":"2022-10-16T13:20:33.212680Z","iopub.status.idle":"2022-10-16T13:20:33.218561Z","shell.execute_reply.started":"2022-10-16T13:20:33.212640Z","shell.execute_reply":"2022-10-16T13:20:33.217616Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 2.模型调用","metadata":{}},{"cell_type":"code","source":"### sklearn一般的范式\n'''\n# 实例化模型\nmodel = XXX(**params)\n\n# 拟合模型\nmodel.fit(X_train, y_train)\n\n# 模型预测 类别\nmodel.predict(X_test)\n\n# 输出概率(分类任务)\nmodel.predict_proba(X_test)\n\n# 获得这个模型的参数\nmodel.get_params()\n'''","metadata":{"execution":{"iopub.status.busy":"2022-10-15T11:20:57.911816Z","iopub.execute_input":"2022-10-15T11:20:57.912256Z","iopub.status.idle":"2022-10-15T11:20:57.921512Z","shell.execute_reply.started":"2022-10-15T11:20:57.912212Z","shell.execute_reply":"2022-10-15T11:20:57.920547Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\nX_train, X_valid, y_train, y_valid = train_test_split(train_df[feature], train_df['label'], random_state=666)","metadata":{"execution":{"iopub.status.busy":"2022-10-15T11:20:57.922394Z","iopub.execute_input":"2022-10-15T11:20:57.922681Z","iopub.status.idle":"2022-10-15T11:20:57.934287Z","shell.execute_reply.started":"2022-10-15T11:20:57.922655Z","shell.execute_reply":"2022-10-15T11:20:57.933331Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.linear_model import LinearRegression\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.naive_bayes import BernoulliNB, MultinomialNB, GaussianNB\nfrom sklearn.svm import SVC\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.ensemble import AdaBoostClassifier, RandomForestClassifier\n","metadata":{"execution":{"iopub.status.busy":"2022-10-16T13:26:55.408549Z","iopub.execute_input":"2022-10-16T13:26:55.408942Z","iopub.status.idle":"2022-10-16T13:26:55.617471Z","shell.execute_reply.started":"2022-10-16T13:26:55.408911Z","shell.execute_reply":"2022-10-16T13:26:55.616398Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.linear_model import LinearRegression\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.naive_bayes import BernoulliNB, MultinomialNB, GaussianNB\nfrom sklearn.svm import SVC\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.ensemble import AdaBoostClassifier, RandomForestClassifier\n\n\nmodel = RandomForestClassifier()\n\nmodel.fit(X_train, y_train)\n\ny_valid_pre = model.predict_proba(X_valid)[:,1] \n# 二分类任务输出的维度是：nx2\n\nprint(f'{str(model)} AUC :{roc_auc_score(y_valid, y_valid_pre)}')\n\nprint(f'{str(model)} LogLoss :{log_loss(y_valid, y_valid_pre)}')\n\ny_pre = model.predict_proba(test_df[feature])[:,1]","metadata":{"execution":{"iopub.status.busy":"2022-10-15T11:20:58.046521Z","iopub.execute_input":"2022-10-15T11:20:58.046892Z","iopub.status.idle":"2022-10-15T11:21:02.584795Z","shell.execute_reply.started":"2022-10-15T11:20:58.046863Z","shell.execute_reply":"2022-10-15T11:21:02.583838Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sklearn_sub_df = pd.DataFrame()\nsklearn_sub_df['ID'] = test_df['ID']\nsklearn_sub_df['predict'] = y_pre\nsklearn_sub_df.to_csv('/kaggle/working/sklearn_baseline.csv',index=False)","metadata":{"execution":{"iopub.status.busy":"2022-10-15T11:21:02.586824Z","iopub.execute_input":"2022-10-15T11:21:02.587265Z","iopub.status.idle":"2022-10-15T11:21:02.890636Z","shell.execute_reply.started":"2022-10-15T11:21:02.587212Z","shell.execute_reply":"2022-10-15T11:21:02.889707Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 3.模型验证","metadata":{}},{"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-16T13:36:04.911496Z","iopub.execute_input":"2022-10-16T13:36:04.911885Z","iopub.status.idle":"2022-10-16T13:36:05.013927Z","shell.execute_reply.started":"2022-10-16T13:36:04.911853Z","shell.execute_reply":"2022-10-16T13:36:05.012761Z"},"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-15T11:22:20.409759Z","iopub.execute_input":"2022-10-15T11:22:20.410157Z","iopub.status.idle":"2022-10-15T11:22:20.421727Z","shell.execute_reply.started":"2022-10-15T11:22:20.410125Z","shell.execute_reply":"2022-10-15T11:22:20.420550Z"},"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/lgb-baseline.csv',index=False)","metadata":{"execution":{"iopub.status.busy":"2022-10-15T11:21:05.780393Z","iopub.execute_input":"2022-10-15T11:21:05.780692Z","iopub.status.idle":"2022-10-15T11:21:06.249551Z","shell.execute_reply.started":"2022-10-15T11:21:05.780665Z","shell.execute_reply":"2022-10-15T11:21:06.248023Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}