项目一描述
(需要数据练习的可以私聊)
# 现有文件名为aviation的航空客运信息数据集,共包括5000个样本,每个样本有55个属性,其中runoff_flag代表是否流失,
# 要求通过这些数据构建客户流失预警模型,而且由于营销资源有限,希望结合客户特征进行有针对性的、高效率的开展客户挽留。
# 具体任务如下:
# 1.读入aviation数据集,设置MEMBER_NO为索引列。(6分)
# 2.剔除重复值、缺失值。(6分)
# 3.随机抽取500样本,切片特征X和标签Y。(6分)
# 4.使用交叉验证方法(10折)比较逻辑回归、决策树算法性能差异,评估指标用F1分数(6分)
# 5.使用网格搜索对上题中F1分数较高的算法进行超参数调优。(5分)
# 6.使用4、5中确定的最优算法和最优参数建立模型。(5分)
# 7.按照6:4划分数据集。(4分)
# 8.使用训练集数据进行模型训练,对测试集数据进行预测,打印混淆矩阵。(4分)
# 9.打印精确率、召回率、F1分数和AUC值。(3分)
# 10.画出ROC曲线。(3分)
数据展示
代码如下
# 1.读入aviation数据集,设置MEMBER_NO为索引列。(6分)
import warnings
import pandas as pd
import numpy as np
# 忽略警告
warnings.filterwarnings('ignore')
df = pd.read_excel(r'../datas/aviation.xls',index_col='MEMBER_NO')
# 2.剔除重复值、缺失值。(6分)
df.drop_duplicates(inplace=True)
df.dropna(inplace=True)
# 3.随机抽取500样本,切片特征X和标签Y。(6分)
df_sampel = df.sample(500,random_state=0)
X = df_sampel.iloc[:,:-1]
Y = df_sampel.iloc[:,-1]
# 4.使用交叉验证方法(10折)比较逻辑回归、决策树算法性能差异,评估指标用F1分数(6分)
from sklearn.model_selection import cross_val_score
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
model_lr = LogisticRegression()
model_dt = DecisionTreeClassifier()
score_lr = cross_val_score(model_lr,X,Y,scoring='f1',cv=10)
score_dt = cross_val_score(model_dt,X,Y,scoring='f1',cv=10)
print('逻辑分数',np.mean(score_lr,axis=0))
print('决策分数',np.mean(score_dt,axis=0))
# 5.使用网格搜索对上题中F1分数较高的算法进行超参数调优。(5分)
# 逻辑回归大于决策树,所以下面选择决策树来建模训练
from sklearn.model_selection import GridSearchCV
params = {
'C':[0.1,0.3,0.5,1,3,5,10,30,50,100],
'max_iter':[10,30,100,300,500,1000,3000,5000]
}
model_be = GridSearchCV(model_lr,param_grid=params,scoring='f1')
model_be.fit(X,Y)
params_be = model_be.best_params_
# 6.使用4、5中确定的最优算法和最优参数建立模型。(5分)
from sklearn.pipeline import Pipeline
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
model_pip = Pipeline([
# ('ss',StandardScaler()),
# ('pca',PCA(n_components=3)),
('lr', LogisticRegression(C=params_be