行业案例 | 数据分析在银行业应用之欺诈检测

人工智能47

行业案例 | 数据分析在银行业应用之欺诈检测

CDA数据分析师 出品

作者:Elena Kosourova

编译:Mika

在本文中,我们将探索一个非常常见的用例,即欺诈检测,以了解数据分析如何在银行中使用。

[En]

In this article, we will explore a very common use case, fraud detection, to understand how data analysis is used in banking.

背景介绍
银行业是历史上收集了大量结构化数据的领域之一,也是最早应用数据科技的领域之一。

[En]

Banking is one of the fields in which a large amount of structured data has been collected in history, and it is also one of the earliest fields to apply data science and technology.

那么,数据分析是如何应用于银行业的?

如今,数据已经成为银行业最有价值的资产,不仅可以帮助银行吸引更多客户,提高现有客户忠诚度,做出更有效的数据驱动决策,还可以提升业务能力和运营效率。改进现有服务、产品和推出新服务,增强安全性,并通过所有这些行动产生更多收入,等等。

[En]

Today, data has become the most valuable asset of the banking industry, which can not only help banks attract more customers, increase existing customer loyalty, and make more effective data-driven decisions, but also enhance business capabilities and operational efficiency. improve existing services, products and launch new services, enhance security, and generate more revenue through all these actions, and so on.

因此,现在对数据相关工作的大部分需求来自银行业也就不足为奇了。

[En]

So it is not surprising that most of the demand for data-related jobs now comes from banking.

数据分析使银行业能够成功地执行众多任务,包括:

投资风险分析
客户终身价值预测
客户细分
客户流失率预测
个性化营销
客户情绪分析
虚拟助理和聊天机器人
下面,我们将仔细看看银行业中最常见的数据分析用例之一。

数据分析在银行业应用案例:欺诈检测

欺诈不仅在银行业是一个具有挑战性的问题,而且在许多其他领域也是如此,如政府、保险、公共部门、销售和医疗保健。

[En]

Fraud is a challenging issue not only in banking, but also in many other areas, such as government, insurance, the public sector, sales and health care.

任何处理大量在线交易的公司都面临欺诈风险。金融犯罪的形式多种多样,包括诈骗信用卡交易、伪造银行支票、逃税、网络攻击、客户账户盗窃、合成身份、诈骗等。

[En]

Any company that handles a large number of online transactions is at risk of fraud. Financial crimes take a variety of forms, including fraudulent credit card transactions, forged bank checks, tax evasion, cyber attacks, customer account theft, synthetic identity, fraud and so on.

欺诈检测是识别和预防欺诈活动和经济损失的一项积极措施。

[En]

Fraud detection is an active measure to identify and prevent fraudulent activities and financial losses.

其主要分析技术可分为两组:

统计学:统计参数计算、回归、概率分布、数据匹配
人工智能(AI):数据挖掘、机器学习、深度学习
机器学习是欺诈检测的重要支柱。其工具包提供了两种方法:

监督方法:K-近邻、逻辑回归、支持向量机、决策树、随机森林、时间序列分析、神经网络等。
非监督方法:聚类分析、链接分析、自组织映射、主成分分析、异常识别等。

[En]

Unsupervised methods: cluster analysis, link analysis, self-organizing map, principal component analysis, anomaly identification, etc.

目前,还没有一种通用的机器学习算法用于欺诈检测。相比之下,对于现实世界的数据科学用例,通常会测试几种技术或它们的组合,计算模型的预测精度,并选择最佳方法。

[En]

At present, there is no general machine learning algorithm for fraud detection. In contrast, for real-world data science use cases, several technologies or their combinations are usually tested, the prediction accuracy of the model is calculated, and the best method is selected.

欺诈检测系统的主要挑战是快速适应不断变化的欺诈模式和欺诈者的策略,并及时识别日益复杂的新方案。欺诈案件总是少数,而且在真实的交易中隐藏得很好。

[En]

The main challenge of fraud detection systems is to quickly adapt to changing fraud patterns and fraudsters' strategies, and to identify new and increasingly complex schemes in a timely manner. Fraud cases are always in the minority and are well hidden in real transactions.

让我们来探讨一下使用Python进行信用卡欺诈检测。

我们将用到creditcard_data数据集。

Credit Card Fraud Detection | Kaggle数据集:

https://www.kaggle.com/mlg-ulb/creditcardfraud

该数据集是Kaggle信用卡欺诈检测数据集的一个修改样本。原始数据代表了2013年9月两天内欧洲持卡人拥有信用卡的交易情况。

让我们读入数据并快速浏览一下。

import pandas as pd
creditcard_data = pd.read_csv('creditcard_data.csv', index_col=0)
print(creditcard_data.info())
print('\n')
pd.options.display.max_columns = len(creditcard_data)
print(creditcard_data.head(3))

; Column Non-Null Count Dtype

0 V1 5050 non-null float64
1 V2 5050 non-null float64
2 V3 5050 non-null float64
3 V4 5050 non-null float64
4 V5 5050 non-null float64
5 V6 5050 non-null float64
6 V7 5050 non-null float64
7 V8 5050 non-null float64
8 V9 5050 non-null float64
9 V10 5050 non-null float64
10 V11 5050 non-null float64
11 V12 5050 non-null float64
12 V13 5050 non-null float64
13 V14 5050 non-null float64
14 V15 5050 non-null float64
15 V16 5050 non-null float64
16 V17 5050 non-null float64
17 V18 5050 non-null float64
18 V19 5050 non-null float64
19 V20 5050 non-null float64
20 V21 5050 non-null float64
21 V22 5050 non-null float64
22 V23 5050 non-null float64
23 V24 5050 non-null float64
24 V25 5050 non-null float64
25 V26 5050 non-null float64
26 V27 5050 non-null float64
27 V28 5050 non-null float64
28 Amount 5050 non-null float64
29 Class 5050 non-null int64
dtypes: float64(29), int64(1)
memory usage: 1.2 MB
V1 V2 V3 V4 V5 V6 V7
0 1.725265 -1.337256 -1.012687 -0.361656 -1.431611 -1.098681 -0.842274
1 0.683254 -1.681875 0.533349 -0.326064 -1.455603 0.101832 -0.520590
2 1.067973 -0.656667 1.029738 0.253899 -1.172715 0.073232 -0.745771
V8 V9 V10 V11 V12 V13 V14
0 -0.026594 -0.032409 0.215113 1.618952 -0.654046 -1.442665 -1.546538
1 0.114036 -0.601760 0.444011 1.521570 0.499202 -0.127849 -0.237253
2 0.249803 1.383057 -0.483771 -0.782780 0.005242 -1.273288 -0.269260
V15 V16 V17 V18 V19 V20 V21
0 -0.230008 1.785539 1.419793 0.071666 0.233031 0.275911 0.414524
1 -0.752351 0.667190 0.724785 -1.736615 0.702088 0.638186 0.116898
2 0.091287 -0.347973 0.495328 -0.925949 0.099138 -0.083859 -0.189315
V22 V23 V24 V25 V26 V27 V28
0 0.793434 0.028887 0.419421 -0.367529 -0.155634 -0.015768 0.010790
1 -0.304605 -0.125547 0.244848 0.069163 -0.460712 -0.017068 0.063542
2 -0.426743 0.079539 0.129692 0.002778 0.970498 -0.035056 0.017313
Amount Class
0 189.00 0
1 315.17 0
2 59.98 0

数据集包含以下变量:

数值编码的变量V1到V28是从PCA变换中获得的主分量。由于保密问题,未提供有关原始功能的背景信息。
Amount变量表示交易金额。
Class变量显示交易是否为欺诈(1)或非欺诈(0)。
幸运的是,就其本质而言,欺诈在任何交易清单中都是罕见的。然而,当数据集中包含的不同类别或多或少存在时,机器学习算法通常工作得最好。否则,将没有数据可供借鉴。这个问题被称为范畴不等性。

[En]

Fortunately, by its nature, fraud is rare in any transaction list. However, machine learning algorithms usually work best when different categories contained in the dataset exist more or less. Otherwise, there will be no data to learn from. This problem is called category inequality.

让我们计算欺诈交易占数据集中交易总数的百分比:

round(creditcard_data['Class'].value_counts()*100/len(creditcard_data)).convert_dtypes()

0 99
1 1
Name: Class, dtype: Int64

并创建一个图表,将欺诈与非欺诈的数据点可视化。

import matplotlib.pyplot as plt
import numpy as np
def prep_data(df):
X = df.iloc[:, 1:28]
X = np.array(X).astype(float)
y = df.iloc[:, 29]
y = np.array(y).astype(float)
return X, y
def plot_data(X, y):
plt.scatter(X[y0, 0], X[y0, 1], label='Class #0', alpha=0.5, linewidth=0.15)
plt.scatter(X[y1, 0], X[y1, 1], label='Class #1', alpha=0.5, linewidth=0.15, c='r')
plt.legend()
return plt.show()
X, y = prep_data(creditcard_data)
plot_data(X, y)

行业案例 | 数据分析在银行业应用之欺诈检测

我们现在可以确认,欺诈性交易的比例非常低,我们有一个类别不平衡问题的案例。为了解决这个问题,我们可以使用合成少数人超抽样技术(SMOTE)来重新平衡我们的数据。与随机超额取样不同,SMOTE稍微复杂一些,因为它不只是创建观察值的精确副本。相反,它使用欺诈案件的最近邻居的特征来创建新的、合成的样本,这些样本与少数人类别中的现有观察值相当相似。让我们把SMOTE应用于我们的信用卡数据。

from imblearn.over_sampling import SMOTE
method = SMOTE()
X_resampled, y_resampled = method.fit_resample(X, y)
plot_data(X_resampled, y_resampled)

行业案例 | 数据分析在银行业应用之欺诈检测

正如我们所看到的,使用SMOTE突然给我们提供了更多的少数类别的观察结果。为了更好地看到这种方法的结果,我们将把它们与原始数据进行比较。

def compare_plot(X, y, X_resampled, y_resampled, method):
f, (ax1, ax2) = plt.subplots(1, 2)
c0 = ax1.scatter(X[y0, 0], X[y0, 1], label='Class #0',alpha=0.5)
c1 = ax1.scatter(X[y1, 0], X[y1, 1], label='Class #1',alpha=0.5, c='r')
ax1.set_title('Original set')
ax2.scatter(X_resampled[y_resampled0, 0], X_resampled[y_resampled0, 1], label='Class #0', alpha=.5)
ax2.scatter(X_resampled[y_resampled1, 0], X_resampled[y_resampled1, 1], label='Class #1', alpha=.5,c='r')
ax2.set_title(method)
plt.figlegend((c0, c1), ('Class #0', 'Class #1'), loc='lower center', ncol=2, labelspacing=0.)
plt.tight_layout(pad=3)
return plt.show()
print(f'Original set:\n'
f'{pd.value_counts(pd.Series(y))}\n\n'
f'SMOTE:\n'
f'{pd.value_counts(pd.Series(y_resampled))}\n')
compare_plot(X, y, X_resampled, y_resampled, method='SMOTE')

Original set:
0.0 5000
1.0 50
dtype: int64
SMOTE:
0.0 5000
1.0 5000
dtype: int64

行业案例 | 数据分析在银行业应用之欺诈检测

因此,SMOTE方法已经完全平衡了我们的数据,少数群体现在与多数群体的规模相等。

我们很快会回到SMOTE方法的实际应用,但现在,让我们回到原始数据,并尝试检测欺诈案件。按照这类"老派"的方式,我们必须制定一些规则来抓捕欺诈行为。

例如,此类规则可能涉及不寻常的交易地点或可疑的频繁交易。我们的想法是基于常见的统计数据定义阈值,通常基于观察的平均值,并在我们的功能中使用这些阈值来检测欺诈。

[En]

For example, such rules may involve unusual trading locations or suspicious frequent transactions. The idea is to define thresholds based on common statistics, usually based on the average of observations, and use these thresholds in our functionality to detect fraud.

print(creditcard_data.groupby('Class').mean().round(3)[['V1', 'V3']])

V1 V3
Class
0 0.035 0.037
1 -4.985 -7.294

在我们的特殊情况下,让我们应用以下条件:V1

Original: https://blog.csdn.net/yoggieCDA/article/details/123788672
Author: CDA·数据分析师
Title: 行业案例 | 数据分析在银行业应用之欺诈检测



相关阅读

Title: TensorFlow实现自注意力机制(Self-attention)

TensorFlow实现自注意力机制(Self-attention)

*
- 自注意力机制(Self-attention)
-
+ 计算机视觉中的自注意力
- Tensorflow实现自注意力模块

自注意力机制(Self-attention)

自注意力机制 (Self-attention) 随着自然语言处理 (Natural Language Processing, NLP) 模型(称为"Transformer")的引入而变得流行。在诸如语言翻译之类的NLP应用程序中,模型通常需要逐字阅读句子以理解它们,然后再产生输出。Transformer问世之前使用的神经网络是递归神经网络 (Recurrent Neural Network, RNN) 或者其变体,例如长短期记忆网络 (Long Short-Term Memory, LSTM)。 RNN 具有其内部状态,能够更好的处理序列信息,例如句子中前面的单词输入和后面的单词输入是有关系的。但是 RNN 也具有其缺陷,例如当单词数量增加时,那么第一个单词的梯度就可能消失。也就是说,随着RNN读取更多单词,句子开头的单词逐渐变得不那么重要。
Transformer 的处理方式有所不同。它会一次读取所有单词,并权衡每个单词的重要性。因此,更多的注意力集中在更重要的单词上,因此也称为注意力。
而自注意力机制是注意力机制的变体,其减少了对外部信息的依赖,更擅长捕捉数据或特征的内部相关性。自注意力是最新的NLP模型 (例如BERT和GPT-3) 的基石。

计算机视觉中的自注意力

首先简单回顾下卷积神经网络 (Convolutional Neural Networks, CNN) 的要点:CNN 主要由卷积层组成。对于卷积核大小为 3×3 的卷积层,它仅查看输入激活中的 3×3 = 9 个特征(也可以将此区域称为卷积核的感受野)以计算每个输出特征,它并不会查看超出此范围的像素。为了捕获超出此范围的像素,我们可以将核大小略微增加到 5×5 或 7×7,但与特征图大小相比感受野仍然很小。
我们必须增加网络的深度,以使卷积核的感受野足够大以捕获我们想要的内容。与RNN一样,输入特征的相对重要性随着我们在网络层中的移动而下降。因此,我们可以利用自注意力来观察特征图中的每个像素,并注意力集中在更加重要的像素上。
现在,我们将研究自注意力机制的工作原理。自注意力的第一步是将每个输入特征投影到三个向量中,这些向量称为键 (key),查询 (query) 和值 (value),虽然这些术语在计算机视觉中较少出现,但是首先介绍有关这些术语的知识,以便可以更好地理解自注意力,Transformer或NLP有关的文献:

  1. 值 (value) 表示输入特征。我们不希望自注意力模块查看每个像素,因为这在计算上过于昂贵且不必要。相反,我们对输入激活的局部区域更感兴趣。因此,值在激活图尺寸(例如,它可以被下采样以具有较小的高度和宽度)和通道的数目方面都减小了来自输入特征的维数。 对于卷积层激活,通过使用1x1卷积来减少通道数,并通过最大池化或平均池化来减小空间大小。
  2. 键和查询 (Keys and queries) 用于计算自注意图中特征的重要性。为了计算位置x x x 处的输出特征,我们在位置x x x 处进行查询,并将其与所有位置处的键进行比较。
    为了进一步说明这一点,假设我们有一幅肖像,当网络处理该肖像的一只眼睛时,它首先进行具有语义意义的查询,并使用该肖像的其他区域中的关键字来检查它。如果其他区域中的一个关键是眼睛,那么网络知道它找到了另一只眼睛,这是网络应该关注的区域,以便网络可以进一步处理它。

    [En]

    To further illustrate this point, suppose we have a portrait that, when the network processes one eye of the portrait, it first makes a query that has the semantic meaning of "eye" and checks it using keys in other areas of the portrait. If one of the keys in other areas is the eye, then the network knows that it has found the other eye, which is the area that the network should pay attention to so that the network can process it further.

    更一般的,使用数学方程表达:对于特征0 0 0,我们计算向量q 0 × k 0 , q 0 × k 1 , q 0 × k 2 , q 0 × k N − 1 q_0×k_0, q_0×k_1, q_0×k_2, q_0×k_{N-1}q 0 ​×k 0 ​,q 0 ​×k 1 ​,q 0 ​×k 2 ​,q 0 ​×k N −1 ​。然后使用s o f t m a x softmax s o f t m a x 将向量归一化,因此它们的总和为 $1.0,这就是是我们要求的注意力得分。将注意力得分用作权重以执行值的逐元素乘法,以获取注意力输出。

下图说明了如何从查询中生成注意力图:

行业案例 | 数据分析在银行业应用之欺诈检测
上图红,最左边一列的图是带有点标记的查询 (queries) 的图像。接下来的五个图像显示了通过查询获得的注意力图。顶部的第一个注意力图查询兔子的一只眼睛;注意图的两只眼睛周围有更多白色区域(指示重要区域),其他区域接近全黑(重要性较低)。

有多种实现自注意力的方法。下图显示了 SAGAN 中的所使用的注意力模块,其中 θ θθ,φ φφ 和 g g g 对应于键,查询和值:

行业案例 | 数据分析在银行业应用之欺诈检测
深度学习中的大多数计算都是为了提高速度性能而矢量化的,而对于自注意力也没有什么不同。如果为简单起见忽略 batch 维度,则 1×1 卷积后的激活将具有 (H, W, C) 的形状。第一步是将其重塑为形状为 (H×W, C) 的2D矩阵,并使用 θ θθ 与 φ φφ 的矩阵相乘来计算注意力图。在SAGAN中使用的自注意力模块中,还有另一个1×1卷积,用于将通道数恢复到与输入通道数相同的数量,然后使用可学习的参数进行缩放操作。

; Tensorflow实现自注意力模块

首先在自定义层的build()中定义所有 1×1 卷积层和权重。这里,使用频谱归一化函数作为卷积层的核约束:

class SelfAttention(Layer):
    def __init__(self):
        super(SelfAttention, self).__init__()

    def build(self, input_shape):
        n,h,w,c = input_shape
        self.n_feats = h * w
        self.conv_theta = Conv2D(c//8, 1, padding='same', kernel_constraint=SpectralNorm(), name='Conv_Theta')
        self.conv_phi = Conv2D(c//8, 1, padding='same', kernel_constraint=SpectralNorm(), name='Conv_Phi')
        self.conv_g = Conv2D(c//8, 1, padding='same', kernel_constraint=SpectralNorm(), name='Conv_g')
        self.conv_attn_g = Conv2D(c//8, 1, padding='same', kernel_constraint=SpectralNorm(), name='Conv_AttnG')
        self.sigma = self.add_weight(shape=[1], initializer='zeros', trainable=True, name='sigma')

需要注意的是:

  1. 内部的激活可以减小尺寸,以使计算运行更快。
  2. 在每个卷积层之后,激活由形状 (H, W, C) 被重塑为形状为 (H*W, C) 的二维矩阵。然后,我们可以在矩阵上使用矩阵乘法。

接下来在 call() 函数中将各层进行连接,用于执行自注意力操作。首先计算 θ \theta θ,φ φφ 和 g g g:

    def call(self, x):
        n, h, w, c = x.shape
        theta = self.conv_theta(x)
        theta = tf.reshape(theta, (-1, self.n_feats, theta.shape[-1]))
        phi = self.conv_phi(x)
        phi = tf.nn.max_pool2d(phi, ksize=2, strides=2, padding='VALID')
        phi = tf.reshape(phi, (-1, self.n_feats//4, phi.shape[-1]))
        g = self.conv_g(x)
        g = tf.nn.max_pool2d(g, ksize=2, strides=2, padding='VALID')
        g = tf.reshape(g, (-1, self.n_feats//4, g.shape[-1]))

然后,将按以下方式计算注意力图:

        attn = tf.matmul(theta, phi, transpose_b=True)
        attn = tf.nn.softmax(attn)

最后,将注意力图与查询 g g g 相乘,并产生最终输出:

        attn_g = tf.matmul(attn, g)
        attn_g = tf.reshape(attn_g, (-1, h, w, attn_g.shape[-1]))
        attn_g = self.conv_attn_g(attn_g)
        output = x + self.sigma * attn_g
        return output

Original: https://blog.csdn.net/LOVEmy134611/article/details/118894270
Author: 盼小辉丶
Title: TensorFlow实现自注意力机制(Self-attention)

相关文章
人工智能基础整理 人工智能

人工智能基础整理

人工智能基础整理 考前复习 随便整了一下 填空题 目前人工智能的主要学派有三家: 符号主义、 进化主义、 连接主义 知识图谱本质上是 结构化的语义知识库,是一种由节点和边组成的 图数据结构,以 符号形...
快速上手tensorflow:tensor运算后的类型 人工智能

快速上手tensorflow:tensor运算后的类型

总论(这是我的总结可以不看直接看下面的安装) 1、 不用看那些版本对应表啊!!!! 记录那些年自己掉过的坑,自己也是看了其他人好多博客,总结下来一个核心问题是要求版本对应,发现大家都是这样教的,以这样...