Python 围绕特定节点对图的节点进行聚类
考虑networkx中的节点图,如何应用所有节点的kmean群集,其中特定节点被视为群集的质心。换句话说,假设我们有这个图:Python 围绕特定节点对图的节点进行聚类,python,python-3.x,networkx,k-means,Python,Python 3.x,Networkx,K Means,考虑networkx中的节点图,如何应用所有节点的kmean群集,其中特定节点被视为群集的质心。换句话说,假设我们有这个图: import networkx as nx s = [0,3,2,3,4,5,1] t = [1,2,7,4,6,6,5] dist = [3,2,5,1,5,4,2] G = nx.Graph() for i in range(len(s)): G.add_edge(s[i],t[i],weight=dist[i]) 我想在网络上应用kmean聚类,例如,
import networkx as nx
s = [0,3,2,3,4,5,1]
t = [1,2,7,4,6,6,5]
dist = [3,2,5,1,5,4,2]
G = nx.Graph()
for i in range(len(s)):
G.add_edge(s[i],t[i],weight=dist[i])
我想在网络上应用kmean聚类,例如,我选择质心为3和6,然后相应地对图进行聚类,以生成两个子图(或输入的任意多个质心)
我一直在研究kmean聚类,这里没有涉及输入的质心,而是只考虑没有质心节点的聚类数。注意,不能直接将k-means聚类应用于网络,因为不一定存在测量节点和质心之间距离的度量但是 。。假设你假设:
- 加权最短路径的路径长度是一对节点之间的距离度量。
- 质心是节点。注:在传统的k-均值聚类中,数据点本身并不一定是数据点
- 将每个节点与质心关联,以使每个节点到其质心的距离之和最小(即带簇距离之和)
- 更新质心
- 重复前两步,直到质心稳定
下面是如何使用python实现这一点: 1.定义初始质心:
centroids = [3, 6]
2.对于每个节点,获取到所有质心的所有最短路径
例如:
这给出了(在这里它们与质心id一起报告):
3.计算所有节点的所有最短路径的实际距离,即对路径上的权重求和:
例如:
因此,距离为:
In [28]: distances
Out[28]:
[[(3, 15), (6, 9)],
[(3, 12), (6, 6)],
[(3, 0), (6, 6)],
[(3, 2), (6, 8)],
[(3, 7), (6, 13)],
[(3, 1), (6, 5)],
[(3, 6), (6, 0)],
[(3, 10), (6, 4)]]
4.为所有节点获取具有最小距离的质心:
例如:
根据质心进行分组:
In [30]: closest_centroid
Out[30]: [6, 6, 3, 3, 3, 3, 6, 6]
5.更新质心,因为当前质心可能不再是组的实际质心:
方法:
迭代:如果新质心与旧质心不同,则使用新质心并重复步骤2-5。
最后一步:如果在第5步中找到的新质心与旧质心相同,或者您已达到迭代限制,将最近的质心与每个节点相关联:
centroids = [3, 6]
例如:
或者nx。如果您仍然在v1.x上,则设置节点属性(G,“形心”,cent\u dict)
这将是一种对网络进行k-均值聚类的方法
希望对大家有帮助,编码快乐 通常,您需要一个可以应用的度量来测量质心和任何数据点之间的距离。在这种情况下,您的度量是什么?因为我选择的中心是图中的节点,所以距离仅为nx。最短路径长度(G,3,G.nodes())能否请您在代码中更明确一些?抱歉,这不是很容易理解:P想法是将每个节点与其最近的质心相关联,对吗?!是的,那正是我要找的!
In [28]: distances
Out[28]:
[[(3, 15), (6, 9)],
[(3, 12), (6, 6)],
[(3, 0), (6, 6)],
[(3, 2), (6, 8)],
[(3, 7), (6, 13)],
[(3, 1), (6, 5)],
[(3, 6), (6, 0)],
[(3, 10), (6, 4)]]
closest_centroid = [
min(dist, key=lambda d: d[1])[0] for dist in distances
]
In [30]: closest_centroid
Out[30]: [6, 6, 3, 3, 3, 3, 6, 6]
# for each group
# for each member of the group
# get the distance of shortest paths to all the other members of the group
# sum this distances
# find the node with the minimal summed distance > this is the new centroid of the group
nodes = [n for n in G] # the actual id of the nodes
cent_dict = {nodes[i]: closest_centroid[i] for i in range(len(nodes))}
nx.set_node_attributes(G, cent_dict, 'centroid')