本文是李航老师的《统计学习方法》一书的代码复现。作者:黄海广 备注:代码都可以在github中下载。
在实际应用中许多数据都以图(graph)的形式存在,比如,互联网、社交网络都可以看作是一个图。图数据上的机器学习具有理论与应用上的重要意义。pageRank算法是图的链接分析 (link analysis)的代表性算法,属于图数据上的无监督学习方法。
pageRank算法最初作为互联网网页重要度的计算方法,1996年由page和Brin提出,并用于谷歌搜索引擎的网页排序。事实上,pageRank可以定义在任意有向图上,后来被应用到社会影响力分析、文本摘要等多个问题。
pageRank算法的基本想法是在有向图上定义一个随机游走模型,即一阶马尔可夫链,描述随机游走者沿着有向图随机访问各个结点的行为。在一定条件下,极限情况访问每个结点的概率收敛到平稳分布, 这时各个结点的平稳概率值就是其 pageRank值,表示结点的重要度。 pageRank是递归定义的,pageRank的计算可以通过迭代算法进行。
#https://gist.github.com/diogojc/1338222/84d767a68da711a154778fb1d00e772d65322187
import numpy as np
from scipy.sparse import csc_matrix
def pageRank(G, s=.85, maxerr=.0001):
"""
Computes the pagerank for each of the n states
Parameters
----------
G: matrix representing state transitions
Gij is a binary value representing a transition from state i to j.
s: probability of following a transition. 1-s probability of teleporting
to another state.
maxerr: if the sum of pageranks between iterations is bellow this we will
have converged.
"""
n = G.shape[0]
# transform G into markov matrix A
A = csc_matrix(G, dtype=np.float)
rsums = np.array(A.sum(1))[:, 0]
ri, ci = A.nonzero()
A.data /= rsums[ri]
# bool array of sink states
sink = rsums == 0
# Compute pagerank r until we converge
ro, r = np.zeros(n), np.ones(n)
while np.sum(np.abs(r - ro)) > maxerr:
ro = r.copy()
# calculate each pagerank at a time
for i in range(0, n):
# inlinks of state i
Ai = np.array(A[:, i].todense())[:, 0]
# account for sink states
Di = sink / float(n)
# account for teleportation to state i
Ei = np.ones(n) / float(n)
r[i] = ro.dot(Ai * s + Di * s + Ei * (1 - s))
# return normalized pagerank
return r / float(sum(r))
# Example extracted from 'Introduction to Information Retrieval'
G = np.array([[0,0,1,0,0,0,0],
[0,1,1,0,0,0,0],
[1,0,1,1,0,0,0],
[0,0,0,1,1,0,0],
[0,0,0,0,0,0,1],
[0,0,0,0,0,1,1],
[0,0,0,1,1,0,1]])
print(pageRank(G,s=.86))
[0.12727557 0.03616954 0.12221594 0.22608452 0.28934412 0.03616954
0.16274076]
本章代码来源:https://github.com/hktxt/Learn-Statistical-Learning-Method
https://github.com/fengdu78/lihang-code
[1] 《统计学习方法》: https://baike.baidu.com/item/统计学习方法/10430179
[2] 黄海广: https://github.com/fengdu78
[3] github: https://github.com/fengdu78/lihang-code
[4] wzyonggege: https://github.com/wzyonggege/statistical-learning-method
[5] WenDesi: https://github.com/WenDesi/lihang_book_algorithm
[6] 火烫火烫的: https://blog.csdn.net/tudaodiaozhale
[7] hktxt: https://github.com/hktxt/Learn-Statistical-Learning-Method
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有