PageRank算法Python实现
生活随笔
收集整理的這篇文章主要介紹了
PageRank算法Python实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
def getGm(A):'''功能:求狀態轉移概率矩陣Gm@A:網頁鏈接圖的鄰接矩陣'''Gm = []for i in range(len(A)):cnt = 0for j in range(len(A[i])):if A[i][j] != 0:cnt += 1tran_prob = 1 / cnt # 轉移概率Gm_tmp = []for j in range(len(A[i])):Gm_tmp.append(tran_prob * A[i][j])Gm.append(Gm_tmp)Gm = np.transpose(Gm)return Gm
def getBaseLev(N):'''功能:計算網頁所獲得的基本級別(1-P)*e/n@N:網頁總個數'''P = 0.85e = np.ones(N)R = [[(1 - P) * i * 1 / N] for i in e]return R
def getPR(P, Gm, R, PR):'''功能:獲取PR值@P:加權系數,通常取 0.85 左右,按照超鏈接進行瀏覽的概率@Gm:狀態轉移概率矩陣@R:網頁所獲得的基本級別@PR:每個網頁節點的PageRank值'''# 狀態轉移概率矩陣Gm與PR值相乘矩陣相乘Gm_PR = np.dot(Gm, PR)# 矩陣乘以常數PP_Gm_PR = P * Gm_PR# 矩陣相加new_PR = P_Gm_PR + R # PR=P*Gm'PR+(1-d)*e/n PageRank算法的核心return new_PR
def res_vis(A, PR):'''將計算出來的值進行可視化展示@A:網頁鏈接圖的鄰接矩陣@PR:每個網頁節點最終的PageRank值'''# G=nx.Graph()構造的是無向圖, G=nx.DiGraph()構造的是有向圖# 初始化有向圖,節點數為7,edge(邊)被創造的隨機概率all_edges = []for i in range(7):for j in range(len(A)):if A[i][j] == 1:all_edges.append([i + 1, j + 1])# (1)初始化有向圖G = nx.DiGraph()# (2)添加節點G.add_nodes_from(range(1, len(A)))# (3)添加有向邊G.add_edges_from(all_edges)# (4)添加PR值pr = {}for i in range(len(PR)):pr[i + 1] = PR[i][0]# (5)畫圖layout = nx.spring_layout(G)plt.figure(1)nx.draw(G, pos=layout, node_size=[x * 6000 for x in pr.values()],node_color='m', with_labels=True)plt.show()
def main():# 初始化參數N = 7 # 網頁個數P = 0.85 # 一個加權系數,通常取 0.85 左右,按照超鏈接進行瀏覽的概率# 網頁鏈接圖的鄰接矩陣,每一列表示一個網頁的出度A = np.array([[0, 1, 1, 0, 1, 1, 0],[1, 0, 1, 1, 0, 0, 0],[1, 0, 0, 1, 1, 0, 0],[1, 0, 0, 0, 1, 0, 0],[1, 0, 0, 1, 0, 1, 1],[0, 0, 0, 0, 1, 0, 0],[1, 0, 0, 0, 0, 0, 0]])A = np.transpose(A) # 轉置# 初始化PR值為0new_PR = []for i in range(N):new_PR.append([0])count = 0 # 迭代計數器while True:PR = new_PRR = getBaseLev(N)Gm = getGm(A)new_PR = getPR(P, Gm, R, PR)count = count + 1print("第 %s 輪迭代" % count)print(str(round(new_PR[0][0], 5))+ "\t" + str(round(new_PR[1][0], 5))+ "\t" + str(round(new_PR[2][0], 5))+ "\t" + str(round(new_PR[3][0], 5))+ "\t" + str(round(new_PR[4][0], 5))+ "\t" + str(round(new_PR[5][0], 5))+ "\t" + str(round(new_PR[6][0], 5)))# 設置迭代條件if (round(PR[0][0], 5) == round(new_PR[0][0], 5)and round(PR[1][0], 5) == round(new_PR[1][0], 5)and round(PR[2][0], 5) == round(new_PR[2][0], 5)and round(PR[3][0], 5) == round(new_PR[3][0], 5)and round(PR[4][0], 5) == round(new_PR[4][0], 5)and round(PR[5][0], 5) == round(new_PR[5][0], 5)and round(PR[6][0], 5) == round(new_PR[6][0], 5)):breakprint("-------------------")print("PageRank值已計算完成")res_vis(A, new_PR)
if __name__ == '__main__':main()
總結
以上是生活随笔為你收集整理的PageRank算法Python实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 淘宝服饰精品案例分析
- 下一篇: pypinyin--python 汉字与