商品类别推荐系统:LightGBM模型

本文介绍了如何利用LightGBM模型为巴西最大的信用卡支付机构Elo开发个性化推荐系统。通过处理历史交易记录和商家信息,进行特征工程,然后训练模型以识别顾客的忠诚度信号和兴趣。最终,探讨了模型的特征重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

机器学习训练营——机器学习爱好者的自由交流空间(入群联系qq:2279055353)

案例介绍

Elo是巴西最大的信用卡支付机构。目前,Elo与巴西的很多商家建立了合作关系,负责向持卡人提供商家的促销或打折信息。但是,这些促销活动对消费者或商家有用吗?引起消费者的兴趣了吗?商家接到“回头客”了吗?要实现这些目的,个性化推荐是关键!Elo已经开发了机器学习模型去理解顾客日常生活里最重要的方面与偏爱,从饮食到购物。本案例将开发算法发现顾客忠实度信号,识别并服务于个人最相关的机会。

  • 代码实现:Python

  • 算法模型:LightGBM

数据描述

文件简述

  • train.csv: 训练集

  • test.csv: 检验集

  • historical_transactions.csv: 每一个card_id直到3个月的历史交易记录。

  • merchants.csv: 商家信息

  • new_merchant_transactions.csv: 每一个card_id在新近商家的2个月的所有交易信息。

加载数据

导入必需的库。

import numpy as np 
import pandas as pd 
import matplotlib.pyplot as plt
import seaborn as sns
import lightgbm as lgb
from sklearn.model_selection import KFold
from sklearn.metrics import mean_squared_error
import warnings
import time
import sys
import datetime
warnings.simplefilter(action='ignore', category=FutureWarning)
pd.set_option('display.max_columns', 500)

由于使用的数据集比较大,为了节省内存,将数值型变量按实际取值范围定义类型。我们定义一个函数reduce_mem_usage实现这个目的。

def reduce_mem_usage(df, verbose=True):
    numerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']
    start_mem = df.memory_usage().sum() / 1024**2    
    for col in df.columns:
        col_type = df[col].dtypes
        if col_type in numerics:
            c_min = df[col].min()
            c_max = df[col].max()
            if str(col_type)[:3] == 'int':
                if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max:
                    df[col] = df[col].astype(np.int8)
                elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max:
                    df[col] = df[col].astype(np.int16)
                elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max:
                    df[col] = df[col].astype(np.int32)
                elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max:
                    df[col] = df[col].astype(np.int64)  
            else:
                if c_min > np.finfo(np.float16).min and c_max < np.finfo(np.float16).max:
                    df[col] = df[col].astype(np.float16)
                elif c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max:
                    df[col] = df[col].astype(np.float32)
                else:
                    df[col] = df[col].astype(np.float64)    
    end_mem = df.memory_usage().sum() / 1024**2
    if verbose: print('Mem. usage decreased to {:5.2f} Mb ({:.1f}% reduction)'.format(end_mem, 100 * (start_mem - end_mem) / start_mem))
    return df

我们先加载数据集new_merchant_transactions.csv and historical_transactions.csv. 实际上,这两个数据文件包括相同的变量,区别仅仅在于关于一个参考日期的时间。而且,逻辑特征转换成数值型。

### 使用LightGBM实现商品购买预测 #### 数据准备与预处理 在构建商品购买预测模型之前,需先准备好数据并进行必要的预处理工作。这通常涉及对原始数据的理解、清洗和转换,确保其适合输入到机器学习模型中。 对于用户特征部分,可以考虑收集用户的年龄、性别、职业等基本信息;同时也要关注用户的行为模式,比如最近一段时间内的点击次数、购买频率等动态指标[^5]。针对商品本身,则应提取诸如价格区间、销售热度、评价分数等属性作为静态描述因素。此外,还需创建反映特定用户对某件商品兴趣程度的新变量,例如过去是否有过相似物品的交互记录等。 完成上述操作之后,还需要进一步执行如下步骤来完善整个流程: - **缺失值填充**:检查是否存在空缺字段,并采取适当措施填补这些空白处。 - **异常检测**:识别潜在离群点并对它们做相应调整或剔除处理。 - **标准化/归一化**:使不同尺度下的数值能够公平比较。 - **编码类别型变量**:将非数字类型的标签转化为计算机易于理解的形式,如整数索引或是独热向量表示法。 ```python import pandas as pd from sklearn.preprocessing import LabelEncoder, StandardScaler from sklearn.model_selection import train_test_split # 假设df是一个包含了所有必要列名的数据框对象 le = LabelEncoder() for col in ['gender', 'occupation']: df[col] = le.fit_transform(df[col]) scaler = StandardScaler() numerical_cols = ['age', 'price'] df[numerical_cols] = scaler.fit_transform(df[numerical_cols]) X_train, X_test, y_train, y_test = train_test_split( df.drop('target', axis=1), df['target'], test_size=.2, random_state=42) ``` #### 构建LightGBM模型 一旦完成了前期准备工作,就可以着手建立LightGBM实例来进行训练了。这里会涉及到参数设定环节,其中一些关键配置项可能会影响最终性能表现,因此建议依据具体应用场景灵活调整。 值得注意的是,在正式调用`train()`函数前,最好先把样本集构造成专门设计好的`lgb.Dataset`结构体形式,以便于后续更高效的运算过程[^3]。 ```python import lightgbm as lgb dtrain = lgb.Dataset(X_train, label=y_train) params = { 'objective': 'binary', 'metric': {'auc'}, 'boosting_type': 'gbdt' } bst = lgb.train(params=params, train_set=dtrain, num_boost_round=100, valid_sets=[dtrain], early_stopping_rounds=10) ``` #### 模型评估与解释 经过一轮或多轮迭代优化后得到满意的模型版本,此时可以通过多种方式检验其泛化能力。除了常规意义上的混淆矩阵、精确度得分之外,还可以借助ROC-AUC曲线直观展示正负两类别的区分效果;另外,SHAP值分析工具可以帮助揭示各个自变量的重要性及其贡献方向,从而增强业务人员对该系统的信任感[^2]。 ```python from sklearn.metrics import roc_auc_score import shap y_pred_prob = bst.predict(X_test) print(f'AUC Score on Test Set: {roc_auc_score(y_test, y_pred_prob)}') explainer = shap.TreeExplainer(bst) shap_values = explainer.shap_values(X_test.iloc[:100]) shap.summary_plot(shap_values[1], X_test.iloc[:100]) ```
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值