目录
本代码将实现使用PCA降维减少数据的维度,并使用下采样处理失衡数据;然后使用随机森林进行模型训练,最后使用混淆矩阵和AUC-ROC曲线评价模型效果。
1.数据标准化
from sklearn.decomposition import PCA
import pandas as pd
import numpy as np
data = pd.read_csv(r".\creditcard.csv", encoding='utf8', engine='python')
'''数据标准化: Z标准化'''
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
a = data[['Amount']]
data['Amount'] = scaler.fit_transform(data[['Amount']])
data = data.drop(['Time'] , axis=1) #删除无用列
2.下采样处理失衡数据
#下采样解决样本不均衡问题
positive_eg= data[data['Class'] == 0] #获取到了所有标签(class)为 0的数据
negative_eg = data[data['Class'] == 1] #获取到了所有标签(class)为 1的数据
np.random.seed(seed=4)
positive_eg = positive_eg.sample(len(negative_eg)) #sample表示随机从参数中抽取数据
# #拼接数据
data_c = pd.concat([positive_eg, negative_eg]) # 数据组合
print(data_c)
3.PCA降维
#下采样数据
X = data_c.drop('Class', axis=1) #对data_c数据进行划分
y = data_c.Class
# 原始数据
X_whole = data.drop('Class', axis=1)
y_whole = data.Class
#PCA降维
pca = PCA(n_components=0.90)
pca.fit(X) #进行训练不需要传入y
pca.fit(X_whole)
new_x = pca.transform(X)
new_x_whole = pca.transform(X_whole)
4.数据切分
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(new_x, y, test_size = 0.3, random_state = 0)
x_train_w, x_test_w, y_train_w, y_test_w= train_test_split(new_x_whole, y_whole, test_size = 0.2, random_state = 0)
5.模型训练
# 进行预测分析
"""
n_estimators:决策树的个数
max_features:特征的个数
此处可以根据需要设置每棵决策树的深度以及最小叶子节点的样本数等
"""
from sklearn.ensemble import RandomForestClassifier
rf = RandomForestClassifier(
n_estimators=100,
max_features=0.8,
random_state=60,
criterion='entropy'
)
rf.fit(x_train, y_train)
6.测试
from sklearn import metrics
'''使用测试集数据进行测试[小测试集]'''
test_predicted = rf.predict(x_test)
print(metrics.classification_report(y_test, test_predicted)) # 小数据集的测试数据集
'''使用测试集数据进行测试[大测试集]'''
test_predicted_big = rf.predict(x_test_w) #大测试数据集进行预测
#绘制混淆矩阵
print(metrics.classification_report(y_test_w, test_predicted_big))
7.分类的性能评价
'''AUC值的计算'''
y_pred_proba = rf.predict_proba(x_test_w)
a = y_pred_proba[:, 1]
auc_result = metrics.roc_auc_score(y_test_w, a)
'''绘制ROC-AUC曲线'''
import matplotlib.pyplot as plt
from sklearn.metrics import roc_curve #得到不同阈值的ROC
#计算ROC曲线的点
fpr, tpr, thresholds = roc_curve(y_test_w, a)
#绘制ROC曲线
plt.figure()
plt.plot(fpr, tpr, color= 'darkorange', lw=2, label='ROC curve(area=%0.2f)'% auc_result)
plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--') #函数来绘制一条从点(0,0)到点(1,1)的线段。
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver Operating Characteristic')
plt.legend()
plt.show()
8.结果
召回率接近1,并且ROC曲线的面积接近1,证明模型效果较好。