信用卡欺诈检测实例

#coding:utf-8
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

data = pd.read_csv("creditcard.csv")
#print(data.head())
#计算Class列中含有哪几类并且各有多少个样本
count_classes = pd.value_counts(data["Class"],sort=True).sort_index()
#此处.sort_index()可加可不加
count_classes.plot(kind="bar")
plt.xlabel("Class")
plt.ylabel("Frequency")
plt.title("Fraud class histogram")
plt.show()
#将Amount列的数据归一化
from sklearn.preprocessing import StandardScaler
#reshape(-1,1) 智能化矩阵转化方法,-1代表自己预测,1代表将原来的数据转换成1列,
#至于几行自己转换就可以
data['nomAmount'] = StandardScaler().fit_transform(data['Amount'].values.reshape(-1,1))
data = data.drop(['Time','Amount'],axis=1)
data.head()
# from sklearn.preprocessing import StandardScaler
# data['normAmount'] = StandardScaler().fit_transform(data['Amount'])
# data = data.drop(['Time','Amount'],axis=1)
#下采样
# cols = data.shape[1]
# X = data[:,0:cols-1]
# Y = data[:,cols-1:cols]
X = data.ix[:, data.columns != 'Class']
y = data.ix[:, data.columns == 'Class']
number_records_fraud = len(data[data.Class == 1])
#把Class==1的样本序号按排序的方式放到数组里
fraud_indices = np.array(data[data.Class == 1].index)
normal_indices = data[data.Class == 0].index
#在Class==0中选出Class==1的数量的样本,下采样。
random_normal_indices = np.random.choice(normal_indices, number_records_fraud, replace = False)
random_normal_indices = np.array(random_normal_indices)
#将fraud_indices和random_normal_indices的索引组合放到矩阵里
under_sample_indices = np.concatenate([fraud_indices,random_normal_indices])
#将under_sample_indices里的索引所对应的样本取出来
under_sample_data = data.iloc[under_sample_indices,:]

#print(under_sample_data)
#处理下采样后组成的数据
X_undersample = under_sample_data.ix[:, under_sample_data.columns != 'Class']
y_undersample = under_sample_data.ix[:, under_sample_data.columns == 'Class']

# Showing ratio
print("Percentage of normal transactions: ", len(under_sample_data[under_sample_data.Class == 0])/len(under_sample_data))
print("Percentage of fraud transactions: ", 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))

#交叉验证
# 1、原始数据集的拆分
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)
print("Number transactions train dataset: ", len(X_train))
print("Number transactions test dataset: ", len(X_test))
print("Total number of transactions: ", len(X_train)+len(X_test))

# 2、下采样数据集的拆分
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("Number transactions train dataset: ", len(X_train_undersample))
print("Number transactions test dataset: ", len(X_test_undersample))
print("Total number of transactions: ", len(X_train_undersample)+len(X_test_undersample))
from sklearn.linear_model import LogisticRegression
from sklearn.cross_validation import KFold, cross_val_score
# cross_val_score得到一个交叉验证的评估结果
from sklearn.metrics import confusion_matrix,recall_score,classification_report
# fold = KFold(len(y_train_undersample),5,shuffle=False)
# print("*****************************************************************")
# print(fold)

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]#惩罚力度 * L2
    #此处的2不知道什么意思5行2列
    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 = []
          #将fold中交叉验证中的四个训练集和一个测试集打印出来
        for iteration, indices in enumerate(fold, start=1):
            #indices指的是交叉验证中的那几份训练值和一份测试值
            # Call the logistic regression model with a certain C parameter
            #用一个C参数调用logistic回归模型
            lr = LogisticRegression(C=c_param, penalty='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())
            #indices[0]代表的是交叉验证中的训练集数据
            # Predict values using the test indices in the training data
            #在训练数据中使用测试指标预测值indices[1]
            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']
    best_c = results_table.iloc[results_table['Mean recall score'].astype('float64').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()#增加颜色类标的代码是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()命令可以在任意的位置添加文字
        plt.text(j, i, cm[i, j],
                 horizontalalignment="center",
                 color="white" if cm[i, j] > thresh else "black")
    #tight_layout会自动调整子图参数,使之填充整个图像区域,不产生叠加现象
    plt.tight_layout()
    plt.ylabel('True label')
    plt.xlabel('Predicted label')
    plt.show()
"""
笛卡尔积:itertools.product(*iterables[, repeat])
import itertools
for i in itertools.product('ABCD', repeat = 2):
    print (''.join(i),end=' ')
输出结果:
AA AB AC AD BA BB BC BD CA CB CC CD DA DB DC DD
print (”.join(i))这个语句可以让结果直接排列到一起
end=’ ‘可以让默认的输出后换行变为一个空格
"""
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)#作用:确定浮点数字、数组、和numpy对象的显示形式。
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)
print(y_pred)
# Compute confusion matrix
cnf_matrix = confusion_matrix(y_test,y_pred)
print("***************姜海洋*********************")
print(cnf_matrix)
print(len(y_test))
print(len(X_test))
print("***************姜海洋*********************")
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)
#predict_proba此函数预测出来的结果是概率值
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)
    plt.tight_layout()
    plt.show()

猜你喜欢

转载自blog.csdn.net/ITpfzl/article/details/82690648
今日推荐