案例背景:
有些人利用信用卡进行诈骗活动,如何根据用户的行为,来判断该用户的信用卡账单是否属于欺诈呢?想获取数据集请点此处。在这个数据集中,由于原始的用户数据具有一定的隐私,因此,每一列(即特征)的名称并没有给出,而是使用V1,V2等代替。目标是进行异常值的检测。数据集中有一列值class,要么为0,表示正常,要么为1,表示异常。
案例实战:
第一步:首先导入数据分析所需用的第三方库numpy、pandas,以及可视化库matplotlib
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# 将matplotlib的图表直接嵌入到Notebook之中,inline表示将图表嵌入到Notebook中
%matplotlib inline
第二步:读取数据,以及基本信息
data = pd.read_csv("creditcard.csv")
data.info()
data.head()
运行结果:
第三步: 根据基本信息分析数据
最后一列"Class"只有0 或者是1,且是 0 的样本很多,1 的样本很少,符合正常情况:少数人利用信用卡欺诈
可视化展现一下,这里提一下,pandas也是可以作图的噢。
count_classes = pd.value_counts(data['Class'], sort = True).sort_index()
print(count_classes)
# pandas画条形图
count_classes.plot(kind = 'bar')
plt.title("Fraud class histogram")
plt.xlabel("Class")
plt.ylabel("Frequency")
运行截图:
由于数据极不均衡,如果直接拿来做训练,在机器学习中,它会默认为数据量大的那一类别占的比重大,会很大影响最终的结果,考虑进行数据的均衡化处理。主要有两种思路:下采样和过采样。
下采样:在数据量比较多的那部分数据中,选取和其余数据数量差不多的部分。 即:“同样少”
过采样:对数据量比较少的那部分数据采取一定的策略,进行生成数据。 即:“同样多”
在进行采样处理之前,观察数据,发现除了Amount之外,其他列的数据都在-1~1,而Amount的数据值特别大。因此在采样之前,先进行标准化处理:
#标准化
from sklearn.preprocessing import StandardScaler
# Series数据类型没有reshape函数
# 将values方法把Series对象转化成numpy的ndarray,再用ndarray的reshape方法
# DataFrame像一张表,Series是指表里的某一行数据或某一列数据
data['normAmount'] = StandardScaler().fit_transform(data['Amount'].values.reshape(-1, 1))
data.head()
注意:使用reshape方法之前,要先使用values方法,否则会提示:Series数据类型没有reshape函数。使用values方法把Series对象转化成numpy的ndarray,再用ndarray的reshape方法 。reshape(-1,1)转换成1列。
开始进行采样:
# 下采样
# X是非标签值,Y是标签值
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)
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))
运行截图:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)