【数据挖掘】线上商城用户购买倾向预测挑战赛

本赛题是由科大讯飞xDatawhale联合举办
地址:https://challenge.xfyun.cn/topic/info?type=buy-propensity


适千里者,三月聚粮。


提示:以下是本篇文章正文内容

一、赛题概要

1.赛题背景

电子商务作为数字经济中规模最大、表现最活跃、发展势头最好的新业态新动能,是新发展格局蓝图中非常重要的一环。在保持高速发展的同时,如何从历史数据中找出规律,去预测用户未来的购买需求,让最合适的商品遇见最需要的人,是大数据应用在精准营销中的关键问题,也是所有电商平台在做智能化升级时所需要的核心技术。

如何使用机器学习来识别最有价值的潜在客户成为挑战。面对如此头疼的问题,某电商平台将部分用户行为数据开放,诚邀大家帮助他们建立用户购买倾向预测模型来预测用户是否下单购买(敏感信息已脱敏)。

2.赛题任务

给定某电商平台实际业务中的用户相关数据,包含25个相关的字段,其中“label”字段为用户是否下单购买(1为已下单,0为未下单)。任务目标是通过训练集训练模型,来预测测试集中**“label”字段的具体值**。

3.赛题数据

赛题数据由训练集和测试集组成,总数据量超过100w,包含25个特征字段。为了保证比赛的公平性,将会从中抽取40万条作为训练集,10万条作为测试集,同时会对部分字段信息进行脱敏。

4.评价指标

AUC评价指标(该指标常用于二分类的预测任务中)

from Sklearn.metrics import roc_auc_score
y_ture = [0 , 1 , 0 , 1 , 1 , 1 ]
y_pred = [0.5 , 0.5 , 0.5 , 0.5 , 0.5 , 0.5 ]
score = roc_auc_score(y_true , y_pred)

二、数据探索(EDA)

处于项目特点,我们这次选择使用 jupyter notebook 进行所有操作。

1.导入库

#导入库
import pandas as pd
import os
import gc
import lightgbm as lgb
import xgboost as xgb
from catboost import CatBoostRegressor
from hyperopt import hp, fmin, tpe
from sklearn.linear_model import SGDRegressor, LinearRegression, Ridge
from sklearn.preprocessing import MinMaxScaler
from gensim.models import Word2Vec
import math
import numpy as np
from numpy.random import RandomState
from tqdm import tqdm
from sklearn.model_selection import StratifiedKFold, KFold
from sklearn.metrics import accuracy_score, f1_score, roc_auc_score, log_loss
import matplotlib.pyplot as plt
import time
import warnings
warnings.filterwarnings('ignore')

2.读取并查看数据

# 读取数据
train = pd.read_csv('train.csv')
test = pd.read_csv('test.csv')

# 使用.head()查看数据前5行
train.head()
test.head()

结果:
在这里插入图片描述

# 使用.describe()查看数据的描述性统计信息
train_data.describe()

结果
在这里插入图片描述

3.相关性分析

# 使用.corr()进行相关性分析,并对相关性排序
train.corr()
corr['label'].sort_values(ascending=False)

结果

label     1.000000
col_18    0.752087
col_21    0.654163
col_20    0.608759
col_8     0.384398
col_10    0.373050
col_9     0.258029
col_16    0.137568
col_4     0.136632
col_17    0.128577
col_12    0.062204
col_19    0.052201
col_22    0.052065
col_14    0.050536
col_13    0.048497
col_11    0.046679
col_6     0.042852
col_2     0.028473
col_23    0.027985
col_15    0.025149
col_3     0.021898
col_7     0.016974
col_1     0.006649
uid      -0.001446
col_5    -0.038957
Name: label, dtype: float64

可以看到col_5是负相关,在后续的处理中可以把它拿掉(但后续发现去不去掉对整体模型的分数没有影响。)

三、构建模型

1.数据准备

代码如下:

# 将除客户ID、目标值、col_5字段,作为特征值字段
features = [f for f in data.columns if f not in ['uid' , 'label' , 'col_5']]
# 重新设置训练集和测试集
train = data[data['label'].notnull()].reset_index(drop=True)
test = data[data['label'].isnull()].reset_index(drop=True)

# 训练集特征值
x_train = train[features]
# 测试集特征值
x_test = test[features]

# 训练集的目标值
y_train = train['label']

2.构建模型

这里我们使用lgb、xgb、cat三个分类器进行模型训练

# 定义函数
# 设置模型
def cv_model(clf, train_x, train_y, test_x, clf_name):
    folds = 5
    seed = 2022
    kf = KFold(n_splits=folds, shuffle=True, random_state=seed)

    train = np.zeros(train_x.shape[0])
    test = np.zeros(test_x.shape[0])

    cv_scores = []

    for i, (train_index, valid_index) in enumerate(kf.split(train_x, train_y)):
        print('************************************ {} ************************************'.format(str(i+1)))
        trn_x, trn_y, val_x, val_y = train_x.iloc[train_index], train_y[train_index], train_x.iloc[valid_index], train_y[valid_index]

        if clf_name == "lgb":
            train_matrix = clf.Dataset(trn_x, label=trn_y)
            valid_matrix = clf.Dataset(val_x, label=val_y)

            params = {
                'boosting_type': 'gbdt',
                'objective': 'binary',
                'metric': 'auc',
                'min_child_weight': 5,
                'num_leaves': 2 ** 5,
                'lambda_l2': 10,
                'feature_fraction': 0.7,
                'bagging_fraction': 0.7,
                'bagging_freq': 10,
                'learning_rate': 0.2,
                'seed': 2022,
                'n_jobs':-1
            }

            model = clf.train(params, train_matrix, 50000, valid_sets=[train_matrix, valid_matrix], 
                        categorical_feature=[], verbose_eval=3000, early_stopping_rounds=200)
            val_pred = model.predict(val_x, num_iteration=model.best_iteration)
            test_pred = model.predict(test_x, num_iteration=model.best_iteration)
            
            print(list(sorted(zip(features, model.feature_importance("gain")), key=lambda x: x[1], reverse=True))[:20])
                
        if clf_name == "xgb":
            train_matrix = clf.DMatrix(trn_x , label=trn_y)
            valid_matrix = clf.DMatrix(val_x , label=val_y)
            test_matrix = clf.DMatrix(test_x)
            
            params={'boosting_type': 'gbdt',
                'objective': 'binary',
                'metric': 'auc',
                'bagging_fraction': 0.8864320989515848,
                'bagging_freq': 10,
                'feature_fraction': 0.7719195132945438,
                'lambda_l1': 4.0642058550131175,
                'lambda_l2': 0.7571744617226672,
                'learning_rate': 0.33853400726057015,
                'max_depth': 10,
                'min_gain_to_split': 0.47988339149638315,
                'num_leaves': 48,
                'seed': 2022,
                'n_jobs':-1}
            
            
            watchlist = [(train_matrix, 'train'),(valid_matrix, 'eval')]
            
            model = clf.train(params, train_matrix, num_boost_round=50000, evals=watchlist, verbose_eval=3000, early_stopping_rounds=200)
            val_pred  = model.predict(valid_matrix, ntree_limit=model.best_ntree_limit)
            test_pred = model.predict(test_matrix , ntree_limit=model.best_ntree_limit)
                
        if clf_name == "cat":
            params = {'learning_rate': 0.2, 'depth': 5, 'l2_leaf_reg': 10, 'bootstrap_type': 'Bernoulli',
                    'od_type': 'Iter', 'od_wait': 50, 'random_seed': 11, 'allow_writing_files': False}
            
            model = clf(iterations=20000, **params)
            model.fit(trn_x, trn_y, eval_set=(val_x, val_y),
                    cat_features=[], use_best_model=True, verbose=3000)
            
            val_pred  = model.predict(val_x)
            test_pred = model.predict(test_x)
            
        train[valid_index] = val_pred
        test = test_pred / kf.n_splits
        cv_scores.append(roc_auc_score(val_y, val_pred))
        
        print(cv_scores)
    
    print("%s_scotrainre_list:" % clf_name, cv_scores)
    print("%s_score_mean:" % clf_name, np.mean(cv_scores))
    print("%s_score_std:" % clf_name, np.std(cv_scores))
    return train, test
    
def lgb_model(x_train, y_train, x_test):
    lgb_train, lgb_test = cv_model(lgb, x_train, y_train, x_test, "lgb")
    return lgb_train, lgb_test

def xgb_model(x_train, y_train, x_test):
    xgb_train, xgb_test = cv_model(xgb, x_train, y_train, x_test, "xgb")
    return xgb_train, xgb_test

def cat_model(x_train, y_train, x_test):
    cat_train, cat_test = cv_model(CatBoostRegressor, x_train, y_train, x_test, "cat") 
    return cat_train, cat_test
    
lgb_train, lgb_test = lgb_model(x_train, y_train, x_test)

查看运行结果
在这里插入图片描述

3.储存数据

test['label'] = lgb_test
test[['uid','label']].to_csv('test_lgb.csv', index=False)

4.上传结果查看分数

在这里插入图片描述

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值