简介 本项目应用XGBoost算法对数据进行分析并建模预测信用卡交易是否具有欺骗性,属于机器学习相关的二分类任务。
XGboost XGBoost 是一个优化的分布式梯度提升库 ,旨在实现高效、灵活和便携。XGBoost 不仅提供了一个强大的机器学习算法,也提供了一个高度灵活的接口,可以对算法进行详细的控制。
正则化 :引入了正则化参数,有助于防止模型过拟合。这使得 XGBoost 的性能通常优于其他梯度提升算法。
并行处理 :并行处理能够更快地构建模型。这是通过在每一次迭代中,利用所有可用的 CPU 核心来计算决策树的节点。
灵活性 :允许用户自定义优化目标和评估标准。
处理缺失值 :XGBoost 有内置的方法来处理缺失值。
剪枝 :与 GBM 不同,XGBoost 中的树是深度优先生成的,然后通过剪枝来防止过拟合。
关于 **model_xgb.feature_importances_**:
feature_importances_ 是 XGBoost 模型的一个属性,它返回一个数组.
表示每个特征在模型中的重要性 (权重)。这个重要性是通过计算每个特征在模型中所有树的决策中的平均贡献来得到的。
这个属性可以帮助你理解模型的决策过程,也可以帮助你选择和优化特征。例如,你可以使用 feature_importances_ 来识别和删除那些对模型贡献不大的特征,从而简化模型并可能提高其性能。
逻辑回归 逻辑回归是一种统计模型,用于预测二元或多元分类问题的概率。
在二元逻辑回归中,模型预测的是某个事件发生的概率。
例如,一个电子邮件是垃圾邮件的概率,或者一个患者有某种疾病的概率。
逻辑回归的主要优点:
它不仅可以预测一个事件是否会发生(即,分类),还可以预测事件发生的概率 。这使得逻辑回归在许多领域,如医学、经济学和社会科学中,都有广泛的应用。
逻辑回归的工作原理:
它使用逻辑函数(也称为 sigmoid 函数)将线性回归的输出转换为介于 0 和 1 之间的概率。 然后,这个概率可以用来做出预测。例如,如果预测的概率大于 0.5,我们可以预测事件会发生;如果预测的概率小于 0.5,我们可以预测事件不会发生。
逻辑回归重要特性:
它可以使用一种称为“最大似然估计” 的方法来估计模型参数。这种方法的目标是找到一组参数,使得给定这组参数,观察到的数据出现的概率最大。
逻辑回归还有一些其他的优点,例如,它可以处理分类和连续的特征,可以容易地更新模型以包含新的数据,而且它的输出可以很容易地解释。
代码 导入相关工具包 1 2 3 4 5 6 7 8 9 10 11 12 13 14 import pandas as pdimport numpy as npimport seaborn as snsimport matplotlib.pyplot as pltfrom imblearn.over_sampling import SMOTEfrom sklearn.model_selection import train_test_splitfrom sklearn.linear_model import LogisticRegression as LRfrom sklearn.model_selection import cross_val_score as CVSfrom xgboost import XGBClassifier as XGBCfrom sklearn.metrics import accuracy_score, recall_score, precision_score, f1_scoreimport warningswarnings.filterwarnings('ignore' )
Seaborn Seaborn 基于 matplotlib 的 Python 数据可视化库。它提供了一种高度交互式界面,方便用户无需复杂代码即可制作出具有吸引力的统计图形 。
数据读取及预处理 1 2 3 4 5 6 7 df=pd.read_csv('./card_transdata.csv' ) df.head() print ('数据维度为:\n' ,df.shape)print ('缺失值为:\n' ,df.isnull().sum ()) print ('重复值\n' ,df.duplicated().sum ()) df.describe()
探索性分析 1 2 3 4 5 6 7 plt.rcParams['font.sans-serif' ]=['Microsoft YaHei' ] plt.rcParams['axes.unicode_minus' ]=False n_sample=df.shape[0 ] n_0_sample=df.fraud.value_counts()[0 ] n_1_sample=df.fraud.value_counts()[1 ] print ('样本个数:{};0占{};1占{}' .format (n_sample,n_0_sample/n_sample,n_1_sample/n_sample))
样本个数:1000000;0占0.912597;1占0.087403
1 2 3 4 5 6 7 8 9 10 11 12 13 14 df_t=df.fraud.value_counts().reset_index() df_t.replace({0 :'非欺诈' ,1 :'欺诈' },inplace=True ) fig=plt.figure(figsize=(10 ,4 )) ax1=fig.add_subplot(1 ,2 ,1 ) ax1.spines['top' ].set_visible(False ) ax1.spines['right' ].set_visible(False ) sns.barplot(x='index' ,y='fraud' ,data=df_t) plt.xlabel('' ) plt.ylabel('count' ,fontdict={'fontsize' :12 }) ax2=fig.add_subplot(1 ,2 ,2 ) plt.pie(x=df_t['fraud' ],labels=df_t['index' ],autopct='%1.1f%%' ,explode=[0.1 ,0 ],startangle=90 ,counterclock=False ,wedgeprops={'linewidth' :1 ,'edgecolor' :"black" }) plt.axis('square' ) plt.show()
1 2 3 4 correlation_matrix=df.corr() sns.heatmap(correlation_matrix,annot=True ,cmap='coolwarm' ,linewidths=0.5 )
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 X=df.iloc[:,:-1 ] y=df.iloc[:,-1 ] smote=SMOTE() X_resampled,y_resampled=smote.fit_resample(X,y) n_sample_new=X_resampled.shape[0 ] n_0_sample_new=y_resampled.value_counts()[0 ] n_1_sample_new=y_resampled.value_counts()[1 ] print ('样本个数:{};0占{};1占{}' .format (n_sample_new,n_0_sample_new/n_sample_new,n_1_sample_new/n_sample_new))
划分训练集和测试集 1 X_train,X_test,y_train,y_test=train_test_split(X_resampled,y_resampled,test_size=0.2 ,random_state=1025 )
逻辑回归和XGboost 1 2 3 4 5 6 7 8 9 10 11 12 model_LR=LR(penalty="l2" ) model_LR.fit(X_train,y_train) model_LR.score(X_test,y_test) CVS(model_LR,X_train,y_train,cv=5 ).mean() model_xgb=XGBC(n_estimators=100 ,max_depth=3 ) model_xgb.fit(X_train,y_train) model_xgb.score(X_test,y_test) CVS(model_xgb,X_train,y_train,cv=5 ).mean() y_test_pred=model_xgb.predict(X_test)
评价 1 2 3 4 5 6 7 8 9 10 11 12 13 auc=accuracy_score(y_test,y_test_pred) print (f"准确率为:{format (auc)} " )recall=recall_score(y_test,y_test_pred) print (f"召回率为:{format (recall)} " )pre=precision_score(y_test,y_test_pred) print (f"精确度为:{format (pre)} " )f1=f1_score(y_test,y_test_pred) print (f"F1-SCORE为:{format (f1)} " )model_xgb.feature_importances_