{"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-17T13:10:49.263054Z","iopub.execute_input":"2023-02-17T13:10:49.264341Z","iopub.status.idle":"2023-02-17T13:10:49.304979Z","shell.execute_reply.started":"2023-02-17T13:10:49.264200Z","shell.execute_reply":"2023-02-17T13:10:49.303333Z"},"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":"2023-02-17T13:10:49.308061Z","iopub.execute_input":"2023-02-17T13:10:49.308492Z","iopub.status.idle":"2023-02-17T13:10:52.070584Z","shell.execute_reply.started":"2023-02-17T13:10:49.308459Z","shell.execute_reply":"2023-02-17T13:10:52.069348Z"},"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-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-17T13:12:42.717416Z","iopub.execute_input":"2023-02-17T13:12:42.717915Z","iopub.status.idle":"2023-02-17T13:13:30.747041Z","shell.execute_reply.started":"2023-02-17T13:12:42.717881Z","shell.execute_reply":"2023-02-17T13:13:30.745534Z"},"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-17T13:21:03.803592Z","iopub.execute_input":"2023-02-17T13:21:03.804201Z","iopub.status.idle":"2023-02-17T13:21:09.057879Z","shell.execute_reply.started":"2023-02-17T13:21:03.804161Z","shell.execute_reply":"2023-02-17T13:21:09.056069Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.head()","metadata":{"execution":{"iopub.status.busy":"2023-02-17T13:18:18.452455Z","iopub.execute_input":"2023-02-17T13:18:18.452865Z","iopub.status.idle":"2023-02-17T13:18:18.479042Z","shell.execute_reply.started":"2023-02-17T13:18:18.452828Z","shell.execute_reply":"2023-02-17T13:18:18.477562Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.info(verbose=True,null_counts=True)","metadata":{"execution":{"iopub.status.busy":"2023-02-17T13:18:23.937000Z","iopub.execute_input":"2023-02-17T13:18:23.938301Z","iopub.status.idle":"2023-02-17T13:18:26.133542Z","shell.execute_reply.started":"2023-02-17T13:18:23.938233Z","shell.execute_reply":"2023-02-17T13:18:26.130938Z"},"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-17T13:19:02.851159Z","iopub.execute_input":"2023-02-17T13:19:02.851648Z","iopub.status.idle":"2023-02-17T13:19:02.858822Z","shell.execute_reply.started":"2023-02-17T13:19:02.851610Z","shell.execute_reply":"2023-02-17T13:19:02.857852Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"num_cols","metadata":{"execution":{"iopub.status.busy":"2023-02-17T13:19:21.257728Z","iopub.execute_input":"2023-02-17T13:19:21.258192Z","iopub.status.idle":"2023-02-17T13:19:21.267423Z","shell.execute_reply.started":"2023-02-17T13:19:21.258154Z","shell.execute_reply":"2023-02-17T13:19:21.265688Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(cate_cols)","metadata":{"execution":{"iopub.status.busy":"2023-02-17T13:19:21.501029Z","iopub.execute_input":"2023-02-17T13:19:21.501480Z","iopub.status.idle":"2023-02-17T13:19:21.508186Z","shell.execute_reply.started":"2023-02-17T13:19:21.501448Z","shell.execute_reply":"2023-02-17T13:19:21.506595Z"},"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":"2023-02-17T13:19:40.351345Z","iopub.execute_input":"2023-02-17T13:19:40.351839Z","iopub.status.idle":"2023-02-17T13:20:34.991117Z","shell.execute_reply.started":"2023-02-17T13:19:40.351802Z","shell.execute_reply":"2023-02-17T13:20:34.989398Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 原生数据编码\nfor col in tqdm(num_cols):\n    df[col] = df[col].fillna(0)\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] - df[col].mean()) / df[col].std()","metadata":{"execution":{"iopub.status.busy":"2023-02-17T13:22:16.824284Z","iopub.execute_input":"2023-02-17T13:22:16.824694Z","iopub.status.idle":"2023-02-17T13:22:17.432380Z","shell.execute_reply.started":"2023-02-17T13:22:16.824660Z","shell.execute_reply":"2023-02-17T13:22:17.431005Z"},"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":"2023-02-14T07:49:22.692165Z","iopub.execute_input":"2023-02-14T07:49:22.693034Z","iopub.status.idle":"2023-02-14T07:49:22.697935Z","shell.execute_reply.started":"2023-02-14T07:49:22.692999Z","shell.execute_reply":"2023-02-14T07:49:22.696873Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 离散特征\n# for col in tqdm(['user_fea1', 'user_fea2', 'user_fea3', 'user_fea4', 'user_fea5', 'item_fea1', 'user_fea9']):\n#     plt.figure(dpi=150)\n#     sns.countplot(df[col])","metadata":{"execution":{"iopub.status.busy":"2023-02-17T13:23:45.194938Z","iopub.execute_input":"2023-02-17T13:23:45.195524Z","iopub.status.idle":"2023-02-17T13:23:45.201870Z","shell.execute_reply.started":"2023-02-17T13:23:45.195486Z","shell.execute_reply":"2023-02-17T13:23:45.200107Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(dpi=150)\nsns.countplot(train_df['label'])","metadata":{"execution":{"iopub.status.busy":"2023-02-17T13:24:27.146361Z","iopub.execute_input":"2023-02-17T13:24:27.146791Z","iopub.status.idle":"2023-02-17T13:24:27.692856Z","shell.execute_reply.started":"2023-02-17T13:24:27.146748Z","shell.execute_reply":"2023-02-17T13:24:27.691524Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 原生离散特征编码\n# 操作df一列：\n# 1.map方法：输入一个dict(k:v对)\n# 2.apply方法：输入一个func,这个func的输入是该列特征的一个值，返回结果是修改后的值\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-17T13:25:10.683707Z","iopub.execute_input":"2023-02-17T13:25:10.684265Z","iopub.status.idle":"2023-02-17T13:25:34.180600Z","shell.execute_reply.started":"2023-02-17T13:25:10.684224Z","shell.execute_reply":"2023-02-17T13:25:34.179417Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 需要维护一个map_dict来定义映射的方法\nmap_dict = dict( zip( train_df['user_fea1'].unique(), range(train_df['user_fea1'].nunique()) ) )","metadata":{"execution":{"iopub.status.busy":"2023-02-17T13:28:04.887974Z","iopub.execute_input":"2023-02-17T13:28:04.888531Z","iopub.status.idle":"2023-02-17T13:28:05.508274Z","shell.execute_reply.started":"2023-02-17T13:28:04.888487Z","shell.execute_reply":"2023-02-17T13:28:05.506875Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def func1(x):\n    return '666_'+x","metadata":{"execution":{"iopub.status.busy":"2023-02-17T13:33:58.386187Z","iopub.execute_input":"2023-02-17T13:33:58.386733Z","iopub.status.idle":"2023-02-17T13:33:58.392999Z","shell.execute_reply.started":"2023-02-17T13:33:58.386690Z","shell.execute_reply":"2023-02-17T13:33:58.391301Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df['user_fea1'].apply(func1)","metadata":{"execution":{"iopub.status.busy":"2023-02-17T13:33:58.618510Z","iopub.execute_input":"2023-02-17T13:33:58.619435Z","iopub.status.idle":"2023-02-17T13:33:59.823483Z","shell.execute_reply.started":"2023-02-17T13:33:58.619393Z","shell.execute_reply":"2023-02-17T13:33:59.822118Z"},"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_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-17T13:34:52.319419Z","iopub.execute_input":"2023-02-17T13:34:52.320028Z","iopub.status.idle":"2023-02-17T13:34:54.827876Z","shell.execute_reply.started":"2023-02-17T13:34:52.319989Z","shell.execute_reply":"2023-02-17T13:34:54.826406Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df.shape,test_df.shape","metadata":{"execution":{"iopub.status.busy":"2023-02-17T13:35:15.364643Z","iopub.execute_input":"2023-02-17T13:35:15.365205Z","iopub.status.idle":"2023-02-17T13:35:15.373777Z","shell.execute_reply.started":"2023-02-17T13:35:15.365167Z","shell.execute_reply":"2023-02-17T13:35:15.372463Z"},"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-17T13:36:37.078753Z","iopub.execute_input":"2023-02-17T13:36:37.079294Z","iopub.status.idle":"2023-02-17T13:36:37.087067Z","shell.execute_reply.started":"2023-02-17T13:36:37.079249Z","shell.execute_reply":"2023-02-17T13:36:37.085873Z"},"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":"2023-02-14T08:08:50.998002Z","iopub.execute_input":"2023-02-14T08:08:50.999062Z","iopub.status.idle":"2023-02-14T08:08:51.006986Z","shell.execute_reply.started":"2023-02-14T08:08:50.999016Z","shell.execute_reply":"2023-02-14T08:08:51.005938Z"},"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_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_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 = AdaBoostClassifier()\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_count":null,"outputs":[]},{"cell_type":"code","source":"sklearn_sub_df = pd.DataFrame()\nsklearn_sub_df['ID'] = test_df['ID']\nsklearn_sub_df['label'] = y_pre\nsklearn_sub_df.to_csv('/kaggle/working/sklearn_baseline.csv',index=False)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 3.模型验证","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\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-17T13:48:31.078781Z","iopub.execute_input":"2023-02-17T13:48:31.079500Z"},"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":[]}]}