参考1:
【案例】交易数据异常检测_CHERISHGF的博客-CSDN博客
参考2:
机器学习-逻辑回归-xyk检测任务_小刘鸭!的博客-CSDN博客_values.ravel()
完整代码 3.9版本可用
from audioop import cross
import imp
import pandas as pd
# import matplotlib as plt
import matplotlib.pyplot as plt
import numpy as np
#大数变成-1,1之间
from sklearn.preprocessing import StandardScaler
#切分数据集
# from sklearn.cross_decomposition import train_test_split #已不能用
from sklearn.model_selection import train_test_split
#模型评估、正则化评估
from sklearn.linear_model import LogisticRegression
#from sklearn.cross_validation import KFold.cross_val_score#这个也没有了
from sklearn.model_selection import KFold, cross_val_score
from sklearn.metrics import confusion_matrix,recall_score,classification_report
import itertools# 笛卡尔积
data=pd.read_csv("creditcard.csv")
data.head
# print(data.head)
count_classes=pd.value_counts(data['Class'],sort=True).sort_index()
# print(count_classes)
count_classes.plot(kind="bar")
plt.title("Fraud class histogram")
plt.xlabel("Class")
plt.ylabel("Frequency")
# plt.show() #显示图像
#import matplotlib.pyplot as plt 解决plt报错 module 'matplotlib' has no attribute 'title'
# plt.title("fraud class histogram")
# plt.xlabel("Class")
# plt.ylabel("frequency")
#缩短Amount值的范围,加入.values转换格式:values方法将Series对象转化成numpy的ndarray,再用ndarray的reshape方法.
data['normAmount']=StandardScaler().fit_transform(data['Amount'].values.reshape(-1,1))
data=data.drop(["Time","Amount"],axis=1)
data.head
# print(data.head)
#下采样:让多的样本变的和少的样本数量一样少#上采样,让少的样本生成后变得和多得一样多
X=data.iloc[:,data.columns!='Class']
Y=data.iloc[:,data.columns=='Class']
# X = data.ix[:, data.columns != 'Class']
# Y = data.ix[:, data.columns == 'Class']
number_records_fraud=len(data[data.Class==1])
fraud_indices=np.array(data[data.Class==1].index)
normal_indices=data[data.Class==0].index#随机选择正常的
random_normal_indices = np.random.choice(normal_indices, number_records_fraud, replace = False)#replace = False 再一次抽取中,抽样的样本不可重复出现
random_normal_indices = np.array(random_normal_indices)
under_sample_indices=np.concatenate([fraud_indices,random_normal_indices])#np合并 *** 作
under_sample_data=data.iloc[under_sample_indices,:]
X_undersample=under_sample_data.iloc[:,under_sample_data.columns!='Class']
Y_undersample=under_sample_data.iloc[:,under_sample_data.columns=='Class']
print("numberof normal :",len(under_sample_data[under_sample_data.Class==0]))
print("percentage of normal transaction:",len(under_sample_data[under_sample_data.Class==0])/len(under_sample_data))
print("numberof fraud :",len(under_sample_data[under_sample_data.Class==1]))
print("percentage of fraud transaction:",len(under_sample_data[under_sample_data.Class==1])/len(under_sample_data))
print("Total number of transactions in resampled data:",len(under_sample_data))
#交叉验证 切分训练集与测试集,训练集平均切分,训练集中包含验证集
##原始数据集切分,用原始的测试
X_train, X_test, y_train, y_test=train_test_split(X,Y,test_size=0.3)
print("number train dataset:",len(X_train))
print("number test dataset:",len(X_test))
print("total number of transactions:",len(X_train)+len(X_test))
#下采样的数据集切分
X_train_undersample, X_test_undersample, y_train_undersample, y_test_undersample =train_test_split(X_undersample, Y_undersample,test_size= 0.3,random_state= 0)
print("")
print("number train dataset:",len(X_train_undersample))
print("number test dataset:",len(X_test_undersample))
print("total number:",len(X_train_undersample)+len(X_test_undersample))
#评估方法 TP正正 FN正的判错 FP错的判正 TN错的判错, Recall=TP/(TP+FN)
def printing_Kfold_scores(X_train_data,y_train_data):
fold = KFold(5, shuffle=False)
fold.get_n_splits(X_train_data)
c_param_range = [0.01, 0.1, 1, 10, 100]#逻辑回归中的,正则化惩罚项
#result可视化显示
results_table = pd.DataFrame(index=range(len(c_param_range), 2), columns=['C_parameter', 'Mean recall score'])
results_table['C_parameter'] = c_param_range
j = 0
for c_param in c_param_range:#看看各个惩罚项的好不好
print('-------------------------------------------')
print('C parameter: ', c_param)
print('-------------------------------------------')
print('')
recall_accs = []
for iteration, indices in fold.split(X_train_data):
lr = LogisticRegression(C=c_param, penalty='l1', solver='liblinear')
lr.fit(X_train_data.iloc[iteration, :], y_train_data.iloc[iteration, :].values.ravel())
y_pred_undersample = lr.predict(X_train_data.iloc[indices, :].values)
recall_acc = recall_score(y_train_data.iloc[indices, :].values, y_pred_undersample)
recall_accs.append(recall_acc)
print('recall score = ', recall_acc)
results_table.loc[j, 'Mean recall score'] = np.mean(recall_accs)
j += 1
print('')
print('Mean recall score ', np.mean(recall_accs))
print('')
results_table['Mean recall score']=results_table['Mean recall score'].astype('float64')#reduction operation 'argmax' not allowed for this dtype
best_c = results_table.loc[results_table['Mean recall score'].idxmax()]['C_parameter']
print('*'*50)
print('Best model to choose from cross validation is with C parameter = ', best_c)
print('*'*50)
return best_c
def plot_confusion_matrix(cm, classes,
title='Confusion matrix',
cmap=plt.cm.Blues):
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=0)
plt.yticks(tick_marks, classes)
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, cm[i, j],
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
#下采样数据值验证
best_c = printing_Kfold_scores(X_train_undersample, y_train_undersample)
lr = LogisticRegression(C=best_c, penalty='l1', solver='liblinear')
lr.fit(X_train_undersample, y_train_undersample.values.ravel())
y_pred_undersample = lr.predict(X_test_undersample.values)
# 计算混淆矩阵
cnf_matrix = confusion_matrix(y_test_undersample, y_pred_undersample)
np.set_printoptions(precision=2)
print("Recall metric in the testing dataset: ", cnf_matrix[1, 1] / (cnf_matrix[1, 0] + cnf_matrix[1, 1]))
# 绘制混淆矩阵
class_names = [0, 1]
plt.figure()
plot_confusion_matrix(cnf_matrix, classes=class_names, title='Confusion matrix')
plt.show()
# #原始数据验证
# best_c = printing_Kfold_scores(X_train, y_train)
# lr = LogisticRegression(C=best_c, penalty='l1', solver='liblinear')
# lr.fit(X_train, y_train.values.ravel())
# y_pred = lr.predict(X_test.values)
# # 计算混淆矩阵
# cnf_matrix = confusion_matrix(y_test, y_pred)
# np.set_printoptions(precision=2)
# print("Recall metric in the testing dataset: ", cnf_matrix[1, 1] / (cnf_matrix[1, 0] + cnf_matrix[1, 1]))
# # 绘制混淆矩阵
# class_names = [0, 1]
# plt.figure()
# plot_confusion_matrix(cnf_matrix, classes=class_names, title='Confusion matrix')
# plt.show()
# 预测
lr = LogisticRegression(C=best_c, penalty='l1', solver='liblinear')#用之前最好的参数来进行建模
lr.fit(X_train_undersample, y_train_undersample.values.ravel())
y_pred = lr.predict(X_test.values)#得到预测结果的概率值
cnf_matrix = confusion_matrix(y_test, y_pred)#混淆矩阵
np.set_printoptions(precision=2)
print("Recall metric in the testing dataset: ", cnf_matrix[1, 1] / (cnf_matrix[1, 0] + cnf_matrix[1, 1]))
# Plot non-normalized confusion matrix
class_names = [0, 1]
plt.figure()
plot_confusion_matrix(cnf_matrix
, classes=class_names
, title='Confusion matrix')
plt.show()
# ###多个阈值
# #指定不同的阈值
# thresholds = [0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9]
# thresholds=thresholds2=np.arange(0,1,0.2).tolist()
# print(thresholds)
# plt.figure(figsize = (10,10))
# j = 1
# # 用混淆矩阵来进行展示
# for i in thresholds:
# y_test_predictions_high_recall = y_pred_undersample_proba[:,1] > i
# plt.subplot(3,3,j)
# j += 1
# cnf_matrix = confusion_matrix(y_test_undersample,y_test_predictions_high_recall)
# np.set_printoptions(precision=2)
# print("给定阈值为:",i,"时测试集召回率: ", cnf_matrix[1,1]/(cnf_matrix[1,0]+cnf_matrix[1,1]))
# class_names = [0,1]
# plot_confusion_matrix(cnf_matrix
# , classes=class_names
# , title='Threshold >= %s'%i)
'''smote过采样方案'''
# import pandas as pd
# from imblearn.over_sampling import SMOTE
# from sklearn.metrics import confusion_matrix
# from sklearn.model_selection import train_test_split
# credit_cards = pd.read_csv('creditcard.csv')
# columns = credit_cards.columns
# #在特征中去除掉标签
# features_columns = columns.delete(len(columns)-1)
# features = credit_cards[features_columns]
# labels = credit_cards['Class']
# features_train, features_test, label_train, label_test = train_test_split(features,lables,test_size = 0.3,random_state =0)
# #基于SMOTE算法进行样本生成,这样正例和负例样本数量就是一致的了
# oversampler =SMOTE(random_state = 0)
# os_features, os_labels = oversampler.fit_sample(features_train, labels_train)
# #训练集样本数量
# len(os_labels[os_labels = 1])
# os_features = pd.DataFrame(os_features)
# os_labels = pd.DataFrame(os_labels)
# best_c = printing_Kfold_scores(os_features, os_labels)
# lr = LogisticRegression(C = best_c, penalty = 'l1', solver = 'liblinear')
# lr.fit(os_features, os_labels.values.ravel())
# y_pred = lr.predict(features_test.values)
# #计算混淆矩阵
# cnf_matrix = confusion_matrix(labels_test, y_pred)
# np.set_printoptions(precision = 2)
# print("召回率:", cnf_matrix[1,1] / (cnf_matrix[1,0] + cnf_matrix[1,1]))
# #绘制
# class_names = [0,1]
# plt.figure()
# plot_confusion_matrix(cnf_matrix,classes = class_names, title = 'Confusion matrix')
# plt.show()
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)