fn pagerankscipy( adjmatrix: Array2<f64>, alpha: f64, personalization:…
- User
fn pagerank_scipy( adj_matrix: Array2, alpha: f64, personalization: Option<Array1>, max_iter: usize, tol: f64, ) -> Result<(FxHashMap<usize, f64>, usize), &'static str> { let n = adj_matrix.shape()[0];
codeif n == 0 { return Ok((FxHashMap::default(), 0)); } let mut a = adj_matrix; let s = a.sum_axis(Axis(1)); let inv_s = &s.mapv(|x| if x != 0.0 { 1.0 / x } else { 0.0 }); let q = Array::from_diag(&inv_s); let sparse_q = CsMat::csr_from_dense(q.view(), 0.0); a = a.dot(&sparse_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 is_dangling = s.mapv(|x| x == 0.0); let dangling_weights = alpha * &p; let mut iterations = 0; for _ in 0..max_iter { iterations += 1; xlast.assign(&x); let dangling_sum = (&x * &is_dangling.mapv(|b| b as usize as f64)).sum(); x = alpha * (x.dot(&a) + dangling_sum * &dangling_weights) + (1.0 - alpha) * &p; let err = (&x - &xlast).mapv(f64::abs).sum(); 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
The issue with this PageRank algorithm lies in the way the dangling nodes are handled, specifically in the calculation of the dangling weights. Dangling nodes are nodes with no outgoing edges, and in the PageRank algorithm, they should distribute their rank equally to all other nodes (or according to the personalization vector).
In the provided code, the dangling weights are calculated as:
rustlet dangling_weights = alpha * &p;Later in the iteration step, the dangling contribution is incorporated as:
rustx = alpha * (x.dot(&a) + dangling_sum * &dangling_weights) + (1.0 - alpha) * &p;