{"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-03-26T08:45:57.594985Z","iopub.execute_input":"2024-03-26T08:45:57.595395Z","iopub.status.idle":"2024-03-26T08:45:57.602808Z","shell.execute_reply.started":"2024-03-26T08:45:57.595369Z","shell.execute_reply":"2024-03-26T08:45:57.601708Z"},"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\nfrom lightgbm import log_evaluation, early_stopping","metadata":{"execution":{"iopub.status.busy":"2024-03-26T09:08:12.687753Z","iopub.execute_input":"2024-03-26T09:08:12.688174Z","iopub.status.idle":"2024-03-26T09:08:12.694176Z","shell.execute_reply.started":"2024-03-26T09:08:12.688148Z","shell.execute_reply":"2024-03-26T09:08:12.692934Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Baseline 主要内容\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-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-03-26T08:47:35.978938Z","iopub.execute_input":"2024-03-26T08:47:35.979645Z","iopub.status.idle":"2024-03-26T08:48:09.206539Z","shell.execute_reply.started":"2024-03-26T08:47:35.979613Z","shell.execute_reply":"2024-03-26T08:48:09.205516Z"},"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-03-26T08:48:09.208452Z","iopub.execute_input":"2024-03-26T08:48:09.208877Z","iopub.status.idle":"2024-03-26T08:48:13.267370Z","shell.execute_reply.started":"2024-03-26T08:48:09.208841Z","shell.execute_reply":"2024-03-26T08:48:13.266286Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.head()","metadata":{"execution":{"iopub.status.busy":"2024-03-26T08:48:13.268699Z","iopub.execute_input":"2024-03-26T08:48:13.269023Z","iopub.status.idle":"2024-03-26T08:48:13.296981Z","shell.execute_reply.started":"2024-03-26T08:48:13.268999Z","shell.execute_reply":"2024-03-26T08:48:13.296040Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.info(verbose=True)","metadata":{"execution":{"iopub.status.busy":"2024-03-26T08:48:23.562087Z","iopub.execute_input":"2024-03-26T08:48:23.562491Z","iopub.status.idle":"2024-03-26T08:48:23.586205Z","shell.execute_reply.started":"2024-03-26T08:48:23.562454Z","shell.execute_reply":"2024-03-26T08:48:23.585041Z"},"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-03-26T08:48:25.796855Z","iopub.execute_input":"2024-03-26T08:48:25.797703Z","iopub.status.idle":"2024-03-26T08:48:25.803331Z","shell.execute_reply.started":"2024-03-26T08:48:25.797668Z","shell.execute_reply":"2024-03-26T08:48:25.802273Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"num_cols","metadata":{"execution":{"iopub.status.busy":"2024-03-26T08:48:27.879751Z","iopub.execute_input":"2024-03-26T08:48:27.880312Z","iopub.status.idle":"2024-03-26T08:48:27.887597Z","shell.execute_reply.started":"2024-03-26T08:48:27.880279Z","shell.execute_reply":"2024-03-26T08:48:27.886344Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(cate_cols)","metadata":{"execution":{"iopub.status.busy":"2024-03-26T08:48:30.213793Z","iopub.execute_input":"2024-03-26T08:48:30.214690Z","iopub.status.idle":"2024-03-26T08:48:30.220395Z","shell.execute_reply.started":"2024-03-26T08:48:30.214647Z","shell.execute_reply":"2024-03-26T08:48:30.219466Z"},"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":"2024-03-26T08:48:31.715663Z","iopub.execute_input":"2024-03-26T08:48:31.716104Z","iopub.status.idle":"2024-03-26T08:49:27.216383Z","shell.execute_reply.started":"2024-03-26T08:48:31.716074Z","shell.execute_reply":"2024-03-26T08:49:27.215331Z"},"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":"2024-03-26T08:49:27.218225Z","iopub.execute_input":"2024-03-26T08:49:27.218632Z","iopub.status.idle":"2024-03-26T08:49:27.781806Z","shell.execute_reply.started":"2024-03-26T08:49:27.218606Z","shell.execute_reply":"2024-03-26T08:49:27.780489Z"},"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":"2024-03-26T08:49:27.782773Z","iopub.execute_input":"2024-03-26T08:49:27.783086Z","iopub.status.idle":"2024-03-26T08:49:27.788042Z","shell.execute_reply.started":"2024-03-26T08:49:27.783060Z","shell.execute_reply":"2024-03-26T08:49:27.786913Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(dpi=150)\nsns.countplot(train_df['label'])","metadata":{"execution":{"iopub.status.busy":"2024-03-26T08:49:27.790391Z","iopub.execute_input":"2024-03-26T08:49:27.790868Z","iopub.status.idle":"2024-03-26T08:49:28.056320Z","shell.execute_reply.started":"2024-03-26T08:49:27.790837Z","shell.execute_reply":"2024-03-26T08:49:28.055088Z"},"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":"2024-03-26T08:49:28.057852Z","iopub.execute_input":"2024-03-26T08:49:28.061780Z","iopub.status.idle":"2024-03-26T08:49:45.714163Z","shell.execute_reply.started":"2024-03-26T08:49:28.061741Z","shell.execute_reply":"2024-03-26T08:49:45.712987Z"},"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":"2024-03-26T08:50:13.197824Z","iopub.execute_input":"2024-03-26T08:50:13.198272Z","iopub.status.idle":"2024-03-26T08:50:13.203606Z","shell.execute_reply.started":"2024-03-26T08:50:13.198243Z","shell.execute_reply":"2024-03-26T08:50:13.202421Z"},"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":"2024-03-26T08:50:19.825851Z","iopub.execute_input":"2024-03-26T08:50:19.826274Z","iopub.status.idle":"2024-03-26T08:50:22.973072Z","shell.execute_reply.started":"2024-03-26T08:50:19.826245Z","shell.execute_reply":"2024-03-26T08:50:22.972233Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df.shape,test_df.shape","metadata":{"execution":{"iopub.status.busy":"2024-03-26T08:50:24.137215Z","iopub.execute_input":"2024-03-26T08:50:24.137616Z","iopub.status.idle":"2024-03-26T08:50:24.143924Z","shell.execute_reply.started":"2024-03-26T08:50:24.137583Z","shell.execute_reply":"2024-03-26T08:50:24.142737Z"},"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":"2024-03-26T08:50:30.928843Z","iopub.execute_input":"2024-03-26T08:50:30.929231Z","iopub.status.idle":"2024-03-26T08:50:30.935561Z","shell.execute_reply.started":"2024-03-26T08:50:30.929203Z","shell.execute_reply":"2024-03-26T08:50:30.934483Z"},"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":"2024-03-26T08:50:48.683813Z","iopub.execute_input":"2024-03-26T08:50:48.684647Z","iopub.status.idle":"2024-03-26T08:50:48.695490Z","shell.execute_reply.started":"2024-03-26T08:50:48.684606Z","shell.execute_reply":"2024-03-26T08:50:48.694272Z"},"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":"2024-03-26T08:51:14.198408Z","iopub.execute_input":"2024-03-26T08:51:14.198815Z","iopub.status.idle":"2024-03-26T08:51:15.752990Z","shell.execute_reply.started":"2024-03-26T08:51:14.198788Z","shell.execute_reply":"2024-03-26T08:51:15.751898Z"},"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 = 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":{"iopub.status.busy":"2024-03-26T08:51:15.755208Z","iopub.execute_input":"2024-03-26T08:51:15.755560Z","iopub.status.idle":"2024-03-26T08:57:48.047963Z","shell.execute_reply.started":"2024-03-26T08:51:15.755531Z","shell.execute_reply":"2024-03-26T08:57:48.047012Z"},"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['label'] = y_pre\nsklearn_sub_df.to_csv('/kaggle/working/sklearn_baseline.csv',index=False)","metadata":{"execution":{"iopub.status.busy":"2024-03-26T08:57:48.049918Z","iopub.execute_input":"2024-03-26T08:57:48.050220Z","iopub.status.idle":"2024-03-26T08:57:53.153314Z","shell.execute_reply.started":"2024-03-26T08:57:48.050196Z","shell.execute_reply":"2024-03-26T08:57:53.152360Z"},"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': 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":{"execution":{"iopub.status.busy":"2024-03-26T09:08:18.986654Z","iopub.execute_input":"2024-03-26T09:08:18.987030Z"},"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":[]}]}