scikit-learn 逻辑回归实现信用卡欺诈检测

读书笔记



import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

data = pd.read_csv('creditcard.csv')

#data.head(10)

print (data.shape)

count_class = pd.value_counts(data['Class'],sort = True).sort_index()

print (count_class)

from sklearn.preprocessing import StandardScaler    #导入数据预处理模块
data['normAmount'] = StandardScaler().fit_transform(data['Amount'].values.reshape(-1,1))   # -1表示系统自动计算得到的行,1表示1列
data = data.drop(['Time','Amount'],axis = 1)  # 删除两列,axis =1表示按照列删除,即删除特征。而axis=0是按行删除,是删除样本
#print (data.head(3))
#print (data['normAmount'])


X = data.ix[:,data.columns != 'Class'] #ix 是通过行号和行标签进行取值
y = data.ix[:,data.columns == 'Class']    # y 为标签,即类别
number_records_fraud = len(data[data.Class==1])  #统计异常值的个数
#print (number_records_fraud)  # 492 个
#print (data[data.Class == 1].index)
fraud_indices = np.array(data[data.Class == 1].index)   #统计欺诈样本的下标,并变成矩阵的格式

#print (fraud_indices)

normal_indices = data[data.Class == 0].index   # 记录正常值的索引
random_normal_indices =np.random.choice(normal_indices,number_records_fraud,replace = False) # 从正常值的索引中,选择和异常值相等个数的样本
random_normal_indices = np.array(random_normal_indices)
#print (len(random_normal_indices))  #492 个

under_sample_indices = np.concatenate([fraud_indices,random_normal_indices])  # 将正负样本的索引进行组合
#print (under_sample_indices)   # 984个
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 (len(under_sample_data[under_sample_data.Class==1])/len(under_sample_data)) # 正负样本的比例都是 0.5
from sklearn.cross_validation import train_test_split   # 导入交叉验证模块的数据切分

X_train,X_test,y_train,y_test = train_test_split(X,y,test_size = 0.3,random_state = 0) # 返回 4 个值

#print (len(X_train)+len(X_test))
#print (len(X))

X_undersample_train,X_undersample_test,y_undersample_train,y_undersample_train = train_test_split(X_undersample,y_undersample,test_size = 0.3,random_state = 0)

print (len(X_undersample_train)+len(X_undersample_test))
print (len(X_undersample))

#Recall = TP/(TP+FN)

from sklearn.linear_model import LogisticRegression  #
from sklearn.cross_validation import KFold, cross_val_score  #
from sklearn.metrics import confusion_matrix,recall_score,classification_report #

def printing_Kfold_scores(x_train_data,y_train_data):

    fold = KFold(len(y_train_data),5,shuffle=False)
    c_param_range = [0.01,0.1,1,10,100] # 惩罚力度参数
    results_table = pd.DataFrame(index = range(len(c_param_range),2),columns = ['C_parameter','Mean recall score'])
    results_table['C_parameter'] = c_param_range

    # k折交叉验证有两个;列表: train_indices = indices[0], test_indices = indices[1]
    j = 0
    for c_param in c_param_range:  # 
        print('------------------------------------------')
        print('C parameter:',c_param)
        print('-------------------------------------------')
        print('')
        recall_accs = []

        for iteration, indices in enumerate(fold,start=1):   #循环进行交叉验证
            # Call the logistic regression model with a certain C parameter

            lr = LogisticRegression(C = c_param, penalty = 'l1')  #实例化逻辑回归模型,L1 正则化
            # Use the training data to fit the model. In this case, we use the portion of the fold to train the model
            # with indices[0]. We then predict on the portion assigned as the 'test cross validation' with indices[1]
            lr.fit(x_train_data.iloc[indices[0],:],y_train_data.iloc[indices[0],:].values.ravel())#  套路:使训练模型fit模型

            # Predict values using the test indices in the training data
            y_pred_undersample = lr.predict(x_train_data.iloc[indices[1],:].values)# 利用交叉验证进行预测

            # Calculate the recall score and append it to a list for recall scores representing the current c_parameter
            recall_acc = recall_score(y_train_data.iloc[indices[1],:].values,y_pred_undersample) #评估预测结果
            recall_accs.append(recall_acc)
            print('Iteration ', iteration,': recall score = ', recall_acc)

 

        # The mean value of those recall scores is the metric we want to save and get hold of.

        results_table.ix[j,'Mean recall score'] = np.mean(recall_accs)
        j += 1
        print('')
        print('Mean recall score ', np.mean(recall_accs))
        print('')
    best_c = results_table.loc[results_table['Mean recall score'].idxmax()]['C_parameter']

    # Finally, we can check which C parameter is the best amongst the chosen.

    print('*********************************************************************************')
    print('Best model to choose from cross validation is with C parameter = ', best_c)
    print('*********************************************************************************')
    return best_c



best_c = printing_Kfold_scores(X_train_undersample,y_train_undersample)

def plot_confusion_matrix(cm, classes, title='Confusion matrix',  cmap=plt.cm.Blues):
    """
    This function prints and plots the confusion matrix.
    """
    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')

import itertools
lr = LogisticRegression(C = best_c, penalty = 'l1')
lr.fit(X_train_undersample,y_train_undersample.values.ravel())
y_pred_undersample = lr.predict(X_test_undersample.values)


# Compute confusion matrix
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]))

# Plot non-normalized confusion matrix
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')
lr.fit(X_train_undersample,y_train_undersample.values.ravel())
y_pred = lr.predict(X_test.values)

 

# Compute confusion matrix
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()
#Recall metric in the testing dataset: 0.918367346939

best_c = printing_Kfold_scores(X_train,y_train)

lr = LogisticRegression(C = best_c, penalty = 'l1')
lr.fit(X_train,y_train.values.ravel())
y_pred_undersample = lr.predict(X_test.values)

# Compute confusion matrix
cnf_matrix = confusion_matrix(y_test,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]))

# Plot non-normalized confusion matrix 
class_names = [0,1]

plt.figure()

plot_confusion_matrix(cnf_matrix, classes=class_names, title='Confusion matrix')

plt.show()

lr = LogisticRegression(C = 0.01, penalty = 'l1')
lr.fit(X_train_undersample,y_train_undersample.values.ravel())
y_pred_undersample_proba = lr.predict_proba(X_test_undersample.values)#原来时预测类别值,而此处是预测概率。方便后续比较

thresholds = [0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9]
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
    # Compute confusion matrix
    cnf_matrix = confusion_matrix(y_test_undersample,y_test_predictions_high_recall)
    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]
    plot_confusion_matrix(cnf_matrix, classes=class_names, title='Threshold >= %s'%i) 

#换种思路,采用上采样,进行数据增广。


import pandas as pd
from imblearn.over_sampling import SMOTE #上采样库,导入SMOTE算法
from sklearn.ensemble import RandomForestClassifier
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
# The labels are in the last column ('Class'). Simply remove it to obtain features columns
features_columns=columns.delete(len(columns)-1)

features=credit_cards[features_columns]
labels=credit_cards['Class']
features_train, features_test, labels_train, labels_test = train_test_split(features,  labels,  test_size=0.2,  random_state=0)
oversampler=SMOTE(random_state=0)  #实例化参数,只对训练集增广,测试集不动
os_features,os_labels=oversampler.fit_sample(features_train,labels_train)# 使 0 和 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')
lr.fit(os_features,os_labels.values.ravel())
y_pred = lr.predict(features_test.values)

# Compute confusion matrix
cnf_matrix = confusion_matrix(labels_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()
#Recall metric in the testing dataset: 0.90099009901

扩展阅读

https://blog.csdn.net/dengheCSDN/article/details/79079364

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
信用卡欺诈检测是一种非常重要的应用场景,可以帮助银行和客户识别和预防欺诈行为。在Python中,我们可以使用各种机器学习和深度学习算法来构建欺诈检测模型。 首先,我们需要了解数据集。信用卡欺诈检测数据集通常包含大量的交易数据,其中只有少数是欺诈交易。我们需要使用机器学习算法来识别这些欺诈交易。 接下来,我们可以使用Python中的各种机器学习库来构建模型,例如Scikit-learn,TensorFlow和Keras等。我们可以使用分类算法(例如逻辑回归,决策树和随机森林等)来构建模型,也可以使用深度学习算法(例如神经网络和卷积神经网络等)来构建模型。 在实现模型之前,我们还需要进行数据预处理和特征工程。我们需要对数据进行清洗,处理缺失值和异常值,并进行特征选择和降维等操作,以提高模型的性能。 最后,我们可以使用交叉验证和网格搜索等技术来优化模型,并评估模型的性能。我们可以使用各种性能指标(例如准确率,召回率和F1分数等)来评估模型的性能,并选择最佳模型来预测新的欺诈交易。 总之,信用卡欺诈检测是一项非常重要的任务,Python提供了各种机器学习和深度学习算法来实现。通过数据预处理,特征工程和模型优化,我们可以构建高效的欺诈检测模型,帮助银行和客户识别和预防欺诈行为。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值