我們用pagerank來查看,各個點的影響力嚣鄙,以及用nexworkx中的graph來展示其關系吻贿。
如圖ABCD代表著4個網(wǎng)頁,其中箭頭指向表示哑子,從某網(wǎng)頁跳轉到另一個網(wǎng)頁舅列,那么我們來計算一下,這4個網(wǎng)頁的影響力是多少吧卧蜓!
pagerank算法原理就是:一個網(wǎng)頁的影響力 = 所有入鏈集合的頁面的加權影響力之和帐要。
如何計算,公式自己去網(wǎng)絡上查找弥奸,我們用代碼演示一遍榨惠。
import matplotlib.pyplot as plt
import networkx as nx
G = nx.DiGraph()
# 有向圖之間邊的關系
edges = [("A", "B"), ("A", "C"), ("A", "D"), ("B", "A"), ("B", "D"), ("C", "A"), ("D", "B"), ("D", "C")]
for edge in edges:
G.add_edge(edge[0], edge[1])
pagerank_list = nx.pagerank(G, alpha=1)#alpha為阻尼因子,alpha=0.85表示跳轉率為15%
print("pagerank 值是:", pagerank_list)
nx.set_node_attributes(G,values=pagerank_list,name='pagerank_list')
# 繪制圓環(huán)圖像
positions=nx.circular_layout(G)
#繪制反射圖像
# positions=nx.spring_layout(G)
# 繪制節(jié)點
nx.draw_networkx_nodes(G, positions, alpha=0.4)
# 繪制邊
nx.draw_networkx_edges(G, positions, alpha=0.2)
# 繪制節(jié)點的 label
nx.draw_networkx_labels(G, positions, font_size=10)
plt.show()
得到的結果:
點越是大盛霎,影響力越大赠橙,當數(shù)據(jù)夠大時會顯現(xiàn)出來。
pagerank 值是: {'A': 0.33333396911621094, 'B': 0.22222201029459634, 'C': 0.22222201029459634, 'D': 0.22222201029459634}
接下來我們看下如何利用pagerank和graph來展示希拉里的郵件愤炸。
一張圖顯示步驟:
1期揪、提取收件名和發(fā)件名
首先我們需要將所有的文件提取出來甚脉,轉化為字典模式怎诫,id對應姓名和真實身份笆豁,最后提取的emails.MetadataTo和emails.MetadataFrom要對應其真實身份五慈。
import pandas as pd
import numpy as np
from collections import defaultdict
emails = pd.read_csv("E:/數(shù)據(jù)學習網(wǎng)站/PageRank-master/input/Emails.csv")
file = pd.read_csv("E:/數(shù)據(jù)學習網(wǎng)站/PageRank-master/input/Aliases.csv")
aliases={}
for index,row in file.iterrows():
aliases[row['Alias']]=row['PersonId']
# print(aliases)
file = pd.read_csv("E:/數(shù)據(jù)學習網(wǎng)站/PageRank-master/input/Persons.csv")
persons={}
for index,row in file.iterrows():
persons[row['Id']]=row['Name']
# 單詞間的轉換
def unify_name(name):
#大小寫沼头,刪除標點和后綴
name =str(name).lower()
name=name.replace(",","").split("@")[0]
#通過key進行名字轉化优构,提取aliases名字對應的唯一身份豹绪,中間通過相同keys連接坛怪。
#如果名字再aliases的keys中所對應的的name一樣墅拭,那么返回persons中aliases榨馁,name的keys,所對應的name帜矾。返回name.
if name in aliases.keys():
return persons[aliases[name]]
return name
#提取收件和發(fā)件名翼虫,apply()代表執(zhí)行函數(shù),用前面的文字代入?yún)?shù)
emails.MetadataTo=emails.MetadataTo.apply(unify_name)
emails.MetadataFrom=emails.MetadataFrom.apply(unify_name)
2屡萤、圖像的準備函數(shù)
利用nexworkx畫圖:邊珍剑,點和標簽的大小,圖像可是化
#spring_layout為放射性圖像
#circular_layout為環(huán)形圖像
def show_graph(graph,layout='spring_layout'):
if layout=="circular_layout":
position=nx.circular_layout(graph)
else:
position=nx.spring_layout(graph)
#node點死陆,edge為邊招拙,lable為標簽
#nodesize點大小設置唧瘾,edgesize大小設置
nodesize=[x['pagerank']*20000 for v,x in graph.node(data=True)]
edgesize=[np.sqrt(e[2]['weight']) for e in graph.edges(data=True)]
#開始畫邊點和標簽
nx.draw_networkx_nodes(graph,position,node_size=nodesize,alpha=0.4)
nx.draw_networkx_edges(graph,position,edge_size=edgesize,alpha=0.2)
nx.draw_networkx_labels(graph,position,font_size=10)
plt.show()
3、權重的設置與遍歷
設置dges_weights
1别凤、用for遍歷emails.MetadataTo,emails.MetadataFrom饰序,得到temp名字('a','b')
2、將用if not in條件句规哪,將temp導入edges_weights_temp成為defaultdict(<class 'list'>, {('a', 'b'): 1,('c','d'),2……}將所有temp生存隨機字典求豫。
3、將字典的items,dict_items([(('Jake Sullivan', 'Hillary Clinton'), 815),……诉稍,利用[key[0],key[1],val轉化為[('Jake Sullivan', 'Hillary Clinton', 815)……list模式
dges_weights_temp=defaultdict()
for row in zip(emails.MetadataTo,emails.MetadataFrom,emails.RawText):
temp=(row[0],row[1])
if temp not in edges_weights_temp:
edges_weights_temp[temp]=1
else:
edges_weights_temp[temp]=edges_weights_temp[temp]+1
edges_weight=[(key[0],key[1],val) for key,val in edges_weights_temp.items()]
4蝠嘉、最后利用pagerank和graph設置
先用graph=nx.DiGraph(),再用add代入權重
接著代入nx.pagerank
用nx.set設置參數(shù)
運行畫圖函數(shù)
graph=nx.DiGraph()
graph.add_weighted_edges_from(edges_weight)
pagerank=nx.pagerank(graph)
nx.set_node_attributes(graph,name='pagerank',values=pagerank)
show_graph(graph)
數(shù)據(jù)資料:鏈接:https://pan.baidu.com/s/14edTkp4TH9EtkWt5KYhrrg
提取碼:ui5t
復制這段內容后打開百度網(wǎng)盤手機App杯巨,操作更方便哦蚤告!
最后是完整代碼:
import pandas as pd
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
from collections import defaultdict
emails = pd.read_csv("E:/數(shù)據(jù)學習網(wǎng)站/PageRank-master/input/Emails.csv")
file = pd.read_csv("E:/數(shù)據(jù)學習網(wǎng)站/PageRank-master/input/Aliases.csv")
aliases={}
for index,row in file.iterrows():
aliases[row['Alias']]=row['PersonId']
# print(aliases)
file = pd.read_csv("E:/數(shù)據(jù)學習網(wǎng)站/PageRank-master/input/Persons.csv")
persons={}
for index,row in file.iterrows():
persons[row['Id']]=row['Name']
# 單詞間的轉換
def unify_name(name):
name =str(name).lower()
name=name.replace(",","").split("@")[0]
if name in aliases.keys():
return persons[aliases[name]]
return name
def show_graph(graph,layout='spring_layout'):
if layout=="circular_layout":
position=nx.circular_layout(graph)
else:
position=nx.spring_layout(graph)
nodesize=[x['pagerank']*20000 for v,x in graph.node(data=True)]
edgesize=[np.sqrt(e[2]['weight']) for e in graph.edges(data=True)]
nx.draw_networkx_nodes(graph,position,node_size=nodesize,alpha=0.4)
nx.draw_networkx_edges(graph,position,edge_size=edgesize,alpha=0.2)
nx.draw_networkx_labels(graph,position,font_size=10)
plt.show()
emails.MetadataTo=emails.MetadataTo.apply(unify_name)
emails.MetadataFrom=emails.MetadataFrom.apply(unify_name)
edges_weights_temp=defaultdict()
for row in zip(emails.MetadataTo,emails.MetadataFrom,emails.RawText):
temp=(row[0],row[1])
if temp not in edges_weights_temp:
edges_weights_temp[temp]=1
else:
edges_weights_temp[temp]=edges_weights_temp[temp]+1
edges_weight=[(key[0],key[1],val) for key,val in edges_weights_temp.items()]
graph=nx.DiGraph()
graph.add_weighted_edges_from(edges_weight)
pagerank=nx.pagerank(graph)
nx.set_node_attributes(graph,name='pagerank',values=pagerank)
show_graph(graph)
pagerank_threshold=0.005
small_graph=graph.copy()
for n,p_rank in graph.node(data=True):
if p_rank["pagerank"]<pagerank_threshold:
small_graph.remove_node(n)
show_graph(small_graph,"circular_layout")
結果:美事我們設置閥值服爷,節(jié)點PR值杜恰,將小于0.005的值全部刪除,這樣我們就得到了一張更加清晰的圖仍源。
這位叫nan的伙計箫章,你是干什么的?為什么天天給美國大美女希拉里天天發(fā)郵件镜会?
總結:
1、這里運用到了终抽,nexworkx包戳表,G=nx.DiGraph()來畫圖,用add_weighted_edges_from()添加信息為[('A', 'B', 1),('c','d',2)]格式的數(shù)據(jù)昼伴。
然后匾旭,nex.pagerank()添加權重信息,最后set進G里圃郊。
2价涝、數(shù)據(jù)清洗,占據(jù)了整個代碼中的一半時間持舆。我們要知道如何利用字典的方式把名字統(tǒng)一在一起色瘩,x1=x2—{'a':x1}—{'b':x2},我們要做到輸入A找到B逸寓。
最后居兆,從字典中取出數(shù)據(jù)轉化成[('A', 'B', 1),('c','d',2)]格式。