Label propagation是基於標傳播的一種社區劃分算法。Label Propagation Algorithm簡稱LPA算法,也能夠是說是一種劃分小團體的算法。這種社區劃分的方法有不少,LPA只是一種最簡單的一種。好比,以微博爲例,用戶在微博上能夠關注感興趣的人,一樣也會被其餘人關注,這樣用戶和用戶之間就存在了關係,使用LPA就能夠對用戶進行聚類操做,相同興趣點的用戶能夠聚類在一塊兒,劃分一塊兒以後就能夠統一進行推薦了,這樣就能夠用LPA。 ###社區劃分 社區結構指的就是在網絡中由一些節點構成的特定分組,在同一個分組內的節點經過節點,之間的鏈接邊緊密的鏈接在一塊兒,而在分組和分組之間,其鏈接比較鬆散,稱每個分組就是一個社區。由上就能夠知道社區是網絡中節點的集合,這些節點內部鏈接較爲緊密而外部鏈接較爲稀疏。 在一個社區網絡中每個用戶其實就是一個節點,用戶之間經過互相關注關係構成了用戶之間的社交關係,用戶之間經過轉發感興趣的東西,從而就構成了用戶之間的興趣關係。經過將不一樣用戶劃分到不一樣的社區,使得每個社區是都有不一樣的屬性,好比興趣,領域等等。而在兩個興趣之間的關係相對來講就比較弱一些的就被分紅了兩個社區,這兩個社區之間的相對鏈接會較爲稀疏。好比:node
def loadData(filePath):
f = open(filePath)
vector_dict = {}
edge_dict = {}
for line in f.readlines():
lines = line.strip().split(" ")
for i in range(2):
if lines[i] not in vector_dict:
vector_dict[lines[i]] = int(lines[i])
edge_list = []
if len(lines) == 3:
edge_list.append(lines[1 - i] + ":" + lines[2])
else:
edge_list.append(lines[1 - i] + ":" + "1")
edge_dict[lines[i]] = edge_list
else:
edge_list = edge_dict[lines[i]]
if len(lines) == 3:
edge_list.append(lines[1 - i] + ":" + lines[2])
else:
edge_list.append(lines[1 - i] + ":" + "1")
edge_dict[lines[i]] = edge_list
return vector_dict, edge_dict
複製代碼
def get_max_community_label(vector_dict, adjacency_node_list):
label_dict = {}
for node in adjacency_node_list:
node_id_weight = node.strip().split(":")
node_id = node_id_weight[0]
node_weight = int(node_id_weight[1])
if vector_dict[node_id] not in label_dict:
label_dict[vector_dict[node_id]] = node_weight
else:
label_dict[vector_dict[node_id]] += node_weight
sort_list = sorted(label_dict.items(), key=lambda d: d[1], reverse=True)
return sort_list[0][0]
複製代碼
獲得鄰居節點最多的社區標籤數。git
def get_max_community_label(vector_dict, adjacency_node_list):
label_dict = {}
for node in adjacency_node_list:
node_id_weight = node.strip().split(":")
node_id = node_id_weight[0]
node_weight = int(node_id_weight[1])
if vector_dict[node_id] not in label_dict:
label_dict[vector_dict[node_id]] = node_weight
else:
label_dict[vector_dict[node_id]] += node_weight
sort_list = sorted(label_dict.items(), key=lambda d: d[1], reverse=True)
return sort_list[0][0]
複製代碼
檢查是否到結束條件了。github
def check(vector_dict, edge_dict):
for node in vector_dict.keys():
adjacency_node_list = edge_dict[node]
node_label = vector_dict[node]
label = get_max_community_label(vector_dict, adjacency_node_list)
if node_label >= label:
continue
else:
return 0
return 1
複製代碼
主函數。算法
def label_propagation(vector_dict, edge_dict):
t = 0
print('First Label: ')
while True:
if (check(vector_dict, edge_dict) == 0):
t = t + 1
print('iteration: ', t)
for node in vector_dict.keys():
adjacency_node_list = edge_dict[node]
vector_dict[node] = get_max_community_label(vector_dict, adjacency_node_list)
else:
break
return vector_dict
複製代碼
最後效果: bash
###附上GitHub代碼:github.com/GreenArrow2…網絡