if n == 0 {
return Ok((FxHashMap::default(), 0));
}
let mut s = adj_matrix.sum_axis(Axis(1));
let mut is_dangling = s.mapv(|x| x == 0.0);
for i in 0..n {
if is_dangling[i] {
if let Some(ref pers) = personalization {
adj_matrix.row_mut(i).assign(&(pers / pers.sum()));
} else {
adj_matrix.row_mut(i).fill(1.0 / (n as f64));
}
}
}
s = adj_matrix.sum_axis(Axis(1));
is_dangling = s.mapv(|x| x == 0.0);
let inv_s = s.mapv(|x| if x != 0.0 { 1.0 / x } else { 0.0 });
let q = Array::from_diag(&inv_s);
adj_matrix = adj_matrix.dot(&q);
let mut x = Array::from_elem(n, 1.0 / (n as f64));
let mut xlast = x.clone();
let p = match personalization {
Some(pers) => {
let pers_sum = pers.sum();
if pers_sum == 0.0 {
return Err("Personalization vector sum is zero.");
}
pers / pers_sum
}
None => Array::from_elem(n, 1.0 / (n as f64)),
};
let mut iterations = 0;
for _ in 0..max_iter {
tracing::trace!("iteration: {}", iterations);
iterations += 1;
xlast.assign(&x);
x = alpha * x.dot(&adj_matrix) + (1.0 - alpha) * &p;
let err = (&x - &xlast).mapv(f64::abs).sum();
tracing::trace!("err: {}", err);
if err < (n as f64) * tol {
let sum_scores: f64 = x.sum();
let x_normalized = x.mapv(|v| v / sum_scores);
let result: FxHashMap<usize, f64> = x_normalized
.as_slice()
.unwrap()
.par_iter()
.enumerate()
.map(|(index, &value)| (index, value))
.collect();
return Ok((result, iterations));
}
}
Err("PowerIterationFailedConvergence: Power iteration failed to converge in the specified number of iterations.")
Assistant
}
There is still an issue with dangling nodes where it is apparent that the highest node isn't objectively better than the second highest node
The issue you're encountering with the PageRank implementation—specifically, the handling of dangling nodes and the resulting PageRank scores—stems from the way the adjacency matrix is being processed in your code. The core problem lies in the normalization of the adjacency matrix and the axes over which sums are computed. Let's break down the issue and provide a solution.
Understanding the Adjacency Matrix and PageRank
In the PageRank algorithm, the adjacency matrix should be used to create a transition probability matrix, where each entry represents the probability of transitioning from one node to another. The key aspects are:
Outgoing Links: The probability of transitioning from node j to node i depends on the number of outgoing links from node j.
Column-Stochastic Matrix: The transition matrix should be column-stochastic, meaning the sum of the probabilities in each column should be 1 (or adjusted appropriately for dangling nodes).
The Issue with Axis Summation
In your current code, you are summing over rows instead of columns. This means you're normalizing the rows of the adjacency matrix, which is incorrect for PageRank computations.
rust
// Incorrect: Summing over rows (Axis(1))
let mut s = adj_matrix.sum_axis(Axis(1));
// ...
adj_matrix = adj_matrix.dot(&q);
This leads to the improper handling of dangling nodes and incorrect transition probabilities, resulting in an inaccurate PageRank vector where the highest-ranked node isn't objectively better than others.
Correcting the Axis Summation
To fix this issue, you need to sum over columns (Axis(0)) and normalize the adjacency matrix accordingly. Here's how you can modify your code:
Step 1: Sum Over Columns
Change the axis in the sum_axis function from Axis(1) to Axis(0).
rust
// Correct: Summing over columns (Axis(0))
let mut s = adj_matrix.sum_axis(Axis(0));
let mut is_dangling = s.mapv(|x| x == 0.0);
Step 2: Handle Dangling Nodes Properly
When you identify dangling nodes (nodes with no outgoing links), you need to adjust the columns of the adjacency matrix, not the rows.
rust
for j in 0..n {
if is_dangling[j] {
if let Some(ref pers) = personalization {
adj_matrix.column_mut(j).assign(&(pers / pers.sum()));
} else {
adj_matrix.column_mut(j).fill(1.0 / (n as f64));
}
}
}
Step 3: Recompute the Column Sums
After adjusting for dangling nodes, recompute the sums over columns.
rust
// Recompute the sums over columns after adjusting for dangling nodes
s = adj_matrix.sum_axis(Axis(0));
Step 4: Normalize the Adjacency Matrix Columns
Create the inverse of the column sums and normalize the adjacency matrix to make it column-stochastic.
rust
let inv_s = s.mapv(|x| if x != 0.0 { 1.0 / x } else { 0.0 });
let q = Array::from_diag(&inv_s);
adj_matrix = q.dot(&adj_matrix);
Step 5: Update the Iterative Computation
Ensure that the iteration multiplies the PageRank vector from the left side, as we are working with a column-stochastic matrix.
rust
// Initial PageRank vector
let mut x = Array::from_elem(n, 1.0 / (n as f64));
// Iterative computation
x = alpha * adj_matrix.dot(&x) + (1.0 - alpha) * &p;
Revised Code Snippet
Here’s how the corrected portion of your code might look:
rust
let n = adj_matrix.shape()[0];
if n == 0 {
return Ok((FxHashMap::default(), 0));
}
// Sum over columns to get the out-degree of each node
let mut s = adj_matrix.sum_axis(Axis(0));
let mut is_dangling = s.mapv(|x| x == 0.0);
// Adjust columns for dangling nodes
for j in 0..n {
if is_dangling[j] {
if let Some(ref pers) = personalization {
adj_matrix.column_mut(j).assign(&(pers / pers.sum()));
} else {
adj_matrix.column_mut(j).fill(1.0 / (n as f64));
}
}
}
// Recompute column sums after adjustments
s = adj_matrix.sum_axis(Axis(0));
// Normalize adjacency matrix to make it column-stochastic
let inv_s = s.mapv(|x| if x != 0.0 { 1.0 / x } else { 0.0 });
let q = Array::from_diag(&inv_s);
adj_matrix = q.dot(&adj_matrix);
// Initialize PageRank vector
let mut x = Array::from_elem(n, 1.0 / (n as f64));
// Personalized vector
let p = match personalization {
Some(pers) => {
let pers_sum = pers.sum();
if pers_sum == 0.0 {
return Err("Personalization vector sum is zero.");
}
pers / pers_sum
}
None => Array::from_elem(n, 1.0 / (n as f64)),
};
let mut iterations = 0;
for _ in 0..max_iter {
iterations += 1;
let xlast = x.clone();
x = alpha * adj_matrix.dot(&x) + (1.0 - alpha) * &p;
let err = (&x - &xlast).mapv(f64::abs).sum();
if err < (n as f64) * tol {
// Normalize the PageRank vector
let sum_scores: f64 = x.sum();
let x_normalized = x.mapv(|v| v / sum_scores);
let result: FxHashMap<usize, f64> = x_normalized
.iter()
.enumerate()
.map(|(index, &value)| (index, value))
.collect();
return Ok((result, iterations));
}
}
Explanation
Summing Over Columns: We now sum over Axis(0) to get the out-degree of each node, which is essential for normalizing the columns.
Adjusting Dangling Nodes: We adjust the columns corresponding to dangling nodes, distributing their "rank" uniformly (or according to the personalization vector) to all nodes.
Normalizing the Columns: By creating a diagonal matrix q with inv_s, we normalize the columns so that each column sums to 1, resulting in a proper transition probability matrix.
Iterative Computation: We update the PageRank vector x using left multiplication with the adjacency matrix, as we're working with a column-stochastic matrix.
Verifying the Results
After making these changes, your PageRank implementation should correctly handle dangling nodes, and the highest-ranked node should objectively have a higher PageRank score compared to others, reflecting its relative importance in the network.
Additional Tips
Personalization Vector: Ensure that your personalization vector (if used) is correctly normalized and reflects the intended bias in the PageRank computation.
Convergence Check: The convergence criterion should be sufficiently tight (controlled by tol) to allow the algorithm to reach a stable solution.
Testing: Test your implementation on known graphs where the PageRank values are already established to verify correctness.
Conclusion
By adjusting the axis over which you sum and normalize the adjacency matrix, you align your implementation with the standard PageRank algorithm. This should resolve the issue with dangling nodes and produce meaningful PageRank scores that reflect the true importance of each node in the network.
Please let me know if you need further assistance or clarification on any of these steps!