本文整理汇总了Python中community.best_partition方法的典型用法代码示例。如果您正苦于以下问题:Python community.best_partition方法的具体用法?Python community.best_partition怎么用?Python community.best_partition使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类community
的用法示例。
在下文中一共展示了community.best_partition方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: plot_graph
# 需要导入模块: import community [as 别名]
# 或者: from community import best_partition [as 别名]
def plot_graph(plt, G):
plt.title('num of nodes: '+str(G.number_of_nodes()), fontsize = 4)
parts = community.best_partition(G)
values = [parts.get(node) for node in G.nodes()]
colors = []
for i in range(len(values)):
if values[i] == 0:
colors.append('red')
if values[i] == 1:
colors.append('green')
if values[i] == 2:
colors.append('blue')
if values[i] == 3:
colors.append('yellow')
if values[i] == 4:
colors.append('orange')
if values[i] == 5:
colors.append('pink')
if values[i] == 6:
colors.append('black')
plt.axis("off")
pos = nx.spring_layout(G)
# pos = nx.spectral_layout(G)
nx.draw_networkx(G, with_labels=True, node_size=4, width=0.3, font_size = 3, node_color=colors,pos=pos)
示例2: clustering
# 需要导入模块: import community [as 别名]
# 或者: from community import best_partition [as 别名]
def clustering(self, threshold):
"""分不同词性的聚类
:return: partition: dict {word_id: cluster_id}
"""
print("Louvain clustering")
partition = {}
part_offset = 0
for etype, ners in self.type_entity_dict.items():
sub_id_mapping = [self.word2id[ner0] for ner0 in ners if ner0 in self.word2id]
if len(sub_id_mapping) == 0:
continue
emb_mat_sub = self.emb_mat[sub_id_mapping, :]
cos_sims = cosine_similarity(emb_mat_sub)
cos_sims -= np.eye(len(emb_mat_sub))
adj_mat = (cos_sims > threshold).astype(int)
G = nx.from_numpy_array(adj_mat)
partition_sub = community.best_partition(G)
for sub_id, main_id in enumerate(sub_id_mapping):
sub_part_id = partition_sub[sub_id]
partition[main_id] = sub_part_id + part_offset
part_offset += max(partition_sub.values()) + 1
return partition
示例3: louvain
# 需要导入模块: import community [as 别名]
# 或者: from community import best_partition [as 别名]
def louvain(
edge_file,
output_file,
resolution
):
################################################################################################
if not os.path.exists(edge_file):
print(('Error: ' + edge_file + ' does not exist!'));
sys.exit(1);
################################################################################################
G = nx.Graph();
with open(edge_file) as fin:
for line in fin:
elems = line.split();
G.add_edge(elems[0],elems[1], weight=float(elems[2]))
partition = community.best_partition(G, resolution = resolution)
with open(output_file, "w") as fout:
for node in list(partition.keys()):
fout.write(str(node) + " " + str(partition[node] + 1) + "\n")
示例4: Louvain
# 需要导入模块: import community [as 别名]
# 或者: from community import best_partition [as 别名]
def Louvain(self):
print('initializing the graph...')
g = nx.Graph()
g.add_nodes_from(np.arange(len(self.dataset)).tolist())
print('adding edges...')
edge_list = np.int32(np.round(self.dist_list))
true_edge_list = []
for i in range(len(idx_list)):
if edge_list[i]==0:
true_edge_list.append(idx_list[i])
g.add_edges_from(true_edge_list)
print('Clustering...')
partition = community.best_partition(g)
label_list = [0]*len(dataset)
for key in partition:
label_list[key] = partition[key]
return label_list
示例5: produce
# 需要导入模块: import community [as 别名]
# 或者: from community import best_partition [as 别名]
def produce(self, X, best_partition=None, graph=None):
best_partition = best_partition or co.best_partition(graph)
values = [b for a, b in best_partition.items()]
missing_community_index = np.max(values) + 10
result = pd.Series(index=X.index)
for i in X.index:
node = X.loc[i][0]
if node in best_partition:
community = best_partition[node]
elif str(node) in best_partition:
community = best_partition[str(node)]
else:
community = missing_community_index
# increment missing index
missing_community_index += 1
result.loc[i] = community
return result.values
示例6: score
# 需要导入模块: import community [as 别名]
# 或者: from community import best_partition [as 别名]
def score(self, sg, *args, **xargs): # get_modularity_cluster
"""
:param sg: subgraph
:return: A dictionary of the modularity scores of the nodes in the subgraph
"""
# args/xargs collected so that passing a topic doesn't mess things up
# Convert to diGraph
if sg.is_multigraph():
sg = self.multigraph_to_digraph(sg)
# Convert to undirected
sg = sg.to_undirected()
return community.best_partition(sg)
示例7: _create_partitions
# 需要导入模块: import community [as 别名]
# 或者: from community import best_partition [as 别名]
def _create_partitions(self):
"""
Creating a non-overlapping clustering of nodes in the persona graph.
"""
print("Clustering the persona graph.")
self.partitions = community.best_partition(self.persona_graph, resolution=self.resolution)
self.overlapping_partitions = {node: [] for node in self.graph.nodes()}
for node, membership in self.partitions.items():
self.overlapping_partitions[self.personality_map[node]].append(membership)
示例8: fit
# 需要导入模块: import community [as 别名]
# 或者: from community import best_partition [as 别名]
def fit(self, graph):
"""
Fitting an Edge Motif clustering model.
Arg types:
* **graph** *(NetworkX graph)* - The graph to be clustered.
"""
self._set_seed()
self._check_graph(graph)
self._graph = graph
self._calculate_motifs()
self._extract_components()
self._fill_blocks()
self._partition = community.best_partition(self._graph, random_state=self.seed)
示例9: _create_partitions
# 需要导入模块: import community [as 别名]
# 或者: from community import best_partition [as 别名]
def _create_partitions(self):
"""
Creating a non-overlapping clustering of nodes in the persona graph.
"""
self.partitions = community.best_partition(self.persona_graph, resolution=self.resolution)
self.overlapping_partitions = {node: [] for node in self.graph.nodes()}
for node, membership in self.partitions.items():
self.overlapping_partitions[self.personality_map[node]].append(membership)
示例10: _run_louvain
# 需要导入模块: import community [as 别名]
# 或者: from community import best_partition [as 别名]
def _run_louvain(nxsupra, resolution, N, T):
comtmp = np.zeros([N*T])
com = community.best_partition(
nxsupra, resolution=resolution, random_state=None)
comtmp[np.array(list(com.keys()), dtype=int)] = list(com.values())
return comtmp
示例11: busmap_by_louvain
# 需要导入模块: import community [as 别名]
# 或者: from community import best_partition [as 别名]
def busmap_by_louvain(network):
lines = network.lines.loc[:,['bus0', 'bus1']].assign(weight=network.lines.num_parallel).set_index(['bus0','bus1'])
lines.weight+=0.1
G = nx.Graph()
G.add_nodes_from(network.buses.index)
G.add_edges_from((u,v,dict(weight=w)) for (u,v),w in lines.itertuples())
b=community.best_partition(G)
list_cluster=[]
for i in b:
list_cluster.append(str(b[i]))
return pd.Series(list_cluster,index=network.buses.index)
示例12: __get_partitions
# 需要导入模块: import community [as 别名]
# 或者: from community import best_partition [as 别名]
def __get_partitions(self, resolution, weight="weight", **kwargs):
"""
Protected method for computing the best
partitions using python-louvain. This is
a simple wrapper to avoid code repetition.
Parameters
----------
weight :
Column to use that represents edge
weights.
resolution :
Resolution of Louvain graph. Passed down
to community.best_partition().
**kwargs :
Eventually passed to community.best_partition().
Returns
-------
A pandas dataframe with the community
members (subscribers) and their respective
community identifier.
"""
self.partition = community.best_partition(
self.graph_louvain, weight=weight, resolution=resolution, **kwargs
)
return pd.DataFrame(
list(self.partition.items()), columns=["subscriber", "community"]
)
示例13: __GetModComms
# 需要导入模块: import community [as 别名]
# 或者: from community import best_partition [as 别名]
def __GetModComms(self, G):
dict_H = community.best_partition(G)
H1 = {}
for e in dict_H:
if dict_H[e] not in H1:
H1[dict_H[e]] = set([])
H1[dict_H[e]].add(e)
H = []
for e in H1:
H.append(H1[e])
return H
示例14: fit
# 需要导入模块: import community [as 别名]
# 或者: from community import best_partition [as 别名]
def fit(self):
"""
Clustering the target graph.
"""
self._calculate_motifs()
self._extract_components()
self._fill_blocks()
partition = community.best_partition(self.graph)
return partition
示例15: draw_graph
# 需要导入模块: import community [as 别名]
# 或者: from community import best_partition [as 别名]
def draw_graph():
#get data
project_key = dataiku.default_project_key()
similarity = float(request.args.get('similarity'))
node_source = request.args.get('node_source')
node_target = request.args.get('node_target')
interactions = request.args.get('interactions')
dataset = request.args.get('dataset')
name=project_key+'.'+dataset
print name
df=dataiku.Dataset(name).get_dataframe()
df=df[df[interactions]>similarity]
df=df[[node_source,node_target,interactions]]
df.columns=['source','target','weight']
print "%d rows" % df.shape[0]
G=nx.Graph()
G.add_edges_from(zip(df.source,df.target))
print nx.info(G)
# degree
for node, val in dict(nx.degree(G)).iteritems():
G.node[node]['degree'] = val
# pagerank
for node, val in dict(nx.pagerank(G)).iteritems():
G.node[node]['pagerank'] = val
# connected components
components = sorted(nx.connected_components(G), key = len, reverse=True)
for component,nodes in enumerate(components):
for node in nodes:
G.node[node]['cc'] = component
# community
partition = best_partition(G)
for node, cluster in dict(partition).iteritems():
G.node[node]['community'] = cluster
# convert to JSON
data = json_graph.node_link_data(G)
#fix for networkx>=2.0 change of API
if nx.__version__ > 2:
dict_name_id = {data["nodes"][i]["id"] : i for i in xrange(len(data["nodes"]))}
for link in data["links"]:
link["source"] = dict_name_id[link["source"]]
link["target"] = dict_name_id[link["target"]]
return json.dumps({"status" : "ok", "graph": data})