fork download
  1. import numpy as np
  2.  
  3. # 参数设置
  4. p = 0.85 # 继续浏览当前网页的概率
  5. a = np.array([[1, 0, 0, 0],
  6. [0, 0, 0, 1],
  7. [0, 0, 0, 1],
  8. [0, 1, 0, 0]], dtype=float)
  9.  
  10. length = a.shape[1] # 网页数量
  11. b = np.transpose(a).copy() # 转置并复制以避免修改原始矩阵
  12. m = np.zeros((a.shape), dtype=float)
  13.  
  14. # 构造转移矩阵(修正 Dead Ends)
  15. for j in range(b.shape[0]):
  16. if b[j].sum() == 0: # 处理 Dead Ends
  17. b[j] = np.ones(length) / length # 修正为均匀分布
  18. for i in range(b.shape[1]):
  19. m[i][j] = b[j][i] / b[j].sum() # 使用修正后的 b[j][i]
  20.  
  21. # 初始化 PageRank 值
  22. v = np.ones(length).reshape(-1, 1) / length
  23. ee = np.ones(length).reshape(-1, 1) / length
  24.  
  25. # 迭代计算 PageRank 值
  26. for _ in range(100):
  27. v = p * np.dot(m, v) + (1 - p) * ee
  28.  
  29. print("修正后的 PageRank 值:")
  30. print(v)
Success #stdin #stdout 0.07s 23424KB
stdin
Standard input is empty
stdout
修正后的 PageRank 值:
[[0.47534884]
 [0.15906977]
 [0.15906977]
 [0.20651163]]