Skip to content
ImagineWorld

Graph Analysis for Credit Card Transactions

node_idnode-book_graph-machine-learning_chapter-09-graph-analysis-for-credit-card-transactions
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num9
chapter_titleGraph Analysis for Credit Card Transactions
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 09: Graph Analysis for Credit Card Transactions

Section titled “Chapter 09: Graph Analysis for Credit Card Transactions”

Fraud detection — building graphs from transactions with NetworkX, network topology, community detection, supervised and unsupervised fraud approaches, node feature generation, hyperparameter tuning.

Analysis of financial data is one of the most common and important domains in big data and data analysis. Due to the increasing number of mobile devices and the introduction of standard platforms for online payments, the amount of transactional data that banks are producing and consuming is increasing exponentially.

As a consequence, new tools and techniques are needed to exploit as much as we can from this huge amount of information in order to better understand customers’ behavior and support data-driven decisions in business processes. Data can also be used to build better mechanisms to improve security in the online payment process. Indeed, at the same time as online payment systems are becoming increasingly popular due to e-commerce platforms, cases of fraud are also increasing. An example of a fraudulent transaction is one performed with a stolen credit card. In this case, the fraudulent transaction will be different from the transactions made by the original owner of the credit card. This difference in transactional patterns can serve as a basis for detecting fraud in automated fraud detection systems.

However, building automatic procedures to detect fraudulent transactions could be a complex problem due to the large number of variables involved. Graph machine learning offers a powerful approach to tackle this challenge by representing transactional data as a graph, enabling the detection of complex relationships and patterns, such as communities of fraudulent behavior, that may be missed by traditional methods.

In this chapter, we will describe how we can represent credit card transaction data as a graph in order to automatically detect fraudulent transactions using machine learning algorithms. We will start processing the dataset by applying some of the techniques and algorithms we described in previous chapters to build a fraud detection algorithm.

The following topics will be covered in this chapter:

  • Generating a graph from credit card transactions
  • Extraction of properties and communities from the graph
  • Application of supervised and unsupervised machine learning algorithms to fraud classification

Building graphs from credit card transactions

Section titled “Building graphs from credit card transactions”

The dataset used in this chapter is the Credit Card Transactions Fraud Detection dataset available on Kaggle at the following URL: https://www.kaggle.com/kartik2112/fraud-detection?select=fraudTrain.csv. We will build two approaches for fraud detection, based on bipartite and tripartite graphs.

The dataset is made up of simulated credit card transactions containing legitimate and fraudulent transactions for the period January 1, 2019 to December 31, 2020. It includes the credit cards of 1,000 customers performing transactions with a pool of 800 merchants. The dataset was generated using Sparkov data generation. More information about the generation algorithm is available at the following URL: https://github.com/namebrandon/Sparkov_Data_Generation.

For each transaction, the dataset contains 23 different features. In the following table, we will show only the information that will be used in this chapter:

Table 9.1: List of variables used in this chapter

Table 9.1: List of variables used in this chapter

The dataset is indeed a simplified version, where only transaction core data is retained. Despite this, the dataset will nevertheless allow a rich analysis of the behavioral patterns and build a fraud detection model. In real-world scenarios, transactional data is generally complemented by metadata for both customers (like emails, phone numbers, addresses, etc.) and merchants (address, product group, legal entity, retailer, etc.) that can be encoded in node features and is generally extremely critical to allow graph-based entity resolution.

For the purposes of our analysis, we will use the fraudTrain.csv file. As already suggested, take a look at the dataset by yourself. It is strongly suggested to explore and become as comfortable as possible with the dataset before starting any machine learning task.

The first step of our analysis will be to load the dataset and build a graph. Since the dataset represents a simple list of transactions, we need to perform several operations to build the final credit card transaction graph. The dataset is a simple CSV file; we can use pandas to load the data as follows:

import pandas as pd
df = df[df["is_fraud"]==0].sample(frac=0.20, random_state=42).append(df[df["is_fraud"] == 1])

In order to help you deal with the dataset, we selected 20% of the genuine transactions and all of the fraudulent transactions. As a result, from a total of 1,296,675 transactions, we will only use 265,342. Moreover, we can also investigate the number of fraudulent and genuine transactions in our dataset as follows:

df["is_fraud"].value_counts()

By way of a result, we get the following:

0 257834
1 7506

In other words, from a total of 265,342 transactions, only 7506 (2.83 %) are fraudulent transactions, while the others are genuine.

The dataset can be represented as a graph using the networkx library. Before starting with the technical description, we will start by specifying how the graph is built from the data. We used two different approaches to build the graph – namely, the bipartite and tripartite approaches, as described in the paper APATE: A Novel Approach for Automated Credit Card Transaction Fraud Detection Using Network-Based Extensions, available at https://www.scinapse.io/papers/614715210.

For the bipartite approach, we build a weighted bipartite graph G=(V,E)G=(V,E), where V=C∪MV=C \cup M, and where each node Ci∈CC_i \in C represents a customer, and each node Mj∈MM_j \in M represents a merchant. An edge e∈Ee \in E is created if a transaction exists from the customer, CiC_i, to the merchant, MjM_j. Finally, to each edge of the graph, we assign an always-positive weight representing the amount (in US dollars) of the transaction. In our formalization, we allow both directed and undirected graphs.

Since the dataset represents temporal transactions, multiple interactions can happen between a customer and a merchant. In both our formalizations, we decided to collapse all that information into a single graph. In other words, if multiple transactions are present between a customer and a merchant, we will build a single edge between the two nodes with its weight given by the sum of all the transaction amounts. A graphical representation of the direct bipartite graph is shown in Figure 9.1:

Figure 9.1: Bipartite graph generated from the input dataset

Figure 9.1: Bipartite graph generated from the input dataset

The bipartite graph we defined can be built using the following code:

def build_graph_bipartite(df_input, graph_type=nx.Graph()):
df = df_input.copy()
mapping = {x:node_id for node_id,x in enumerate(set(df["cc_num"].values.tolist() + df["merchant"].values.tolist()))}
df["from"] = df["cc_num"].apply(lambda x: mapping[x])
df["to"] = df["merchant"].apply(lambda x: mapping[x])
df = df[['from', 'to', "amt", "is_fraud"]].groupby(['from', 'to']).agg({"is_fraud": "sum", "amt": "sum"}).reset_index()
df["is_fraud"] = df["is_fraud"].apply(lambda x: 1 if x>0 else 0)
G = nx.from_edgelist(df[["from", "to"]].values, create_using=graph_type)
nx.set_edge_attributes(G, {(int(x["from"]), int(x["to"])):x["is_fraud"] for idx, x in df[["from","to","is_fraud"]].iterrows()}, "label")
nx.set_edge_attributes(G,{(int(x["from"]), int(x["to"])):x["amt"] for idx, x in df[["from","to","amt"]].iterrows()}, "weight")
return G

The code is quite simple. To build the bipartite credit card transaction graph, we use different networkx functions. To go more in-depth, the operations we performed in the code are as follows:

  1. We built a map to assign a node_id to each merchant or customer.
  2. Multiple transactions are aggregated in a single transaction.
  3. The networkx function, nx.from_edgelist, is used to build the networkx graph.
  4. Two attributes (namely, weight and label) are assigned to each edge. The former represents the total number of transactions between the two nodes, whereas the latter indicates whether the transaction is genuine or fraudulent.

As we can also see from the code, we can select whether we want to build a directed or an undirected graph. We can build an undirected graph by calling the following function:

G_bu = build_graph_bipartite(df, nx.Graph(name="Bipartite Undirect"))

We can instead build a direct graph by calling the following function:

G_bd = build_graph_bipartite(df, nx.DiGraph(name="Bipartite Direct"))

The only difference is given by the second parameter we pass in the constructor.

The tripartite approach is an extension of the previous one, also allowing the transactions to be represented as a vertex. While, on the one hand, this approach drastically increases network complexity, on the other hand, it allows extra node embeddings to be built for merchants and cardholders and every transaction. Formally, for this approach, we build a weighted tripartite graph, G=(V,E)G=(V,E), where V=C∪M∪TV=C \cup M \cup T, where each node Ci∈CC_i \in C represents a customer, each node Mj∈MM_j \in M represents a merchant, and each node Tk∈TT_k \in T is a transaction. Two edges (Ci,Tk)(C_i, T_k) and (Tk,Mj)(T_k, M_j) are created for each transaction, TkT_k, from the customer, CiC_i, to the merchant, MjM_j.

Finally, to each edge of the graph, we assign an always-positive weight representing the amount (in US dollars) of the transaction. Since, in this case, we create a node for each transaction, we do not need to aggregate multiple transactions from a customer to a merchant. Moreover, as for the other approach, in our formalization, we allow both directed and undirected graphs. A graphical representation of the direct bipartite graph is shown in Figure 9.2:

Figure 9.2: Tripartite graph generated from the input dataset

Figure 9.2: Tripartite graph generated from the input dataset

The tripartite graph we defined can be built using the following code:

def build_graph_tripartite(df_input, graph_type=nx.Graph()):
df = df_input.copy()
mapping = {x:node_id for node_id,x in enumerate(set(df.index.values.tolist() + df["cc_num"].values.tolist() + df["merchant"].values.tolist()))}
df["in_node"] = df["cc_num"].apply(lambda x: mapping[x])
df["out_node"] = df["merchant"].apply(lambda x: mapping[x])
G = nx.from_edgelist([(x["in_node"], mapping[idx]) for idx, x in df.iterrows()] + [(x["out_node"], mapping[idx]) for idx, x in df.iterrows()], create_using=graph_type)
nx.set_edge_attributes(G,{(x["in_node"], mapping[idx]):x["is_fraud"] for idx, x in df.iterrows()}, "label")
nx.set_edge_attributes(G,{(x["out_node"], mapping[idx]):x["is_fraud"] for idx, x in df.iterrows()}, "label")
nx.set_edge_attributes(G,{(x["in_node"], mapping[idx]):x["amt"] for idx, x in df.iterrows()}, "weight")
nx.set_edge_attributes(G,{(x["out_node"], mapping[idx]):x["amt"] for idx, x in df.iterrows()}, "weight")
return G

The code is quite simple. To build the tripartite credit card transaction graph, we use different networkx functions. To go more in-depth, the operations we performed in the code are as follows:

  1. We built a map to assign a node_id to each merchant, customer, and transaction.
  2. The networkx function, nx.from_edgelist, is used to build the networkx graph.
  3. Two attributes (namely, weight and label) are assigned to each edge. The former represents the total number of transactions between the two nodes, whereas the latter indicates whether the transaction is genuine or fraudulent.

As we can also see from the code, we can select whether we want to build a directed or an undirected graph. We can build an undirected graph by calling the following function:

G_tu = build_graph_tripartite(df, nx.Graph(name="Tripartite Undirect"))

We can instead build a direct graph by calling the following function:

G_td = build_graph_tripartite(df, nx.DiGraph(name="Tripartite Direct"))

The only difference is given by the second parameter we pass in the constructor.

In the formalized graph representation that we introduced, the real transactions are represented as edges. According to this structure for both bipartite and tripartite graphs, the classification of fraudulent/genuine transactions is described as an edge classification task. In this task, the goal is to assign to a given edge a label (0 for genuine, 1 for fraudulent) describing whether the transaction the edge represents is fraudulent or genuine.

In the rest of this chapter, we use both bipartite and tripartite undirected graphs for our analysis, denoted by the Python variables G_bu and G_tu, respectively. We will leave to you, as an exercise, an extension of the analyses proposed in this chapter to direct graphs.

We begin our analysis with a simple check to validate whether our graph is a real bipartite graph using the following code:

from networkx.algorithms import bipartite
all([bipartite.is_bipartite(G) for G in [G_bu,G_tu]])

As a result, we get True. This check gives us the certainty that the two graphs are actually bipartite/tripartite graphs. Note that networkx does not have an is_tripartite check, but the constraint to be verified here is that a link between nodes of the same type doesn’t exist, which would apply to bipartite, tripartite, or any n-partite graphs.

Moreover, using the following command, we can get some basic statistics:

for G in [G_bu, G_tu]:
print(nx.info(G))

By way of a result, we get the following:

Name: Bipartite Undirect
Type: Graph
Number of nodes: 1676
Number of edges: 201725
Average degree: 240.7220
Name: Tripartite Undirect
Type: Graph
Number of nodes: 267016
Number of edges: 530680
Average degree: 3.9749

As we can see, the two graphs differ in the number of nodes and the number of edges. The bipartite undirected graph has 1,676 nodes, equal to the number of customers plus the number of merchants, and 201,725 edges.

The tripartite undirected graph has 267,016 nodes, equal to the number of customers plus the number of merchants plus all the transactions. In this graph, the number of edges, as expected, is higher (530,680) compared to the bipartite graph. The interesting difference in this comparison is given by the average degree of the two graphs: the average degree of the bipartite graph is higher than that of the tripartite graph. This was expected, as in the tripartite graph, the connections are “split” by the presence of the transaction nodes. This makes the connections more “direct,” which increases connectivity between nodes. Therefore, the resulting average degree is lower.

In the next section, we will describe how we can now use the transaction graphs that we generated to perform a more complete statistical analysis.

In this section, we are going to analyze some graph metrics to have a clear picture of the general structure of the graph. We will be using networkx to compute most of the useful metrics we saw in Chapter 1, Getting Started with Graphs. We will try to interpret the metrics to gain insights into the graph.

A good starting point for our analysis is the extraction of simple graph metrics to have a general understanding of the main properties of bipartite and tripartite transaction graphs.

We start by looking at the distribution of the degree for both bipartite and tripartite graphs using the following code:

for G in [G_bu, G_tu]:
plt.figure(figsize=(10,10))
degrees = pd.Series({k: v for k, v in nx.degree(G)})
degrees.plot.hist()
plt.yscale("log")

By way of a result, we get the following plots:

Figure 9.3: Degree distribution for bipartite (left) and tripartite (right) graphs

Figure 9.3: Degree distribution for bipartite (left) and tripartite (right) graphs

From Figure 9.3, it is possible to see how the distribution of nodes reflects the average degree we previously saw. In greater detail, the bipartite graph has a more variegated distribution, with a peak of around 300. For the tripartite graph, the distribution has a big peak for degree 0, while the other part of the tripartite degree distribution is similar to the bipartite distribution. These distributions completely reflect the differences in how the two graphs were defined. Indeed, if bipartite graphs are made by connections from the customer to the merchant, in the tripartite graph, all the connections pass through the transaction nodes. Those nodes are the majority in the graph, and they all have a degree of 2 (an edge from a customer and an edge to a merchant). As a consequence, the frequency in the bin representing degree 2 is equal to the number of transaction nodes.

In the next subsection, we will continue our investigation by analyzing some key metrics for the graphs:

  • Edge weight
  • Node centrality
  • Assortativity

Edge weight

  1. We begin by computing the quantile distribution, as it provides a concise summary of the data by dividing the range of the edge weights into intervals of equal probability:

    for G in [G_bu, G_tu]:
    allEdgesWeights = pd.Series({(d[0], d[1]): d[2]["weight"] for d in G.edges(data=True)})
    print(np.quantile(allEdgesWeights.values,[0.10,0.50,0.70,0.9]))
  2. By way of a result, we get the following:

    array([ 5.03 , 58.25 , 98.44 , 215.656])
    array([ 4.21, 48.51, 76.4 , 147.1 ])
  3. We can also plot (in log scale) the distribution of edges weight, cut to the 90th percentile by using allEdgesWeightsFiltered.plot.hist(bins=40). The result is shown in the following charts:

Figure 9.4: Edge weight distribution for bipartite (left) and tripartite (right) graphs

Figure 9.4: Edge weight distribution for bipartite (left) and tripartite (right) graphs

We can see how, due to the aggregation of the transaction having the same customer and merchant, the distribution of the bipartite graph is shifted to the right (high values) compared to the tripartite graph, where edge weights were not computed by aggregating multiple transactions.

Node centrality

  1. We will now investigate the node centrality via the betweenness centrality metric. It measures how many shortest paths pass through a given node, giving an idea of how central that node is for the spreading of information inside the network. We can compute the distribution of node centrality by using the following command:

    for G in [G_bu, G_tu]:
    plt.figure(figsize=(10,10))
    bc_distr = pd.Series(nx.betweenness_centrality(G, k=200))
    bc_distr.plot.hist()
    plt.yscale("log")
  2. As a result, we get the following distributions:

Figure 9.5: Betweenness centrality distribution for bipartite (left) and tripartite (right) graphs

Figure 9.5: Betweenness centrality distribution for bipartite (left) and tripartite (right) graphs

As can be seen, the betweenness centrality is low for both graphs. This can be understood due to the large number of non-bridging nodes inside the network. Similar to what we saw for the degree distribution, the distribution of betweenness centrality values is different in the two graphs. The bipartite graph has a more variegated distribution with a mean of 0.00072, while in the tripartite graph, the transaction nodes move the distribution values and lower the mean to 1.38e-05. Also, we can see that the distribution for the tripartite graph has a big peak, representing the transaction nodes, and the rest of the distribution is quite similar to the bipartite distribution.

Assortativity

  1. We can finally compute the assortativity of the two graphs using the following code:

    for G in [G_bu, G_tu]:
    print(nx.degree_pearson_correlation_coefficient(G))
  2. By way of a result, we get the following:

    -0.1377432041049189
    -0.8079472914876812

Here, we can observe how both graphs have a negative assortativity, which likely shows that well-connected individuals associate with poor-connected individuals. For the bipartite graph, the value is low (-0.14), since customers who have a low degree are only connected with merchants who have high degrees due to the high number of incoming transactions.

The assortativity is even lower (-0.81) for the tripartite graph. This behavior could be attributed to the presence of the transaction nodes, as these nodes always have a degree of 2, and they are linked to customers and merchants represented by highly connected nodes.

Another interesting analysis we can perform is community detection, as communities often correspond to meaningful substructures in the graph, where fraudulent activities may be concentrated. This analysis can help to identify specific fraudulent patterns:

  1. The code to perform community extraction is as follows:

    import community
    for G in [G_bu, G_tu]:
    parts = community.best_partition(G, random_state=42, weight='weight')
    communities = pd.Series(parts)
    print(communities.value_counts().sort_values(ascending=False))

In this code, we simply use the community library to extract the communities in the input graph. We then print the communities detected by the algorithms, sorted according to the number of nodes contained.

  1. For the bipartite graph, we obtain the following output:

    5 546
    0 335
    7 139
    2 136
    4 123
    3 111
    8 83
    9 59
    10 57
    6 48
    11 26
    1 13
  2. For the tripartite graph, we obtain the following output:

    11 4828
    3 4493
    26 4313
    94 4115
    8 4036
    ...
    47 1160
    103 1132
    95 954
    85 845
    102 561
  3. Due to the large number of nodes in the tripartite graph, we found 106 communities (we reported just a subset of them), whereas, for the bipartite graph, only 12 communities were found.

  4. To have a clear picture of the tripartite graph, it is better to plot the distribution of the nodes contained in the different communities using the following command:

    communities.value_counts().plot.hist(bins=20)
  5. By way of a result, we get the following:

Figure 9.6: Distribution of communities’ node size

Figure 9.6: Distribution of communities’ node size

From the diagram, it is possible to see that the peak is reached around 2,500. This means that more than 30 large communities have more than 2,000 nodes. From the plot, it is also possible to see that a few communities have fewer than 1,000 nodes and more than 3,000 nodes.

  1. For each set of communities detected by the algorithm, we can compute the percentage of fraudulent transactions. The goal of this analysis is to identify specific subgraphs where there is a high concentration of fraudulent transactions:

    graphs = []
    d = {}
    for x in communities.unique():
    tmp = nx.subgraph(G, communities[communities==x].index)
    fraud_edges = sum(nx.get_edge_attributes(tmp, "label").values())
    ratio = 0 if fraud_edges == 0 else (fraud_edges/tmp.number_of_edges())*100
    d[x] = ratio
    graphs += [tmp]
    print(pd.Series(d).sort_values(ascending=False))
  2. The code simply generates a node-induced subgraph by using the nodes contained in a specific community. The graph is used to compute the percentage of fraudulent transactions as a ratio of the number of fraudulent edges over the number of all the edges in the graph.

  3. For the bipartite graph, we will obtain the following output:

    9 26.905830
    10 25.482625
    6 22.751323
    2 21.993834
    11 21.333333
    3 20.470263
    8 18.072289
    4 16.218905
    7 6.588580
    0 4.963345
    5 1.304983
    1 0.000000
  4. We can also plot a node-induced subgraph detected by the community detection algorithm by using the following code:

    gId = ...
    spring_pos = nx.spring_layout(graphs[gId])
    edge_colors = ["r" if x == 1 else "g" for x in nx.get_edge_attributes(graphs[gId], 'label').values()]
    nx.draw_networkx(graphs[gId], pos=spring_pos, node_color=default_node_color, edge_color=edge_colors, with_labels=False, node_size=15)

Given a particular community index, gId, the code extracts the node-induced subgraph, using the node available in the gId community index, and plots the graph obtained.

  1. For each community, we have the percentage of its fraudulent edges. To have a better description of the subgraph, we can plot community 10 by executing the previous line of code using gId=10. As a result, we get the following:

Figure 9.7: Induced subgraph of community 10 for the bipartite graph

Figure 9.7: Induced subgraph of community 10 for the bipartite graph

  1. The image of the induced subgraph allows us to better understand whether specific patterns are visible in the data.

  2. Similarly, by running the above code on the tripartite graph, we obtain the following output:

    6 6.857728
    94 6.551151
    8 5.966981
    1 5.870918
    89 5.760271
    ...
    102 0.889680
    72 0.836013
    85 0.708383
    60 0.503461
    46 0.205170
  3. Due to the large number of communities, we can plot the distribution of the fraudulent over genuine ratio with the following command:

    pd.Series(d).plot.hist(bins=20)
  4. By way of a result, we get the following:

Figure 9.8: Distribution of communities’ fraudulent/genuine edge ratio

Figure 9.8: Distribution of communities’ fraudulent/genuine edge ratio

From the diagram, we can observe that a large part of the distribution is around communities having a ratio of between 2 and 4. There are a few communities with a low ratio (<1) and with a high ratio (>5).

  1. Also, for the tripartite graph, we can plot community 6 (with a ratio of 6.86), made by 1,935 nodes, by executing the previous line of code using gId=6:

Figure 9.9: Induced subgraph of community 6 for the tripartite graph

Figure 9.9: Induced subgraph of community 6 for the tripartite graph

As for the bipartite use case, in this image, we can see an interesting pattern that could be used to perform a deeper exploration of some important graph sub-regions.

In this section, we performed some explorative tasks to better understand the graphs and their properties. We also gave an example describing how a community detection algorithm can be used to spot patterns in the data. In the next section, we will describe how the bipartite and tripartite graphs and their properties can be utilized by graph machine learning algorithms to build automatic procedures for fraud detection using supervised and unsupervised approaches.

Applying supervised and unsupervised fraud approaches to fraud detection

Section titled “Applying supervised and unsupervised fraud approaches to fraud detection”

As we already discussed at the beginning of this chapter, transactions are represented by edges, and we then want to classify each edge in the correct class: fraudulent or genuine. The pipeline we will use to perform the classification task is the following:

  • A sampling procedure for the imbalanced task
  • The use of an unsupervised embedding algorithm to create a feature vector for each edge
  • The application of supervised and unsupervised machine learning algorithms to the feature space defined in the previous point

Since our dataset is strongly imbalanced, with fraudulent transactions representing 2.83% of total transactions, we need to apply some techniques to deal with unbalanced data. In this use case, we will apply a simple random undersampling strategy. Going into more depth, we will take a subsample of the majority class (genuine transactions) to match the number of samples of the minority class (fraudulent transactions). This is just one of the many techniques available in literature. It is also possible to use outlier detection algorithms, such as isolation forests, to detect fraudulent transactions as outliers in the data. We leave it to you, as an exercise, to extend the analyses using other techniques to deal with imbalanced data, such as random oversampling or using cost-sensitive classifiers for the classification task. Specific techniques for node and edge sampling that can be directly applied to the graph will be described in Chapter 13, Novel Trends on Graphs. Here are the steps to try this:

  1. The code we use for random undersampling is as follows:

    from sklearn.utils import resample
    df_majority = df[df.is_fraud==0]
    df_minority = df[df.is_fraud==1]
    df_maj_dowsampled = resample(df_majority, n_samples=len(df_minority), random_state=42)
    df_downsampled = pd.concat([df_minority, df_maj_dowsampled])
    G_down = build_graph_bipartite(df_downsampled, nx.Graph())
  2. The code is straightforward. We applied the resample function of the sklearn package to filter the downsample function of the original data frame. We then build a graph using the build_graph_bipartite function defined at the beginning of the chapter. To create the tripartite graph, the build_graph_tripartite function should be used.

  3. As the next step, we split the dataset into training and validation with a ratio of 80/20:

    from sklearn.model_selection import train_test_split
    train_edges, val_edges, train_labels, val_labels = train_test_split(list(range(len(G_down.edges))), list(nx.get_edge_attributes(G_down, "label").values()), test_size=0.20, random_state=42)
    edgs = list(G_down.edges)
    train_graph = G_down.edge_subgraph([edgs[x] for x in train_edges]).copy()
    train_graph.add_nodes_from(list(set(G_down.nodes) - set(train_graph.nodes)))

As before, in this case, the code is straightforward since we simply apply the train_test_split function of the sklearn package.

We can now build the feature space using the Node2Vec algorithm, as follows:

from node2vec import Node2Vec
node2vec = Node2Vec(train_graph, weight_key='weight')
model = node2vec.fit(window=10)

Node2Vec results (which provide each node with a vector) are then aggregated to produce the feature set for the edges, as described in Chapter 4, Unsupervised Graph Learning.

Different choices for the aggregation can be used, resulting in slightly different variations for the Edge2Vec algorithm. For instance, using the WeightedL1Embedder, the embedding can be obtained by:

from node2vec.edges import WeightedL1Embedder
embeddings = WeightedL1Embedder(keyed_vectors=model.wv)

The edge embedding that is obtained in this way will generate the final feature space used by the classifier. The specific type of node feature aggregation algorithm (WeightedL1Embedder, in this case) together with the various parameters used in the Node2Vec algorithm represent the hyperparameters of our machine learning pipeline.

Finally, we can train and evaluate a machine learning model using the feature set generated in the previous step. Here, we will use a RandomForestClassifier from the sklearn Python library, but of course, other choices could also be valid. Different performance metrics (namely, precision, recall, and F1 score) are computed on the validation test:

  1. First, we build the training and validation datasets:

    # Building training and validation sets
    train_embeddings = [embeddings[str(edgs[x][0]), str(edgs[x][1])] for x in train_edges]
    val_embeddings = [embeddings[str(edgs[x][0]), str(edgs[x][1])] for x in val_edges]
  2. Then, we train the classifier on the training set:

    rf = RandomForestClassifier(n_estimators=1000, random_state=42)
    rf.fit(train_embeddings, train_labels)
  3. Finally, we evaluate the performances on the validation set:

    y_pred = rf.predict(val_embeddings)
    print('Precision:', metrics.precision_score(val_labels, y_pred))
    print('Recall:', metrics.recall_score(val_labels, y_pred))
    print('F1-Score:', metrics.f1_score(val_labels, y_pred))

As mentioned in the previous subsection, the Edge2Vec algorithm can be seen as a hyperparameter for the machine learning pipeline. In the following code snippet, we loop over some possible choices for the node feature aggregation function, to identify the best choice for this particular dataset. The code to perform this task is the following:

from sklearn import metrics
from sklearn.ensemble import RandomForestClassifier
from node2vec.edges import HadamardEmbedder, AverageEmbedder, WeightedL1Embedder, WeightedL2Embedder
classes = [HadamardEmbedder, AverageEmbedder, WeightedL1Embedder, WeightedL2Embedder]
for cl in classes:
embeddings = cl(keyed_vectors=model.wv)
train_embeddings = [embeddings[str(edgs[x][0]), str(edgs[x][1])] for x in train_edges]
val_embeddings = [embeddings[str(edgs[x][0]), str(edgs[x][1])] for x in val_edges]
rf = RandomForestClassifier(n_estimators=1000, random_state=42)
rf.fit(train_embeddings, train_labels)
y_pred = rf.predict(val_embeddings)
print(cl)
print('Precision:', metrics.precision_score(val_labels, y_pred))
print('Recall:', metrics.recall_score(val_labels, y_pred))
print('F1-Score:', metrics.f1_score(val_labels, y_pred))

We can apply the preceding code to both bipartite and tripartite graphs to solve the fraud detection task. In the following table, we report the performances for the bipartite graph:

Table 9.2: Supervised fraud edge classification performances for a bipartite graph

Table 9.2: Supervised fraud edge classification performances for a bipartite graph

Embedding MethodPrecisionRecallF1 Score
HadamardEmbedder0.730.760.75
AverageEmbedder0.710.790.75
WeightedL1Embedder0.710.690.70
WeightedL2Embedder0.720.700.71

In the following table, we report the performances for the tripartite graph:

Table 9.3: Supervised fraud edge classification performances for a tripartite graph

Table 9.3: Supervised fraud edge classification performances for a tripartite graph

Embedding MethodPrecisionRecallF1 Score
HadamardEmbedder0.890.290.44
AverageEmbedder0.740.450.48
WeightedL1Embedder0.880.250.39
WeightedL2Embedder0.870.240.38

In Table 9.2 and Table 9.3, we reported the classification performances obtained using bipartite and tripartite graphs. As we can see from the results, in terms of F1 score, precision, and recall, the two methods show significant differences. Since, for both graph types, Hadamard and average edge embedding algorithms give the most interesting results, we are going to focus our attention on those two.

Going into more detail, the tripartite graph has better precision compared to the bipartite graph (0.89 and 0.74 for the tripartite graph versus 0.73 and 0.71 for the bipartite graph). In contrast, the bipartite graph has a better recall (0.76 and 0.79 for the bipartite graph versus 0.29 and 0.45 for the tripartite graph) and F1 score (0.75 and 0.75 for the bipartite graph versus 0.44 and 0.48 for the tripartite graph) than the tripartite graph. We can therefore conclude that, in this specific case, the use of a bipartite graph could be a better choice since it achieves high performances in terms of F1 score and recall with a smaller graph (in terms of nodes and edges) than the tripartite graph.

In the context of fraud detection, it is common to prioritize recall over precision, given the importance of not missing the detection of any fraud, and also at the expense of more false positives.

Unsupervised approach to fraudulent transaction identification

Section titled “Unsupervised approach to fraudulent transaction identification”

The same approach can also be applied in unsupervised tasks using k-means. The main difference is that the generated feature space will not undergo a train-validation split. Indeed, in the following code, we will compute the Node2Vec algorithm on the entire graph generated following the downsampling procedure:

nod2vec_unsup = Node2Vec(G_down, weight_key='weight')
unsup_vals = nod2vec_unsup.fit(window=10)

When building the node feature vectors, we can use different Egde2Vec algorithms to run the k-means algorithm, as follows:

from sklearn.cluster import KMeans
classes = [HadamardEmbedder, AverageEmbedder, WeightedL1Embedder, WeightedL2Embedder]
true_labels = [x for x in nx.get_edge_attributes(G_down, "label").values()]
for cl in classes:
embedding_edge = cl(keyed_vectors=unsup_vals.wv)
embedding = [embedding_edge[str(x[0]), str(x[1])] for x in G_down.edges()]
kmeans = KMeans(2, random_state=42).fit(embedding)
nmi = metrics.adjusted_mutual_info_score(true_labels, kmeans.labels_)
ho = metrics.homogeneity_score(true_labels, kmeans.labels_)
co = metrics.completeness_score(true_labels, kmeans.labels_)
vmeasure = metrics.v_measure_score(true_labels, kmeans.labels_)
print(cl)
print('NMI:', nmi)
print('Homogeneity:', ho)
print('Completeness:', co)
print('V-Measure:', vmeasure)

Different steps are performed in the previous code:

  1. For each Edge2Vec algorithm, the previously computed Node2Vec algorithm on training and validation sets is used to generate the feature space.

A KMeans clustering algorithm from the sklearn Python library is fitted on the feature set generated in the previous step. In the previous code snippet, we assumed k=2 as an example, although in general, the number of clusters is one hyperparameter of the modeling pipeline and is to be varied and optimized.

  1. Different performance metrics are used – namely, adjusted mutual information (MNI), homogeneity, completeness, and v-measure scores.

We can apply the code to both bipartite and tripartite graphs to solve the fraud detection task using the unsupervised algorithm. In the following table, we report the performances for the bipartite graph:

Table 9.4: Unsupervised fraud edge classification performances for the bipartite graph

Table 9.4: Unsupervised fraud edge classification performances for the bipartite graph

Embedding MethodNMIHomogeneityCompletenessV-Measure
HadamardEmbedder0.080.070.100.08
AverageEmbedder0.000.000.000.00
WeightedL1Embedder0.020.020.020.02
WeightedL2Embedder0.010.010.010.01

In the following table, we report the performances for the tripartite graph:

Table 9.5: Unsupervised fraud edge classification performances for the tripartite graph

Table 9.5: Unsupervised fraud edge classification performances for the tripartite graph

Embedding MethodNMIHomogeneityCompletenessV-Measure
HadamardEmbedder0.160.150.160.16
AverageEmbedder0.000.000.000.00
WeightedL1Embedder0.000.000.000.00
WeightedL2Embedder0.000.000.000.00

In Table 9.4 and Table 9.5, we reported the classification performances obtained using bipartite and tripartite graphs with the application of an unsupervised algorithm. As we can see from the results, the two methods show significant differences. It is also worth noticing that, in this case, the performances obtained with the Hadamard embedding algorithm clearly outperform all other approaches.

As shown by the tables, for this task, the performances obtained with the tripartite graph outstrip those obtained with the bipartite graph. In the unsupervised case, we can see how the introduction of the transaction nodes improves the overall performance. This additional layer of information may enable more accurate embeddings. Thus, in the unsupervised setting, for this specific use case and using as a reference the results obtained in Table 9.4 and Table 9.5, the use of the tripartite graph could be a better choice since it enables the attainment of superior performances compared with the bipartite graph.

On Kaggle, you can find further resources to analyze and explore datasets with financial transactions in which you can similarly apply the frameworks learned here. In particular, we suggest you investigate two other datasets:

The first one is the Czech Bank’s Financial Analysis dataset, available at https://github.com/Kusainov/czech-banking-fin-analysis. This dataset came from an actual Czech bank in 1999, for the period covering 1993–1998. The data pertaining to clients and their accounts consists of directed relations. The dataset does not come with labels on the transactions. It is therefore not possible to train a fraud detection engine using supervised machine learning techniques, whereas the unsupervised techniques would still apply.

The second dataset is the paysim1 dataset, available at https://www.kaggle.com/datasets/ealaxi/paysim1. This dataset comprises simulated mobile money transactions based on a sample of real transactions extracted from one month of financial logs from a mobile money service implemented in an African country. The original logs were provided by a multinational company that is the provider of a mobile financial service and is currently running in more than 14 countries across the globe. This dataset also contains labels on fraudulent/genuine transactions.

Moreover, it is worth pointing out that there can be different types of fraud, depending on the relationship between the fraudster and the entity being defruaded. In general, frauds are generally divided into:

  1. First-party fraud, where the fraudster uses their identity and/or fabricated information to deceive a business and obtain personal gain. Some examples of first-party fraud are making unauthorized purchases with stolen or false credit cards, or providing false records to obtain a loan.
  2. Second-party fraud, where a person internal to an organization or a business colludes with an external party in order to pursue an advantage against the organization or the business itself. The internal person generally abuses their position, knowledge, and/or access to internal information in order to perpetuate a personal gain.
  3. Third-party fraud, where an external entity, unrelated to a business or its customers, commits fraud at the expense of either of the two. Some examples of third-party fraud are phishing scams, counterfeit goods, or identity theft.

Each type of fraud may require a different set of controls and measures, as well as specific analytic algorithms. Indeed, the transaction dataset and the analysis presented in the chapter are more suited to address first-party frauds as, in general, models to spot this type of fraud focus on identifying spending patterns to then capture transactions dissimilar from the expected behavior. Graph analytics is generally very effective in clustering users, merchants, and communities to provide an effective implementation of behavior analytics. On the other hand, second-party fraud can be identified with the implementation of monitoring employee behavior, as well as compliance checks. Graph analytics can indeed be useful for these use cases. Similar to the first-party models, employee behavior can also be analyzed using graph machine learning, although the dataset may need to encode a number of other sources of information besides transactional data. From a compliance standpoint, process mining techniques that still rely on a graph representation of the various procedural steps/pathways can be effective in identifying fraudulent behavior or non-compliant processes. Finally, third-party fraud, especially in the form of phishing attacks, can also be addressed using graph machine learning. In this context, understanding the network from which the phishing attack comes as well as the URLs being used (which can also benefit from a graph representation) can be critical for building an effective phishing classifier.

In this chapter, we described how a classical fraud detection task can be described as a graph problem and how the techniques described in the previous chapters can be used to tackle the problem. Going into more detail, we introduced the dataset we used and described the procedure to transform the transactional data into two types of graph – namely, bipartite and tripartite undirected graphs.

We then computed local (along with their distributions) and global metrics for both graphs, comparing the results. Moreover, a community detection algorithm was applied to the graphs in order to spot and plot specific regions of the transaction graph where the density of fraudulent transactions is higher compared to the other communities.

Finally, we solved the fraud detection problem using supervised and unsupervised algorithms, comparing the performance of the bipartite and tripartite graphs. As the first step, since the problem was unbalanced with a higher presence of genuine transactions, we performed simple downsampling. We then applied different Edge2Vec algorithms in combination with a random forest for the supervised task, and k-means for the unsupervised task, achieving good classification performances.

This chapter concludes the series of examples that are used to show how graph machine learning algorithms can be applied to problems belonging to different domains, such as social network analysis, text analytics, and credit card transaction analysis.

In the next chapter, we will describe some practical uses for graph databases and graph processing engines that are useful for scaling out the analysis to large graphs.