算法的定义和介绍就不收了,论文中都有,下面直接上代码实现。
def label_rank(A, in_, q, r):
def ismember(a,b):
for i in a:
res = 1
for j in b:
if i not in j:
res = 0
break
if res == 1:
break
return res
Aori = A.copy()
A = A + np.eye(len(A)) #添加自环
# P_0 = A / A.sum(axis=0)
# P_0 = np.array([[0, 0],[0, 0],[0, 0],[0, 0],[0, 0],[0, 0], [0, 0],[0, 0],[0, 0],[0, 1],[0, 0],[1, 0],[0, 0],[0, 0],
# [0, 0],[0, 0],[0, 0],[0, 0],[0, 0],[0, 0],[0, 0],[0, 0],[0, 0],[0, 0],[0, 0],[0, 0],[0, 0],[0, 0],[0, 0],[0, 0],[0, 0],[0, 0],[0, 0],[0, 0]])
P_0 = np.eye(len(A))
P_pre = np.dot(A.T, P_0)
P_pre = P_pre / P_pre.sum(axis=0)
a = 1
COM = {}
count = 0
while a:
#Step1:Propagation
P_now = np.dot(A.T, P_pre)
#Step2:Inflation
P_in = np.power(P_now, in_)
P_now = P_in / (P_in.sum(axis=1)+0.00001).reshape(-1, 1)
#Step3:Cutoff
P_now[P_now < r] = 0
# #Step4:Explicit Conditional Update
# MaNow = np.nanargmax(P_now, axis=1)
# MaPre = np.nanargmax(P_pre, axis=1)
# restart = []
# for i in range(len(A)):
# gain = 0
# Nb = np.nonzero(Aori[i,:])
# MaxI = np.nanargmax(P_now[i, :])
# MaxI = np.nonzero(P_now[i, :] == MaxI)
# MaxNb = MaNow[Nb]
# for k in range(len(Nb)):
# MaxNbID = np.nonzero(P_now[Nb[k], :] == MaxNb[k])
# if ismember(MaxI, MaxNbID):
# gain += 1
# if gain >= q * len(Nb):
# restart.append(i)
# P_now[restart, :] = P_pre[restart, :]
#Step5:Stop Criterion
# if ismember(np.nonzero(P_now[i, :]==MaNow[i]), np.nonzero(P_pre[i, :] == MaPre[i])):
if count == 50:
a = 0
P_pre = P_now
count += 1
R = P_now
# for one in range(len(P_now)):
# print(one+1, P_now[one,:])
return R
以上是LabelRank算法的Python实现版本,目前来说还比较粗糙,还有许多地方需要优化完善,后续版本敬请期待。