信用卡欺诈案例数据分析——利用逻辑回归进行分类

1.数据读取import pandas as pdimport matplotlib.pyplot as pltimport numpy as np%matplotlib inlinedata = pd.read_csv("creditcard.csv")data.head()展示数据基本信息,如缺失值,字段类型等等data.info()2.数据预处理#统计不同标签对应...
摘要由CSDN通过智能技术生成

1.数据读取

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

data = pd.read_csv("creditcard.csv")
data.head()

展示数据基本信息,如缺失值,字段类型等等

data.info()

在这里插入图片描述

2.数据预处理

#统计不同标签对应的样本数
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")

在这里插入图片描述通过条形图显示,正负样本(class分别为1和0的样本)比例失调,通常解决这一问题的方法有:

  • 调整正负样本的权重
  • 上采样
  • 下采样
#对样本的Amount列进行归一化处理
from sklearn import preprocessing
data['normAmount'] = preprocessing.scale(data['Amount'])
#删除无关列
data = data.drop(['Time', 'Amount'], axis=1)
data.head()

生成下采样样本数据集

#筛选出训练数据与相应的分类标签
X = data.loc[:, data.columns != 'Class']
y = data.loc[:, 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.loc[:, under_sample_data.columns != 'Class']
y_undersample = under_sample_data.loc[:, under_sample_data.columns == 'Class']

# 打印出正负样本比例
print("Percentage of normal transactions: ", len(under_sample_data[under_sample_data.Class == 0])/len(
  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值