项目简介
使用信用卡是普遍的当今社会。信用卡诈骗案检测是一项艰巨的任务,信用卡诈骗罪的侦查无论在学术或商业都极为重要。该项目利用已有信用卡用户的数据进行训练,建立一个检测模型,以此来检测信用卡用户是否为异常用户。
导入数据
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
data = pd.read_csv('F:\\card_data\\creditcard.csv')
data.head()
在数据集中,大部分特征已经是经过数据标准化的处理了,但是Amount特征与其它特征相比数字差异比较大,需要进行标准化处理,同时Time对于结果的预测来说是多余的,需要处理掉
首先进行数据预处理
from sklearn.preprocessing import StandardScaler
data['normAmount'] = StandardScaler().fit_transform(data['Amount'].values.reshape(-1, 1))
data = data.drop(['Time','Amount'],axis=1)
data.head()
count_class = pd.value_counts(data['Class'],sort=True).sort_index()
在对训练数据的结果统计中,不难发现正常与异常的账户相差过大,如果直接对训练数据进行训练预测结果将会不理想,
所以需要对样本数据进行处理,一般来说有两种方法:1.下采样处理,2.过量处理
对数据进行下采样处理:
X = data.iloc[:,data.columns != 'Class']
y = data.iloc[:,data.columns == 'Class']
#Number of data points in the minority class
number_record_fraud = len(data[data.Class == 1])
fraud_ridices = np.array(data[data.Class == 1].index)
#Picking the indices of the normal classes
normal_indices = data[data.Class == 0].index
#out of indices we picked, randmly select 'X' number (num_records_fraud)
random_normal_indices = np.random.choice(normal_indices, number_record_fraud, replace = False)
random_normal_indices = np.array(random_normal_indices)
#Appending the two indices
under_sample_indices = np.concatenate([fraud_ridices, random_normal_indices])
#Under sample dataset
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']
#Showing ratio
print('Percentage of normal transactions:', len(under_sample_data[under_sample_data.Class == 0]) / len(under_sample_data))
print(