Social Network Graphs
local graph
Chapter 07: Social Network Graphs
Section titled “Chapter 07: Social Network Graphs”Social network analysis — topology overview, node centrality, community detection, Node2Vec link prediction, GraphSAGE link prediction (featureless and with node features).
The growth of social networking sites has been one of the most active trends in digital media over recent years. Since the late 1990s, when the first social applications were published, they have attracted billions of active users worldwide, many of whom have integrated digital social interactions into their daily lives. New ways of communication are being driven by social networks such as Facebook, Twitter, and Instagram, among others. Users can share ideas, post updates and feedback, or engage in activities and events while sharing their broader interests on social networking sites.
Besides, social networks constitute a huge source of information for studying user behaviors, interpreting the interaction among people, and predicting their interests. Structuring them as graphs, where a vertex corresponds to a person and an edge represents the connection between them, provides a powerful tool to extract useful knowledge.
However, understanding the dynamics that drive the evolution of the social network is a complex problem due to a large number of variable parameters.
In this chapter, we will talk about how we can analyze the Facebook social network using graph theory and how we can solve useful problems such as link prediction and community detection using machine learning.
The following topics will be covered in this chapter:
- Overview of the dataset
- Network topology and community detection
- Embedding for supervised and unsupervised tasks
Overview of the dataset
Section titled “Overview of the dataset”We will be using a SNAP public dataset, social circles: Facebook, from Stanford University (https://snap.stanford.edu/data/ego-Facebook.html).
The dataset was created by collecting Facebook user information from survey participants. In more detail, ego networks were created for 10 users. Each user was asked to identify all the circles (list of friends) to which their friends belong. On average, each user identified 19 circles in their ego networks, where each circle has on average 22 friends.
For each user, the following information was collected:
- Edges: An edge exists if two users are friends on Facebook.
- Node features: Features are scored as 1 if the user has this property in their profile and 0 otherwise. Features have been anonymized since the names of the features would reveal private data.
The 10 ego networks were then unified in a single graph that we are going to study.
Dataset download
Section titled “Dataset download”The dataset can be retrieved using the following URL: https://snap.stanford.edu/data/ego-Facebook.html. In particular, three files can be downloaded: facebook.tar.gz, facebook_combined.txt.gz, and readme-Ego.txt. Let’s inspect each file separately:
facebook.tar.gz: This is an archive containing four files for each ego user (40 files in total). Each file is named using the format Node.extension, whereNodeis the node ID of the ego user andextensionis one of edges, circles, feat, egofeat, or featnames. This is explained in more detail here:- Node.edges: Contains a list of edges for the network of node
Node. - Node.circles: Contains several lines (one for each circle). Each line consists of a name (the circle name) followed by a series of node IDs.
- Node.feat: Contains the features (0 if
Nodehas that feature, 1 otherwise) for each node in the ego network. - Node.egofeat: Contains the features of the ego user.
- Node.featname: Contains the names of the features.
- Node.edges: Contains a list of edges for the network of node
facebook_combined.txt.gz: This is an archive containing a single file,facebook_combined.txt, which is a list of edges from all the ego networks combined.readme-Ego.txt: This contains a description of the above-mentioned files.
Take a look at those files by yourself. It is strongly suggested to explore and become as comfortable as possible with the dataset before starting any machine learning task.
Loading the dataset using networkx
Section titled “Loading the dataset using networkx”The first step of our analysis will be loading the aggregated ego networks using networkx. As we have seen in the previous chapters, networkx is powerful for graph analysis and, given the size of the datasets, will be the perfect tool for the analysis that we will be doing in this chapter. However, for larger social network graphs with billions of nodes and edges, more specific tools might be required for loading and processing them. We will cover the tools and technologies used for scaling out the analysis in Chapter 10, Building a Data-Driven Graph-Powered Application.
As we have seen above, the combined ego network is represented as a list of edges. We can create an undirected graph from a list of edges using networkx as follows:
G = nx.read_edgelist("facebook_combined.txt", create_using=nx.Graph(), nodetype=int)Notice that here we are using an undirected graph because connections on Facebook are undirected: when you accept someone’s friend request, you are added to their friend list and vice versa (that is, an undirected edge is added to the graph).
Let’s print some basic information about the graph:
print(nx.info(G))The output should be as follows:
Name:Type: GraphNumber of nodes: 4039Number of edges: 88234Average degree: 43.6910As we can see, the aggregated network contains 4039 nodes and 88234 edges. This is a fairly connected network with the number of edges being more than 20 times the number of nodes. Due to the nature of the network, it is expected that several clusters will emerge, particularly because of the small-world properties of the individual ego networks. In a small-world network, nodes are highly clustered, meaning that individuals (or nodes) are more likely to be connected to their immediate neighbors, and groups of tightly connected nodes (clusters) form naturally. These clusters represent subgroups of ego users, each with their own localized connections, which are typically observed in social network structures.
Drawing the network will also help with better understanding what we are going to analyze. We can draw the graph using networkx as follows:
nx.draw_networkx(G, pos=spring_pos, with_labels=False, node_size=35)The output should be as follows:

Figure 7.1 – The aggregated Facebook ego network
We can observe the presence of highly interconnected hubs. This is interesting from a social network analysis point of view since these hubs may result from underlying social mechanisms, such as the presence of influential individuals or key opinion leaders. For example, highly interconnected hubs could represent influential people in a community who have strong relationships with a large number of others, often acting as connectors between different groups. These hubs might also emerge due to mechanisms like preferential attachment (where new nodes are more likely to connect to already well-connected nodes) or homophily (where individuals tend to connect with others who are similar to themselves). These mechanisms can be further investigated to better understand the structure of an individual’s relationships within their social world.
Before continuing our analysis, let’s save the IDs of the ego-user nodes inside the network. We can retrieve them from the files contained in the facebook.tar.gz archive.
First, unpack the archive. The extracted folder will be named facebook. Let’s run the following Python code for retrieving the IDs by taking the first part of each filename:
ego_nodes = set([int(name.split('.')[0]) for name in os.listdir("facebook/")])We are now ready to analyze the graph. In particular, in the next section, we will better understand the structure of the graph by inspecting its properties. This will help us to have a clearer idea of its topology and its relevant characteristics.
Analyzing the graph structure
Section titled “Analyzing the graph structure”Understanding the topology of the network, the role of its nodes, and the presence of communities is a crucial step in the analysis of the social network. It is important to keep in mind that, in this context, nodes are actually users, each with its own interests, habits, and behaviors. Such knowledge will be extremely useful when performing predictions and/or finding insights.
We will be using networkx to compute a few useful metrics we have seen in Chapter 1, Getting Started with Graphs. We will try to give them an interpretation to collect insight into the graph. Let’s begin as usual, by importing the required libraries and defining some variables that we will use throughout the code:
import osimport mathimport numpy as npimport networkx as nximport matplotlib.pyplot as plt
default_edge_color = 'gray'default_node_color = '#407cc9'enhanced_node_color = '#f5b042'enhanced_edge_color = '#cc2f04'We can now proceed to the analysis.
Topology overview
Section titled “Topology overview”As we have already seen before, our combined network has 4,039 nodes and more than 80,000 edges. The next metric we will compute is assortativity. It will reveal information about the tendency of users to be connected with users with a similar degree. We can do that as follows:
assortativity = nx.degree_pearson_correlation_coefficient(G)The output should be as follows:
0.06357722918564912The assortativity coefficient ranges from -1 to 1, where a value of 1 indicates a perfect positive correlation (users tend to connect with others of similar degree) and -1 indicates a perfect negative correlation (users tend to connect with others of different degree). Here, we can observe a positive assortativity, likely showing that well-connected individuals associate with other well-connected individuals (as we have seen in Chapter 1, Getting Started with Graphs). This is expected since inside each circle, users tend to be highly connected to each other.
Transitivity could also help with better understanding how individuals are connected. Recall transitivity indicates the mean probability that two people with a common friend are themselves friends. Transitivity can range from 0 (no probability) to 1 (certainty):
t = nx.transitivity(G)The output should be as follows:
0.5191742775433075Here we have the half probability that two friends can or cannot have common friends.
The observation is also confirmed by computing the average clustering coefficient. The average clustering coefficient ranges from 0 (no clustering) to 1 (perfect clustering). Indeed, it can be considered as an alternative definition of transitivity:
aC = nx.average_clustering(G)The output should be as follows:
0.6055467186200876Notice that the clustering coefficient tends to be higher than the transitivity. Indeed, by definition, it puts more weight on vertices with a low degree, since they have a limited number of possible pairs of neighbors (the denominator of the local clustering coefficient).
Node centrality
Section titled “Node centrality”Once we have a clearer idea of what the overall topology looks like, we can proceed by investigating the importance of each individual inside the network. In Chapter 1, Getting Started with Graphs, we understood the significance of betweenness centrality. 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. The betweenness centrality can range from 0 (no shortest path passes through the node) to a higher value, with larger values indicating more central nodes. We can compute it using:
bC = nx.betweenness_centrality(G)np.mean(list(bC.values()))The output should be as follows:
0.0006669573568730229The average betweenness centrality is pretty low, which is understandable given the large amount of non-bridging nodes inside the network. In other words, many nodes have few or no shortest paths passing through them, which reduces their centrality. This suggests that the network may have many nodes that are more peripheral or isolated in terms of information flow. However, we could collect better insights by visually inspecting the graph. In particular, we will draw the combined ego network by enhancing nodes with the highest betweenness centrality. Let’s define a proper function for this:
def draw_metric(G, dct, spring_pos): top = 10 max_nodes = sorted(dct.items(), key=lambda v: -v[1])[:top] max_keys = [key for key,_ in max_nodes] max_vals = [val*300 for _, val in max_nodes] plt.axis("off") nx.draw_networkx(G, pos=spring_pos, cmap='Blues', edge_color=default_edge_color, node_color=default_node_color, node_size=3, alpha=0.4, with_labels=False) nx.draw_networkx_nodes(G, pos=spring_pos, nodelist=max_keys, node_color=enhanced_edge_color, node_size=max_vals)Now let’s invoke it as follows:
draw_metric(G,bC,spring_pos)The output should be as follows:

Figure 7.2: Betweenness centrality
Let’s also inspect the degree centrality of each node. Since this metric is related to the number of neighbors of a node, we will have a clearer idea of how nodes are well connected to each other. A higher degree centrality means that a node has more connections, which often indicates its importance in the network:
deg_C = nx.degree_centrality(G)np.mean(list(deg_C.values()))draw_metric(G,deg_C,spring_pos)The output should be as follows:
0.010819963503439287
Figure 7.3: Degree centrality
This value represents the average degree centrality across all nodes in the network. Given that degree centrality ranges from 0 (no connections) to 1 (the most connected node), this value suggests that, on average, the nodes in the network have relatively few connections.
Next, let’s look at the closeness centrality, which helps us understand how close nodes are to each other in terms of the shortest path. A higher closeness centrality means a node is closer, on average, to all other nodes in the network:
clos_C = nx.closeness_centrality(G)np.mean(list(clos_C.values()))draw_metric(G,clos_C,spring_pos)The output should be as follows:
0.2761677635668376
Figure 7.4: Closeness centrality
The closeness centrality ranges from 0 (isolated nodes) to 1 (nodes that can reach all other nodes in the fewest steps). Here, the average closeness centrality suggests that most nodes are somewhat close to each other, but not extremely close on average.
Overall, from the centrality analysis, it is interesting to observe that each central node seems to be part of a sort of community (this is reasonable, since central nodes might correspond to ego nodes of the network). It is also interesting to notice the presence of a bunch of highly interconnected nodes (especially from the closeness centrality analysis). Let’s thus identify these communities in the next part of our analysis.
Community detection
Section titled “Community detection”Since we are performing social network analysis, it is worth exploring one of the most interesting graph structures for social networks: communities. If you use Facebook, it is very likely that your friends reflect different aspects of your life: friends from the educational environment (high school, college, and so on), friends from your weekly football match, friends you have met at parties, and so on.
An interesting aspect of social network analysis is to automatically identify such groups. This can be done automatically, inferring them from topological properties, or semi-automatically, exploiting some prior insight.
As we have seen in Chapter 1, Getting Started with Graphs, and Chapter 6, Solving Common Graph-Based Machine Learning Problems, one good criterion is to try to compute the partition of the graph nodes that maximizes the modularity using the Louvain heuristics. Recall that modularity evaluates whether the density of edges within communities is higher than what would be expected in a random graph with the same degree distribution. By aiming to maximize modularity, we ensure that the computed partition reflects significant community structure, meaning the groups are highly interconnected internally but sparsely connected to other groups.
We can do that in networkx with the help of the python-louvain package, as follows:
import community
parts = community.best_partition(G)values = [parts.get(node) for node in G.nodes()]n_sizes = [5]*len(G.nodes())plt.axis("off")nx.draw_networkx(G, pos=spring_pos, cmap=plt.get_cmap("Blues"), edge_color=default_edge_color, node_color=values, node_size=n_sizes, with_labels=False)The output should be as follows:

Figure 7.5: Detected communities using networkx
In terms of social network analysis, the detected clusters likely represent groups of tightly connected individuals who share similar interests, affiliations, or social contexts. For example, dense clusters, represented in the figure using different colors, may correspond to groups, such as family units or friend groups. Furthermore, the connections between clusters highlight bridging individuals (e.g., ego users) or relationships, which act as connectors between different communities. These individuals are often influential in information dissemination across the network.
In this context, it is also interesting to investigate whether the ego users occupy some roles inside the detected communities. Let’s enhance the size and color of the ego user nodes, as follows:
for node in ego_nodes: n_sizes[node] = 250nodes = nx.draw_networkx_nodes(G,spring_pos,ego_nodes,node_color=[parts.get(node) for node in ego_nodes])nodes.set_edgecolor(enhanced_node_color)The output should be as follows:

Figure 7.6: Detected communities using networkx with ego user’s node size enhanced
The output highlights ego users as larger, distinctively colored nodes within their respective communities, making them easily identifiable. It is interesting to notice that some ego users belong to the same community. It is possible that ego users are actual friends on Facebook, and therefore their ego networks are partially shared. It is also interesting to notice that a few of the high betweenness nodes are not ego nodes and, conversely, some ego nodes are not high betweenness. This occurs because high-betweenness nodes act as connectors between communities, while ego nodes may be deeply embedded within their groups. Thus, structural importance and ego selection criteria are not always aligned.
We have now completed our basic understanding of the graph structure. We now know that some important nodes can be identified inside the network. We have also seen the presence of well-defined communities to which those nodes belong. Keep in mind these observations while performing the next part of the analysis, which is applying machine learning methods for supervised and unsupervised tasks.
Embedding for supervised and unsupervised tasks
Section titled “Embedding for supervised and unsupervised tasks”Social media nowadays represent one of the most interesting and rich sources of information. Every day, thousands of new connections arise, new users join the communities, and billions of posts are shared. Graphs mathematically represent all those interactions, helping to make order in all such spontaneous and unstructured traffic.
When dealing with social graphs, there are many interesting problems that can be addressed using machine learning. Under the correct settings, it is possible to extract useful insight from this huge amount of data for improving your marketing strategy, identifying users with dangerous behaviors (for example, terrorist networks), and predicting the likelihood that a user will read your new post.
Specifically, link prediction is one of the most interesting and important research topics in this field. Depending on what a connection in your social graph represents, by predicting future edges, you will be able to predict your next suggested friend, the next suggested movie, and which product you are likely to buy.
As we have already seen in Chapter 6, Solving Common Graph-Based Machine Learning Problems, the link prediction task aims at forecasting the likelihood of a future connection between two nodes, and it can be solved using several machine learning algorithms.
In the next examples, we will be applying machine learning supervised and unsupervised graph embedding algorithms for predicting future connections on the SNAP Facebook social graph. Furthermore, we will evaluate the contribution of node features in the prediction task.
Task preparation
Section titled “Task preparation”In order to perform the link prediction task, it is necessary to prepare our dataset. The problem will be treated as a supervised task. Pairs of nodes will be provided to each algorithm as input, while the target will be binary, that is, connected if the two nodes are actually connected in the network and not connected otherwise.
Since we aim to cast this problem as a supervised learning task, we need to create a training and testing dataset. We will, therefore, create two new subgraphs that have the same number of nodes but different numbers of edges (as some edges will be removed and treated as positive samples for training/testing the algorithm).
The stellargraph library provides a useful tool for splitting the data and creating training and test reduced subgraphs. This process is similar to the one we have already seen in Chapter 6, Solving Common Graph-Based Machine Learning Problems:
from sklearn.model_selection import train_test_splitfrom stellargraph.data import EdgeSplitterfrom stellargraph import StellarGraph
edgeSplitter = EdgeSplitter(G)graph_test, samples_test, labels_test = edgeSplitter.train_test_split(p=0.1, method="global", seed=24)
edgeSplitter = EdgeSplitter(graph_test, G)graph_train, samples_train, labels_train = edgeSplitter.train_test_split(p=0.1, method="global", seed=24)We are using the EdgeSplitter class to extract a fraction (p=10%) of all the edges in G, as well as the same number of negative edges, in order to obtain a reduced graph, graph_test. The train_test_split method also returns a list of node pairs, samples_test (where each pair corresponds to an existing or not-existing edge in the graph), and a list of binary targets (labels_test) of the same length of the samples_test list. Then, from such a reduced graph, we repeat the operation to obtain another reduced graph, graph_train, as well as the corresponding samples_train and labels_train lists.
We will be comparing three different methods for predicting missing edges:
- Method1:
node2vecwill be used to learn a node embedding without supervision. The learned embedding will be used as input for a supervised classification algorithm to determine whether the input pair is actually connected. - Method2: The graph neural network-based algorithm GraphSAGE will be used to jointly learn the embedding and perform the classification task.
- Method3: Hand-crafted features will be extracted from the graph and used as inputs for a supervised classifier, together with the nodes’ IDs.
Let’s analyze them in more detail.
Node2Vec-based link prediction
Section titled “Node2Vec-based link prediction”The proposed method involves several steps:
-
We use
node2vecto generate node embeddings without supervision from the training graph. This can be done using thenode2vecPython implementation, as we have already seen in Chapter 6, Solving Common Graph-Based Machine Learning Problems:from node2vec import Node2Vecnode2vec = Node2Vec(graph_train)model = node2vec.fit() -
Then, we use
HadamardEmbedderto generate an embedding for each pair of embedded nodes. Such feature vectors will be used as input to train the classifier:from node2vec.edges import HadamardEmbedderedges_embs = HadamardEmbedder(keyed_vectors=model.wv)train_embeddings = [edges_embs[str(x[0]),str(x[1])] for x in samples_train]
It’s time to train our supervised classifier. We will be using the RandomForest classifier, a powerful decision tree-based ensemble algorithm:
from sklearn.ensemble import RandomForestClassifierfrom sklearn import metricsrf = RandomForestClassifier(n_estimators=10)rf.fit(train_embeddings, labels_train)Finally, let’s apply the trained model for creating the embedding of the test set:
edges_embs = HadamardEmbedder(keyed_vectors=model.wv)test_embeddings = [edges_embs[str(x[0]),str(x[1])] for x in samples_test]-
Now we are ready to perform the prediction on the test set using our trained model:
y_pred = rf.predict(test_embeddings)print('Precision:', metrics.precision_score(labels_test, y_pred))print('Recall:', metrics.recall_score(labels_test, y_pred))print('F1-Score:', metrics.f1_score(labels_test, y_pred)) -
The output should be as follows:
Precision: 0.9701333333333333Recall: 0.9162573983125551F1-Score: 0.9424260086781945
Not bad at all! We can observe that the node2vec-based embedding already provides a powerful representation for actually predicting links on the combined Facebook ego network.
GraphSAGE-based link prediction
Section titled “GraphSAGE-based link prediction”Next, we will use GraphSAGE to learn node embeddings and classify edges. More specifically, we will build a two-layer GraphSAGE architecture that, given labeled pairs of nodes, outputs a pair of node embeddings. Then, a fully connected neural network will be used to process these embeddings and produce link predictions. Notice that the GraphSAGE model and the fully connected network will be concatenated and trained from end to end so that the embedding learning stage is influenced by the predictions.
A similar example using PyTorch is also available in the GitHub repository (https://github.com/PacktPublishing/Graph-Machine-Learning/blob/main/Chapter07) repository for interested readers.
Featureless approach
Section titled “Featureless approach”Before starting, you may recall from Chapters 4, Unsupervised Graph Learning, and Chapter 5, Supervised Graph Learning, that GraphSAGE needs node descriptors (features). Such features may or may not be available in your dataset. Let’s begin our analysis by not considering available node features. In this case, a common approach is to assign to each node a one-hot feature vector of length |V| (the number of nodes in the graph), where only the cell corresponding to the given node is 1, while the remaining cells are 0.
This can be done in Python and networkx as follows:
eye = np.eye(graph_train.number_of_nodes())fake_features = {n:eye[n] for n in G.nodes()}nx.set_node_attributes(graph_train, fake_features, "fake")
eye = np.eye(graph_test.number_of_nodes())fake_features = {n:eye[n] for n in G.nodes()}nx.set_node_attributes(graph_test, fake_features, "fake")In the preceding code snippet, we did the following:
- Created an identity matrix of size |V|. Each row of the matrix is the one-hot vector we need for each node in the graph.
- Then, we create a Python dictionary where, for each
Node(used as the key), we assign the corresponding row of the above-created identity matrix. - Finally, the dictionary is passed to the
networkxfunctionset_node_attributesto assign the “fake” features to each node in thenetworkxgraph.
Notice that the process is repeated for both training and test graphs.
The next step will be defining the generator that will be used to feed the model. We will be using the stellargraph GraphSAGELinkGenerator for this, which essentially provides the model with pairs of nodes as input:
from stellargraph.mapper import GraphSAGELinkGeneratorbatch_size = 64num_samples = [4, 4]
# convert graph_train and graph_test for stellargraphsg_graph_train = StellarGraph.from_networkx(graph_train, node_features="fake")sg_graph_test = StellarGraph.from_networkx(graph_test, node_features="fake")
train_gen = GraphSAGELinkGenerator(sg_graph_train, batch_size, num_samples)train_flow = train_gen.flow(samples_train, labels_train, shuffle=True, seed=24)
test_gen = GraphSAGELinkGenerator(sg_graph_test, batch_size, num_samples)test_flow = test_gen.flow(samples_test, labels_test, seed=24)Note that we also need to define the batch_size (number of inputs per minibatch) and the number of first- and second-hop neighbor samples that GraphSAGE should consider.
Finally, we are ready to create the model:
from stellargraph.layer import GraphSAGE, link_classificationfrom tensorflow import keras
layer_sizes = [20, 20]graphsage = GraphSAGE(layer_sizes=layer_sizes, generator=train_gen, bias=True, dropout=0.3)x_inp, x_out = graphsage.in_out_tensors()
# define the link classifierprediction = link_classification(output_dim=1, output_act="sigmoid", edge_embedding_method="ip")(x_out)model = keras.Model(inputs=x_inp, outputs=prediction)model.compile( optimizer=keras.optimizers.Adam(lr=1e-3), loss=keras.losses.mse, metrics=["acc"],)In the preceding snippet, we are creating a GraphSAGE model with two hidden layers of size 20, each with a bias term and a dropout layer for reducing overfitting. Then, the output of the GraphSAGE part of the module is concatenated with a link_classification layer that takes pairs of node embeddings (output of GraphSAGE), uses binary operators (inner product – ip – in our case) to produce edge embeddings, and finally passes them through a fully connected neural network for classification.
The model is optimized via the Adam optimizer (learning rate=1e-3) using the mean squared error as a loss function.
Let’s train the model for 20 epochs:
epochs = 20history = model.fit(train_flow, epochs=epochs, validation_data=test_flow)The tail of the output should be as follows:
Epoch 18/20loss: 0.4921 - acc: 0.8476 - val_loss: 0.5251 - val_acc: 0.7884Epoch 19/20loss: 0.4935 - acc: 0.8446 - val_loss: 0.5247 - val_acc: 0.7922Epoch 20/20loss: 0.4922 - acc: 0.8476 - val_loss: 0.5242 - val_acc: 0.7913As you can see, in the final epochs (18–20), the loss and accuracy values stabilize, suggesting the model has mostly converged. The validation metrics (val_loss and val_acc) are close to the training metrics, indicating that the model generalizes well and is not overfitting. Let’s compute the performance metrics over the test set:
from sklearn import metricsy_pred = np.round(model.predict(train_flow)).flatten()print('Precision:', metrics.precision_score(labels_train, y_pred))print('Recall:', metrics.recall_score(labels_train, y_pred))print('F1-Score:', metrics.f1_score(labels_train, y_pred))The output should be as follows:
Precision: 0.7156476303969199Recall: 0.983125550938169F1-Score: 0.8283289124668435As we can observe, performances are lower than the ones obtained in the node2vec-based approach. A possible reason may be attributed to the particular global structure of the social network: the dataset used here likely benefits from the global structural relationships captured by node2vec. Node2vec relies on the relationships captured through random walks, which emphasize connections between nodes that may not be directly adjacent but share a broader context in the network, while the featureless GraphSAGE relies on aggregating information from immediate neighbors. Without informative node features, this “local” approach may not fully capture the relationships present in the network defined by, for example, common interests. For this reason, real node features may represent a great source of information and we may want to use it. Let’s do that in the following test.
In this example, node2vec performs better than the featureless GraphSAGE. However, this may not be the case for other scenarios. The featureless GraphSAGE excels in scenarios dominated by local interactions, such as citation or community-based networks with strong localized patterns, and may be particularly effective when small, connected clusters or highly predictive immediate neighbors are present.
Introducing node features
Section titled “Introducing node features”The process of extracting node features for the combined ego network is quite verbose. This is because, as we explained in the first part of the chapter, each ego network is described using several files, as well as all the feature names and values. We have written useful functions for parsing all the ego networks in order to extract the node features. You can find their implementation in the Python notebook supplied with this book. Here, let’s just briefly summarize how they work:
- The
load_featuresfunction parses each ego network and creates two dictionaries: feature_index, which maps numeric indices to feature namesinverted_feature_indexes, which maps names to numeric indices- The
parse_nodesfunction receives the combined ego networkGand the ego node IDs. Then, each ego node in the network is assigned the corresponding features previously loaded using theload_featuresfunction.
Let’s invoke them in order to load a feature vector for each node in the combined ego network:
load_features()parse_nodes(G, ego_nodes)We can easily check the result by printing the information of one node in the network (e.g., the node with ID 0):
print(G.nodes[0])The output should be as follows:
{'features': array([1., 1., 1., ..., 0., 0., 0.])}As we can observe, the node has a dictionary containing a key named features. The corresponding value is the feature vector assigned to this node.
We are now ready to repeat the same steps used before for training the GraphSAGE model, this time using features as the key when converting the networkx graph to the stellargraph format:
sg_graph_train = StellarGraph.from_networkx(graph_train, node_features="features")sg_graph_test = StellarGraph.from_networkx(graph_test, node_features="features")Finally, as we have done before, we create the generators, compile the model, and train it for 20 epochs:
train_gen = GraphSAGELinkGenerator(sg_graph_train, batch_size, num_samples)train_flow = train_gen.flow(samples_train, labels_train, shuffle=True, seed=24)test_gen = GraphSAGELinkGenerator(sg_graph_test, batch_size, num_samples)test_flow = test_gen.flow(samples_test, labels_test, seed=24)
layer_sizes = [20, 20]graphsage = GraphSAGE(layer_sizes=layer_sizes, generator=train_gen, bias=True, dropout=0.3)x_inp, x_out = graphsage.in_out_tensors()prediction = link_classification(output_dim=1, output_act="sigmoid", edge_embedding_method="ip")(x_out)model = keras.Model(inputs=x_inp, outputs=prediction)model.compile( optimizer=keras.optimizers.Adam(lr=1e-3), loss=keras.losses.mse, metrics=["acc"],)epochs = 20history = model.fit(train_flow, epochs=epochs, validation_data=test_flow)Notice that we are using the same hyperparameters (including the number of layers, batch size, and learning rate) as well as the random seed, to ensure a fair comparison between the models.
The tail of the output should be as follows:
Epoch 18/20loss: 0.1337 - acc: 0.9564 - val_loss: 0.1872 - val_acc: 0.9387Epoch 19/20loss: 0.1324 - acc: 0.9560 - val_loss: 0.1880 - val_acc: 0.9340Epoch 20/20loss: 0.1310 - acc: 0.9585 - val_loss: 0.1869 - val_acc: 0.9365Let’s evaluate the model performance:
from sklearn import metricsy_pred = np.round(model.predict(train_flow)).flatten()print('Precision:', metrics.precision_score(labels_train, y_pred))print('Recall:', metrics.recall_score(labels_train, y_pred))print('F1-Score:', metrics.f1_score(labels_train, y_pred))We’ll check the output:
Precision: 0.7895418326693228Recall: 0.9982369978592117F1-Score: 0.8817084700517213As we can notice, the introduction of real node features has brought a good improvement, even if the best performances are still the ones achieved using the node2vec approach. This can be attributed to the effectiveness of capturing global structural patterns, which seems to be highly advantageous for this social network dataset and more informative than individual node features, according to the observed results. Such global patterns may include relationships between nodes that do not share direct edges but are closely connected within the graph’s topology, relationships that the random walks employed by node2vec likely enhance in their identification.
Finally, we will evaluate a shallow embedding approach where hand-crafted features will be used for training a supervised classifier.
Hand-crafted features for link prediction
Section titled “Hand-crafted features for link prediction”As we have already seen in Chapter 5, Supervised Graph Learning, shallow embedding methods represent a simple yet powerful approach for dealing with supervised tasks. Basically, for each input edge, we will compute a set of metrics that will be given as input to a classifier.
In this example, for each input edge represented as a pair of nodes (u,v), four metrics will be considered, namely:
- Shortest path: The length of the shortest path between u and v. If u and v are directly connected through an edge, this edge will be removed before computing the shortest path. The value 0 will be used if u is not reachable from v.
- Jaccard coefficient: Given a pair of nodes (u,v), it is defined as the intersection over a union of the set of neighbors of u and v. Formally, let be the set of neighbors of the node u and be the set of neighbors of the node v:
- Centrality: The degree centrality computed for the nodes v and u.
- u community: The community ID assigned to the nodes u and v using the Louvain heuristic.
We have written a useful function for computing these metrics using Python and networkx. You can find the implementation in the Python notebook attached to this book.
Let’s compute the features for each edge in the training and test sets:
feat_train = get_hc_features(graph_train, samples_train, labels_train)feat_test = get_hc_features(graph_test, samples_test, labels_test)In the proposed shallow approach, these features will be directly used as input for a Random Forest classifier. We will use its scikit-learn implementation as follows:
from sklearn.ensemble import RandomForestClassifierfrom sklearn import metricsrf = RandomForestClassifier(n_estimators=10)rf.fit(feat_train, labels_train)The above lines automatically instantiate and train a Random Forest classifier using the edge features we have computed before. We are now ready to compute the performance as follows:
y_pred = rf.predict(feat_test)print('Precision:', metrics.precision_score(labels_test, y_pred))print('Recall:', metrics.recall_score(labels_test, y_pred))print('F1-Score:', metrics.f1_score(labels_test, y_pred))The output will be:
Precision: 0.9636952636282395Recall: 0.9777853337866939F1-Score: 0.9706891701828411Surprisingly, the shallow method based on hand-crafted features performs better than the others. This result can be attributed to the high expressiveness of the hand-crafted metrics used in this specific dataset.
Metrics such as the shortest path, Jaccard coefficient, centrality, and community information directly capture structural properties of the graph that are particularly predictive for link prediction tasks. Additionally, the Random Forest classifier used in the shallow method may have better exploited these engineered features compared to the more generalized embeddings generated by node2vec and GraphSAGE. However, it is important to note that this observation is dataset-dependent and may not hold true in all cases. The shallow method relies heavily on the quality of the hand-crafted features, which may not always capture all relevant graph properties for more complex or large-scale datasets. In contrast, methods like node2vec and GraphSAGE are designed to generalize across diverse graph structures by learning feature representations directly from the data. These methods often outperform shallow approaches in scenarios where the graph is too complex for simple metrics to capture all predictive patterns.
Summarizing the results
Section titled “Summarizing the results”In the above examples, we have trained three algorithms in learning, with and without supervision, useful embeddings for link prediction. In the following table, we summarize the results:

Table 7.1: Summary of the results achieved for the link prediction task
| Method | Precision | Recall | F1-Score |
|---|---|---|---|
| Node2Vec | 0.970 | 0.916 | 0.942 |
| GraphSAGE (Featureless) | 0.716 | 0.983 | 0.828 |
| GraphSAGE (Features) | 0.790 | 0.998 | 0.882 |
| Hand-crafted Features | 0.964 | 0.978 | 0.971 |
As shown in Table 7.1, the node2vec-based method is already able to achieve a high level of performance without supervision or per-node information. As mentioned earlier, such high results might be related to the particular structure of the combined ego network. Due to the high sub-modularity of the network (since it is composed of several ego networks), predicting whether two users will be connected or not might be highly related to the way the two candidate nodes are connected inside the network. For example, there might be a systematic situation in which two users, both connected to several users in the same ego network, have a high chance of being connected as well. On the other hand, two users belonging to different ego networks, or very far from each other, are likely to be not connected, making the prediction task easier. This is also confirmed by the high results achieved using the shallow method.
Such a situation might be confusing, instead, for more complicated algorithms like GraphSAGE, especially when node features are involved. For example, two users might share similar interests, making them very similar. However, they might belong to different ego networks, where the corresponding ego users live in two very different parts of the world. So, similar users that in principle should be connected are not. However, it is also possible that such algorithms are predicting something further in the future. Recall that the combined ego network is a timestamp of a particular situation in a given period of time. Who knows how it might have evolved now!
Interpreting machine learning algorithms is probably the most interesting challenge of machine learning itself. For this reason, we should always interpret results with care. Our suggestion is always to dig into the dataset and try to give an explanation of your results.
Finally, it is important to remark that each of the algorithms was not tuned for the purpose of this demonstration. Different results can be obtained by properly tuning each hyperparameter and we highly suggest you try to do it.
Notice that, in this example, we did not apply any particular feature processing method. However, in other scenarios, we may want to perform feature engineering to improve performances. Skewed data may benefit from transformations, and highly correlated features, though not harmful, could be pruned for efficiency. Addressing outliers enhances model robustness, and dimensionality reduction prevents issues with overly high-dimensional data.
Summary
Section titled “Summary”In this chapter, we have seen how machine learning can be useful for solving practical machine learning tasks on social network graphs. More specifically, we have seen how future connections can be predicted on the SNAP Facebook combined ego network.
We reviewed graph analysis concepts and used graph-derived metrics to collect insights into the social graph. Then, we benchmarked several machine learning algorithms on the link prediction task, evaluating their performance and trying to give them an interpretation.
In the next chapter, we will focus on how similar approaches can be used to analyze a corpus of documents, using text analytics and natural language processing.