【网络】基于标签的LPA算法的python3版本

LPA算法python2版本见:http://blog.csdn.net/ztf312/article/details/78710501。

下面是python3版本。

 

# -*- coding: utf-8 -*-
"""
Created on Mon Dec  4 15:47:35 2017


@author: ztf
"""


# -*- coding: UTF-8 -*-


"""
Created on 17-11-28


@summary: 实现传统标签传播算法LPA


@author: dreamhome
"""


import random
import networkx as nx
import matplotlib.pyplot as plt
from nets import *
# nets是自己定义的文件,里面有RG、ER、BA、WS,可通过networkx生成

def generate_graph(G):
    """
    :return: Graph graph
    """
    # 定义图
    graph = G


    # 给每个节点增加标签
    for node, data in graph.nodes_iter(True):
        data['label'] = node
            
    return graph




def lpa(graph):
    """
    标签传播算法 使用异步更新方式
    :param graph:
    :return:
    """
    def estimate_stop_condition():
        """
        算法终止条件:所有节点的标签与大部分邻居节点标签相同或者迭代次数超过指定值则停止
        :return:
        """
        for node in graph.nodes_iter():
            count = {}
            for neighbor in graph.neighbors_iter(node):
                neighbor_label = graph.node[neighbor]['label']
                count[neighbor_label] = count.setdefault(
                    neighbor_label, 0) + 1


            # 找到计数值最大的label
            count_items = count.items()
            count_items = sorted(count_items, key=lambda x: x[1], reverse=True)
            labels = [k for k, v in count_items if v == count_items[0][1]]
            # 当节点标签与大部分邻居节点标签相同时则达到停止条件
            if graph.node[node]['label'] not in labels:
                return False


        return True


    loop_count = 0


    # 迭代标签传播过程
    while True:
        loop_count += 1
        print('迭代次数', loop_count)


        for node in graph.nodes_iter():
            count = {}
            for neighbor in graph.neighbors_iter(node):
                neighbor_label = graph.node[neighbor]['label']
                count[neighbor_label] = count.setdefault(
                    neighbor_label, 0) + 1


            # 找到计数值最大的标签
            count_items = count.items()
            # print count_items
            count_items = sorted(count_items, key=lambda x: x[1], reverse=True)
            labels = [(k, v) for k, v in count_items if v == count_items[0][1]]
            # 当多个标签最大计数值相同时随机选取一个标签
            label = random.sample(labels, 1)[0][0]
            graph.node[node]['label'] = label


        if estimate_stop_condition() is True or loop_count >= 10:
            print('complete')
            return




if __name__ == "__main__":


#    path = "/home/dreamhome/network-datasets/dolphins/out.dolphins"
#    graph = read_graph_from_file(path)
    G = WS(100, 2, 0.1)
    graph = generate_graph(G)
    lpa(graph)


    # 根据算法结果画图
    node_color = [float(graph.node[v]['label']) for v in graph]
    nx.draw_networkx(graph, node_color=node_color)
    plt.show()
    labels = set([float(graph.node[v]['label']) for v in graph])
    community = dict()
    print(labels)
    for l in labels:
        community[l] = [v for v in graph if float(graph.node[v]['label'])==l]
        print(l, ":", community[l])
        
    

 

 

 

 

 

 

 

 

 

 

发布了392 篇原创文章 · 获赞 492 · 访问量 241万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览