'''
@author: Administrator
'''
def inNodes(node,edges):
ins=[]
for edge in edges:
if edge[1]==node:
ins.append(edge[0])
return ins
def update_simRank(node1,node2,edges,simRank):
if node1==node2:
simRank[(node1,node2)]=1
simRank[(node2,node1)]=1
return simRank
ins_1=inNodes(node1,edges)
ins_2=inNodes(node2,edges)
if len(ins_1)==0 or len(ins_2)==0:
simRank[(node1,node2)]=0
simRank[(node2,node1)]=0
return simRank
sum_sim=0
for i in ins_1:
for j in ins_2:
if (i,j) in simRank:
sum_sim+=simRank[(i,j)]
elif i==j:
sum_sim+=1
else:
sum_sim+=0
C=0.8
sim_ab=C*sum_sim/(len(ins_1)*len(ins_2))
simRank[(node1,node2)]=sim_ab
simRank[(node2,node1)]=sim_ab
return simRank
if __name__ == '__main__':
nodes=["Univ","ProfA","StudentA","ProfB","StudentB"]
edges=[];
edges.append(["Univ","ProfA"])
edges.append(["Univ","ProfB"])
edges.append(["ProfA","StudentA"])
edges.append(["StudentA","Univ"])
edges.append(["ProfB","StudentB"])
edges.append(["StudentB","ProfB"])
simRank={}
i_total=20
for i in range(i_total):
for node1 in range(len(nodes)):
for node2 in range(node1,len(nodes)):
simRank=update_simRank(nodes[node1],nodes[node2],edges,simRank)
print(simRank)
结果是:
{('Univ', 'Univ'): 1, ('Univ', 'ProfA'): 0.0, ('ProfA', 'Univ'): 0.0, ('Univ', 'StudentA'): 0.0, ('StudentA', 'Univ'): 0.0, ('Univ', 'ProfB'): 0.0, ('ProfB', 'Univ'): 0.0, ('Univ', 'StudentB'): 0.0, ('StudentB', 'Univ'): 0.0, ('ProfA', 'ProfA'): 1, ('ProfA', 'StudentA'): 0.0, ('StudentA', 'ProfA'): 0.0, ('ProfA', 'ProfB'): 0.4, ('ProfB', 'ProfA'): 0.4, ('ProfA', 'StudentB'): 0.0, ('StudentB', 'ProfA'): 0.0, ('StudentA', 'StudentA'): 1, ('StudentA', 'ProfB'): 0.0, ('ProfB', 'StudentA'): 0.0, ('StudentA', 'StudentB'): 0.32000000000000006, ('StudentB', 'StudentA'): 0.32000000000000006, ('ProfB', 'ProfB'): 1, ('ProfB', 'StudentB'): 0.0, ('StudentB', 'ProfB'): 0.0, ('StudentB', 'StudentB'): 1}