电商平台用户退款预测模型(Python语言)

电商平台用户退款预测模型(Python语言)

(…待改进)

# 加载需要用到的包
import pandas as pd
import numpy as np

import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
plt.style.use('fivethirtyeight')

from warnings import filterwarnings
filterwarnings('ignore')
orders=pd.read_excel('chargepre.xlsx')
orders
goodsIDorderAmountpaymentchanelIDplatfromTypediscountpayyearpaymonthchargebackusercount_total_count
1PR0009401978.471770.81渠道-0530WechatMP0.1049602019101
2PR000512521.60511.59渠道-0765WechatMP0.019191201951
3PR000398466.89443.55渠道-0007WechatMP0.0499902019112
4PR0003512337.012328.43渠道-0985APP0.0036712019102
5PR0004332178.202162.14渠道-9527APP0.007373201911
6PR0007714949.654879.94渠道-0007WechatMP0.0140842019111
7PR000828565.26556.96渠道-0896WechatMP0.014684201991
8PR000147430.34373.46渠道-0465APP0.132175201971
9PR000060694.52664.79渠道-0530APP0.042807201932
10PR000072453.83371.50渠道-0283WechatMP0.1814122019122
11PR000898529.57488.08渠道-0530WEB0.0783472019112

104552 rows × 10 columns

orders.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 104552 entries, 1 to 104552
Data columns (total 10 columns):
goodsID                  104552 non-null object
orderAmount              104552 non-null float64
payment                  104552 non-null float64
chanelID                 104552 non-null object
platfromType             104552 non-null object
discount                 104552 non-null float64
payyear                  104552 non-null int64
paymonth                 104552 non-null int64
chargeback               104552 non-null object
usercount_total_count    104552 non-null int64
dtypes: float64(3), int64(3), object(4)
memory usage: 8.8+ MB
plt.figure(figsize=(20,10))
sns.pairplot(orders)

在这里插入图片描述

sns.heatmap(orders.corr(),annot=True,cmap='viridis')

在这里插入图片描述

target_array = orders['chargeback'].copy()
train =  orders.drop(orders[['chargeback']],axis=1)
test = train
from sklearn import preprocessing

le = preprocessing.LabelEncoder()

for feature in ['goodsID','chanelID','platfromType','orderAmount','payment','discount','payyear','paymonth','usercount_total_count']:
    train[feature]=le.fit_transform(train[feature])
    # test[feature]=le.transform(test[feature])
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
train = pd.DataFrame(scaler.fit_transform(train), columns=train.columns)
test = pd.DataFrame(scaler.transform(test), columns=test.columns)
X = train
y = target_array
 
X_to_be_predicted = test

from sklearn.model_selection import train_test_split
 
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25)
from lightgbm import LGBMClassifier

model = LGBMClassifier(learning_rate=0.1,
n_estimators=10000,
max_depth=5,
min_child_weight=1,
gamma=0,
subsample=0.8,
colsample_bytree=0.8,
nthread=4,
scale_pos_weight=3,
seed=10)
model.fit(X_train, y_train)
[LightGBM] [Warning] Unknown parameter: gamma
[LightGBM] [Warning] num_threads is set with n_jobs=-1, nthread=4 will be ignored. Current value: num_threads=-1
[LightGBM] [Warning] Accuracy may be bad since you didn't explicitly set num_leaves OR 2^max_depth > num_leaves. (num_leaves=31).





LGBMClassifier(boosting_type='gbdt', class_weight=None, colsample_bytree=0.8,
        gamma=0, importance_type='split', learning_rate=0.1, max_depth=5,
        min_child_samples=20, min_child_weight=1, min_split_gain=0.0,
        n_estimators=10000, n_jobs=-1, nthread=4, num_leaves=31,
        objective=None, random_state=None, reg_alpha=0.0, reg_lambda=0.0,
        scale_pos_weight=3, seed=10, silent=True, subsample=0.8,
        subsample_for_bin=200000, subsample_freq=0)
from sklearn.metrics import classification_report
 
#打印评分
print(classification_report(y_train, model.predict(X_train)))
#测试集
print(classification_report(y_test, model.predict(X_test)))

y_predict = model.predict(X_to_be_predicted)
y_predict
              precision    recall  f1-score   support

           否       1.00      0.99      1.00     68085
           是       0.96      0.98      0.97     10329

   micro avg       0.99      0.99      0.99     78414
   macro avg       0.98      0.99      0.98     78414
weighted avg       0.99      0.99      0.99     78414

              precision    recall  f1-score   support

           否       0.87      0.93      0.90     22687
           是       0.12      0.06      0.08      3451

   micro avg       0.82      0.82      0.82     26138
   macro avg       0.50      0.50      0.49     26138
weighted avg       0.77      0.82      0.79     26138






array(['否', '否', '否', ..., '否', '否', '否'], dtype=object)

训练结果明显过拟合,由于原始数据(0/1)比例十分不均衡,接近9:1,故导致训练结果异常。
关于样本不均衡情况,应当进行如何处理?
根据样本数据又是否能高精度预测呢?

当处理数据时,可能会出现缺失值的情况,因此需要进行缺失值的处理。下面是一些常见的处理缺失值的方法。 1. 删除包含缺失值的行/列 如果缺失值比较少,可以考虑直接删除包含缺失值的行或列。对于缺失值较多的情况,建议删除缺失值所在的整个列。以下是一个简单的代码示例: ```python import pandas as pd # 读取数据集 df = pd.read_csv('data.csv') # 删除包含缺失值的行 df = df.dropna() # 删除包含缺失值的列 df = df.dropna(axis=1) ``` 在上述代码中,`dropna()`函数可以删除包含缺失值的行或列,`axis`参数默认为0,表示删除行,如果指定为1,则表示删除列。 2. 填充缺失值 如果缺失值比较少,可以考虑使用均值、中位数、众数等方法进行填充。以下是一个简单的代码示例: ```python import pandas as pd # 读取数据集 df = pd.read_csv('data.csv') # 使用均值填充缺失值 df = df.fillna(df.mean()) # 使用中位数填充缺失值 df = df.fillna(df.median()) # 使用众数填充缺失值 df = df.fillna(df.mode()) ``` 在上述代码中,`fillna()`函数可以用来填充缺失值,使用`mean()`、`median()`、`mode()`函数可以计算均值、中位数、众数。注意,对于非数值类型的数据,只能使用众数进行填充。 3. 插值填充缺失值 如果缺失值比较多,可以考虑使用插值方法进行填充。插值方法可以根据已知数据的值来推断缺失值。以下是一个简单的代码示例: ```python import pandas as pd # 读取数据集 df = pd.read_csv('data.csv') # 使用线性插值填充缺失值 df = df.interpolate(method='linear') # 使用多项式插值填充缺失值 df = df.interpolate(method='polynomial', order=2) ``` 在上述代码中,`interpolate()`函数可以用来进行插值填充,可以使用`linear`方法进行线性插值,使用`polynomial`方法进行多项式插值,`order`参数指定多项式的阶数。 4. 使用模型预测填充缺失值 如果缺失值比较多,并且数据集较大,可以考虑使用模型进行预测填充。例如,可以使用线性回归模型或者随机森林模型进行预测填充。以下是一个简单的代码示例: ```python import pandas as pd from sklearn.ensemble import RandomForestRegressor # 读取数据集 df = pd.read_csv('data.csv') # 构建随机森林模型 model = RandomForestRegressor() # 分割数据集为已知和未知数据 known_data = df[df['缺失列'].notnull()] unknown_data = df[df['缺失列'].isnull()] # 训练模型 model.fit(known_data.drop('缺失列', axis=1), known_data['缺失列']) # 预测缺失值 unknown_data['缺失列'] = model.predict(unknown_data.drop('缺失列', axis=1)) # 合并数据集 df = pd.concat([known_data, unknown_data]) ``` 在上述代码中,首先构建随机森林模型,然后将数据集分割为已知和未知数据,训练模型并预测缺失值,最后将已知数据和预测出来的未知数据合并在一起。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值