Sure! Let's explore the differences in PageRank distributions between the Erdős–Rényi (ER) model and the Barabási–Albert (BA) model using Python. We'll:
- Generate both types of graphs with the same number of nodes and edges.
- Compute the PageRank for each graph.
- Compare the distributions of PageRank values by calculating statistical moments.
- Visualize the graphs and the PageRank distributions.
We'll use the following Python libraries:
networkx for creating and handling graphs.
matplotlib and seaborn for plotting.
numpy and pandas for numerical operations and data handling.
Let's start by installing any necessary libraries. If you haven't installed them yet, you can do so using pip:
pip install networkx matplotlib seaborn numpy pandas
Now, let's dive into the code.
import networkx as nx
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import pandas as pd
# For better plot aesthetics
sns.set(style="whitegrid")
# 1. Define the parameters for the graphs
num_nodes = 1000 # Number of nodes in each graph
# For ER graph, the probability p is chosen such that the expected number of edges matches BA
# BA graph has m(t) edges added per new node; total edges = m * (n - m0)
# For simplicity, let's assume m0 = m = 5 (m0 is the initial number of nodes)
m0 = m = 5
ba_total_edges = m * (num_nodes - m0)
# ER graph has total possible edges = n*(n-1)/2
# To find probability p such that expected edges = ba_total_edges
er_p = (2 * ba_total_edges) / (num_nodes * (num_nodes - 1))
print(f"Number of nodes: {num_nodes}")
print(f"Number of edges for BA graph: {ba_total_edges}")
print(f"Edge creation probability for ER graph: {er_p:.6f}")
# 2. Generate the Erdős–Rényi (ER) graph
er_graph = nx.erdos_renyi_graph(n=num_nodes, p=er_p, seed=42)
# Verify the number of edges (since ER is random, actual edges may vary)
print(f"ER Graph has {er_graph.number_of_edges()} edges.")
# 3. Generate the Barabási–Albert (BA) graph
ba_graph = nx.barabasi_albert_graph(n=num_nodes, m=m, seed=42)
# Verify the number of edges
print(f"BA Graph has {ba_graph.number_of_edges()} edges.")
# 4. Compute PageRank for both graphs
# PageRank returns a dictionary where keys are nodes and values are PageRank scores
print("\nComputing PageRank...")
er_pagerank = nx.pagerank(er_graph, alpha=0.85)
ba_pagerank = nx.pagerank(ba_graph, alpha=0.85)
print("PageRank computation completed.")
# 5. Extract PageRank values and convert to numpy arrays for analysis
er_pagerank_values = np.array(list(er_pagerank.values()))
ba_pagerank_values = np.array(list(ba_pagerank.values()))
# 6. Calculate statistical moments
def compute_statistics(pagerank_values):
mean = np.mean(pagerank_values)
variance = np.var(pagerank_values)
skewness = pd.Series(pagerank_values).skew()
kurtosis = pd.Series(pagerank_values).kurt()
return mean, variance, skewness, kurtosis
er_stats = compute_statistics(er_pagerank_values)
ba_stats = compute_statistics(ba_pagerank_values)
# Display the statistics
stats_df = pd.DataFrame({
'Statistic': ['Mean', 'Variance', 'Skewness', 'Kurtosis'],
'ER Graph': er_stats,
'BA Graph': ba_stats
})
print("\nStatistical Moments of PageRank:")
print(stats_df)
# 7. Visualize the PageRank distributions
plt.figure(figsize=(14, 6))
# ER PageRank Distribution
plt.subplot(1, 2, 1)
sns.histplot(er_pagerank_values, bins=50, color='skyblue', kde=True)
plt.title('PageRank Distribution - Erdős–Rényi Graph')
plt.xlabel('PageRank')
plt.ylabel('Frequency')
# BA PageRank Distribution
plt.subplot(1, 2, 2)
sns.histplot(ba_pagerank_values, bins=50, color='salmon', kde=True)
plt.title('PageRank Distribution - Barabási–Albert Graph')
plt.xlabel('PageRank')
plt.ylabel('Frequency')
plt.tight_layout()
plt.show()
# 8. Visualize the graphs with node sizes based on PageRank
# Due to the size of the graphs (1000 nodes), direct plotting can be cluttered.
# We'll plot smaller subgraphs or use a spring layout with node sizes scaled by PageRank.
# For demonstration, let's visualize a sample subgraph of each
sample_size = 100 # Number of nodes to visualize
# Sample nodes with highest PageRank for better visibility
er_top_nodes = er_pagerank_values.argsort()[-sample_size:][::-1]
ba_top_nodes = ba_pagerank_values.argsort()[-sample_size:][::-1]
er_subgraph = er_graph.subgraph(er_top_nodes)
ba_subgraph = ba_graph.subgraph(ba_top_nodes)
# Function to plot subgraphs
def plot_subgraph(graph, pagerank, title):
plt.figure(figsize=(8, 6))
pos = nx.spring_layout(graph, seed=42) # Positions for all nodes
# Scale node sizes by PageRank
sizes = [pagerank[node] * 10000 for node in graph.nodes()]
# Draw nodes and edges
nx.draw_networkx_nodes(graph, pos, node_size=sizes, node_color='blue', alpha=0.6)
nx.draw_networkx_edges(graph, pos, alpha=0.4)
plt.title(title)
plt.axis('off')
plt.show()
# Plot ER subgraph
plot_subgraph(er_subgraph, er_pagerank, 'ER Graph Subgraph (Top PageRank Nodes)')
# Plot BA subgraph
plot_subgraph(ba_subgraph, ba_pagerank, 'BA Graph Subgraph (Top PageRank Nodes)')
# 9. Discussion:
# The ER graph is a random graph where each edge is equally likely, leading to a more uniform PageRank distribution.
# The BA graph follows a power-law degree distribution, resulting in a few nodes with very high PageRank and many with low PageRank.
Explanation of the Code
-
Import Libraries: We start by importing the necessary libraries for graph creation, numerical operations, and plotting.
-
Define Graph Parameters:
- We set the number of nodes (
num_nodes) to 1000.
- For the ER graph, we calculate the probability
p to ensure that the expected number of edges matches that of the BA graph. The BA model adds m edges for each new node. We calculate the total edges for the BA graph and then derive p for the ER graph to have a similar number of edges.
-
Generate Graphs:
- Erdős–Rényi (ER) Graph: Created using
nx.erdos_renyi_graph with the calculated probability p.
- Barabási–Albert (BA) Graph: Created using
nx.barabasi_albert_graph with parameter m (number of edges to attach from a new node).
-
Compute PageRank:
- We compute the PageRank for both graphs using NetworkX's
pagerank function with the damping factor alpha=0.85 (a common choice).
-
Extract and Analyze PageRank Values:
- The PageRank scores are extracted into NumPy arrays for easier analysis.
- We define a function
compute_statistics to calculate the mean, variance, skewness, and kurtosis of the PageRank distributions.
- These statistics help us understand the shape and spread of the PageRank distributions.
-
Visualize PageRank Distributions:
- We use histograms with Kernel Density Estimates (KDE) to visualize how PageRank values are distributed in both graphs.
- Typically, the ER graph should show a more uniform distribution, while the BA graph should exhibit a heavy tail, indicating a few nodes with very high PageRank.
-
Visualize Graph Structures:
- Due to the large size of the graphs (1000 nodes), we visualize subgraphs consisting of the top 100 nodes with the highest PageRank.
- Node sizes in the visualization are scaled based on their PageRank values, highlighting the most influential nodes.
-
Discussion:
- Finally, we provide a brief discussion on the observed differences. The ER graph's uniform edge distribution leads to a more uniform PageRank distribution.
Expected Output
When you run the above code, you should observe:
-
Printed Information:
- The number of nodes, edges in both graphs, and the edge creation probability for the ER graph.
- Confirmation of PageRank computation.
- A table displaying the mean, variance, skewness, and kurtosis of the PageRank distributions for both graphs.
-
Plots:
- Two histograms showing the PageRank distributions for ER and BA graphs.
- Two visualizations of subgraphs highlighting the top PageRank nodes in both ER and BA graphs.
-
Observations:
- The ER graph's PageRank distribution should be relatively flat, indicating a uniform distribution.
- The BA graph's PageRank distribution should have a long tail, highlighting a few highly influential nodes.
- The subgraph visualizations for the BA graph will show a few large nodes with many connections, whereas the ER graph's subgraph will appear more uniform.
This comparative analysis helps in understanding how different network generation models influence the importance and influence distribution of nodes within the graph.