如下图是该数据集正负样本的分布情况,异常情况相比正常情况极少。
面对非平衡数据集时,有两种解决方案:过采样和下采样。
下采样: 让数量多的样本减少到和数量少的样本数量一样多。
过采样:生成数量少的样本,以平衡数据。
下采样
下采样代码:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from IPython import get_ipython
get_ipython().run_line_magic('matplotlib', 'inline')
data=pd.read_csv("creditcard.csv")
data.head()
#可以看到正负样本分布极不平衡,异常样本很少
count_classes=pd.value_counts(data["Class"],sort=True).sort_index()
count_classes.plot(kind='bar')
plt.title("Fraud class histogram")
plt.xlabel("Class")
plt.ylabel("Frequency")
#sklearn库提供机器学习操作和预处理操作
#fit_transform将Amount特征变换为一列数据
from sklearn.preprocessing import StandardScaler
data["normAmount"]=StandardScaler().fit_transform(data["Amount"].reshape(-1,1))
#删除Time和Amount两列
data=data.drop(["Time","Amount"],axis=1)
#下采样
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模块,随机选择和异常事件一样多的正常数据
random_normal_indices = np.random.choice(normal_indices, number_records_fraud, replace = False)
random_normal_indices = np.array(random_normal_indices)
#合并异常和正常的数据集
under_sample_indices = np.concatenate([fraud_indices,random_normal_indices])
under_sample_data = data.iloc[under_sample_indices,:]
X_undersample = under_sample_data.ix[:, under_sample_data.columns != 'Class']
y_undersample = under_sample_data.ix[:, under_sample_data.columns == 'Class']
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))
下采样导致数据量变少。虽然召回率能达到要求,但是将正常类错分为异常类的几率很高。如下图混淆矩阵所示,误分的有9895个,这就是下采样的劣势。
交叉验证:
切分数据为两部分。80%训练,20%测试。平均切分训练集为三份1、2、3,分别用1、2来训练,3来验证;用1、3训练,2来验证;用2、3训练、1来验证。利用交叉验证找到合适的模型参数。
本案例采用逻辑斯特回归模型,在skleaarn库中有。