簡體   English   中英

使用networkx檢測社區

[英]detect communities using networkx

我有一個如下所示的數據庫:

id_1 id_2 日期
H4FR923 AAE9987Y 01-01-2018

我是這樣讀取數據的:

    import pandas as pd 
    
    path = "data.csv"
    
    df = pd.read_csv(path) 

然后通過以下方式使用 netowkrx 創建一個網絡:

    import networkx as nx 
    G = nx.from_pandas_edgelist(df, source='id_1', target='id_2', edge_attr='date')

現在我想檢測社區,我需要根據日期定義社區。 例如,就像我們在日期欄下的日期:1-1-2018 - 1-6-2018

我想建立一個社區,在此日期 1-1-2018 tp 1-6-2018 和 community_2 之間擁有所有節點,並且 community_2 可能有 2-6-2018 到 30-12-2018 類似這樣

所以每個社區都應該有具有一組日期的節點

那可能嗎!!

這是我所做的:

from networkx.algorithms import community

partition = community.asyn_lpa_communities(G) 

def modularity(G, partition):
W = sum(G.edges[v, w].get('weight', 1) for v, w in G.edges)
summation = 0
for cluster_nodes in partition:
    s_c = sum(G.degree(n, weight='weight') for n in cluster_nodes)
    # Use subgraph to count only internal links
    C = G.subgraph(cluster_nodes)
    W_c = sum(C.edges[v, w].get('weight', 1) for v, w in C.edges)
    summation += W_c - s_c ** 2 / (4 * W)

return summation / W

但現在確定如何根據我上面描述的社區做任何幫助!

我假設您想根據邊緣 dataframe 中的dateid_1節點進行分區。

根據您在評論中給出的規格,我相信您想要這樣的東西:

import networkx as nx
import pandas as pd

data = {
    "id_1": [1, 2, 3],
    "id_2": [2, 3, 1],
    "date": ["date1", "date2", "date1"],
}


df = pd.DataFrame(data, columns=[x for x in data.keys()])

# df =
#    id_1  id_2   date
# 0     1     2  date1
# 1     2     3  date2
# 2     3     1  date1

node_attrs = dict(zip(df.id_1, df.date))

# node_attrs ={1: 'date1', 2: 'date2', 3: 'date1'}

for node in node_attrs:
    node_attrs[node] = {"date": node_attrs[node]}

for node in node_attrs:
    if node_attrs[node]["date"] == "date1":
        node_attrs[node]["partition"] = 1
    else:
        node_attrs[node]["partition"] = 2


# creating the graph
G = nx.from_pandas_edgelist(df, source="id_1", target="id_2")

nx.set_node_attributes(G, node_attrs)

print(G.nodes(data=True))

# output: [(1, {'date': 'date1', 'partition': 1}), (2, {'date': 'date2', 'partition': 2}), (3, {'date': 'date1', 'partition': 1})]

所有節點都根據其date屬性進行分區。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM