本文整理汇总了Python中networkx.from_numpy_array方法的典型用法代码示例。如果您正苦于以下问题:Python networkx.from_numpy_array方法的具体用法?Python networkx.from_numpy_array怎么用?Python networkx.from_numpy_array使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类networkx
的用法示例。
在下文中一共展示了networkx.from_numpy_array方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: as_graph
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import from_numpy_array [as 别名]
def as_graph(self, directed=True):
if self.normalized_difference.ndim > 2:
raise MarkovError("You can only graph one-step chains.")
try:
import networkx as nx
except ImportError:
nx = None
if nx is None:
print("Please install networkx with `pip install networkx`.")
return
if directed:
alg = nx.DiGraph
else:
alg = nx.Graph
G = nx.from_numpy_array(self.normalized_difference, create_using=alg)
nx.set_node_attributes(G, self._state_dict, 'state')
return G
示例2: obfuscator
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import from_numpy_array [as 别名]
def obfuscator(a_string):
filename = a_string.replace(" ", "_") + ".png"
#Create an image of our string using Imagemagick -- image must be square
subprocess.run(["convert", "-background","white", "-fill", "black",
"-size",
f"{graph_order_and_image_dim}x{graph_order_and_image_dim}",
"caption:" + a_string, filename])
#Turn our image into a numpy array
string_as_image = Image.open(filename)
string_as_array = np.array(string_as_image)
#We just need an array of 1's and 0's
string_as_array[string_as_array > 0] = 1
#Turn our array into a graph by treating it as an adjacency matrix
string_as_graph = nx.from_numpy_array(string_as_array,
create_using=nx.DiGraph)
#Obfuscated string is a dictionary of dictionaries of this graph:
return nx.to_dict_of_dicts(string_as_graph, edge_data=1)
示例3: clustering
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import from_numpy_array [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
示例4: setup_class
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import from_numpy_array [as 别名]
def setup_class(self, tmpdir):
n = 10
p = 0.5
wt = np.random.exponential
wtargs = dict(scale=4)
np.random.seed(1)
self.A = gs.simulations.er_np(n, p)
self.B = gs.simulations.er_np(n, p, wt=wt, wtargs=wtargs)
G_A = nx.from_numpy_array(self.A)
G_B = nx.from_numpy_array(self.B)
G_B = nx.relabel_nodes(G_B, lambda x: x + 10) # relabel nodes to go from 10-19.
self.A_path = str(tmpdir / "A_unweighted.edgelist")
self.B_path = str(tmpdir / "B.edgelist")
self.root = str(tmpdir)
nx.write_edgelist(G_A, self.A_path, data=False)
nx.write_weighted_edgelist(G_B, self.B_path)
示例5: test_from_numpy_array_type
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import from_numpy_array [as 别名]
def test_from_numpy_array_type(self):
A = np.array([[1]])
G = nx.from_numpy_array(A)
assert_equal(type(G[0][0]['weight']), int)
A = np.array([[1]]).astype(np.float)
G = nx.from_numpy_array(A)
assert_equal(type(G[0][0]['weight']), float)
A = np.array([[1]]).astype(np.str)
G = nx.from_numpy_array(A)
assert_equal(type(G[0][0]['weight']), str)
A = np.array([[1]]).astype(np.bool)
G = nx.from_numpy_array(A)
assert_equal(type(G[0][0]['weight']), bool)
A = np.array([[1]]).astype(np.complex)
G = nx.from_numpy_array(A)
assert_equal(type(G[0][0]['weight']), complex)
A = np.array([[1]]).astype(np.object)
assert_raises(TypeError, nx.from_numpy_array, A)
示例6: convert
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import from_numpy_array [as 别名]
def convert(something): # use networkx conversion from numpy array
# g = nx.from_numpy_matrix(someNPMat)
# print(type(something))
g = nx.from_numpy_array(something)
return g
示例7: create_graph
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import from_numpy_array [as 别名]
def create_graph(A, create_using=None, remove_self_loops=True):
"""Flexibly creating a networkx graph from a numpy array.
Parameters
----------
A (np.ndarray)
A numpy array.
create_using (nx.Graph or None)
Create the graph using a specific networkx graph. Can be used for
forcing an asymmetric matrix to create an undirected graph, for
example.
remove_self_loops (bool)
If True, remove the diagonal of the matrix before creating the
graph object.
Returns
-------
G
A graph, typically a nx.Graph or nx.DiGraph.
"""
if remove_self_loops:
np.fill_diagonal(A, 0)
if create_using is None:
if np.allclose(A, A.T):
G = nx.from_numpy_array(A, create_using=nx.Graph())
else:
G = nx.from_numpy_array(A, create_using=nx.DiGraph())
else:
G = nx.from_numpy_array(A, create_using=create_using)
return G
示例8: make_all_dists
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import from_numpy_array [as 别名]
def make_all_dists(bin_adj, dmax, use_weights=False):
g = nx.from_numpy_array(bin_adj.detach().numpy())
if not use_weights:
lengths = nx.shortest_path_length(g)
else:
lengths = nx.shortest_path_length(g, weight='weight')
dist = torch.zeros_like(bin_adj)
for u, lens_u in lengths:
for v in range(bin_adj.shape[0]):
if v in lens_u:
dist[u,v] = lens_u[v]
else:
dist[u,v] = dmax
return dist
示例9: test_graphin
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import from_numpy_array [as 别名]
def test_graphin(self):
G = nx.from_numpy_array(self.A)
np.testing.assert_array_equal(nx.to_numpy_array(G), gs.utils.import_graph(G))
示例10: test_graphin
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import from_numpy_array [as 别名]
def test_graphin(self):
G = nx.from_numpy_array(self.A)
np.testing.assert_array_equal(nx.to_numpy_array(G), gus.import_graph(G))
示例11: test_from_numpy_matrix_type
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import from_numpy_array [as 别名]
def test_from_numpy_matrix_type(self):
A = np.matrix([[1]])
G = nx.from_numpy_matrix(A)
assert_equal(type(G[0][0]['weight']), int)
A = np.matrix([[1]]).astype(np.float)
G = nx.from_numpy_matrix(A)
assert_equal(type(G[0][0]['weight']), float)
A = np.matrix([[1]]).astype(np.str)
G = nx.from_numpy_matrix(A)
assert_equal(type(G[0][0]['weight']), str)
A = np.matrix([[1]]).astype(np.bool)
G = nx.from_numpy_matrix(A)
assert_equal(type(G[0][0]['weight']), bool)
A = np.matrix([[1]]).astype(np.complex)
G = nx.from_numpy_matrix(A)
assert_equal(type(G[0][0]['weight']), complex)
A = np.matrix([[1]]).astype(np.object)
assert_raises(TypeError, nx.from_numpy_matrix, A)
G = nx.cycle_graph(3)
A = nx.adj_matrix(G).todense()
H = nx.from_numpy_matrix(A)
assert_true(all(type(m) == int and type(n) == int for m, n in H.edges()))
H = nx.from_numpy_array(A)
assert_true(all(type(m) == int and type(n) == int for m, n in H.edges()))
示例12: identity_conversion
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import from_numpy_array [as 别名]
def identity_conversion(self, G, A, create_using):
assert(A.sum() > 0)
GG = nx.from_numpy_array(A, create_using=create_using)
self.assert_equal(G, GG)
GW = nx.to_networkx_graph(A, create_using=create_using)
self.assert_equal(G, GW)
GI = nx.empty_graph(0, create_using).__class__(A)
self.assert_equal(G, GI)
示例13: test_shape
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import from_numpy_array [as 别名]
def test_shape(self):
"Conversion from non-square array."
A = np.array([[1, 2, 3], [4, 5, 6]])
assert_raises(nx.NetworkXError, nx.from_numpy_array, A)
示例14: test_from_numpy_array_dtype
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import from_numpy_array [as 别名]
def test_from_numpy_array_dtype(self):
dt = [('weight', float), ('cost', int)]
A = np.array([[(1.0, 2)]], dtype=dt)
G = nx.from_numpy_array(A)
assert_equal(type(G[0][0]['weight']), float)
assert_equal(type(G[0][0]['cost']), int)
assert_equal(G[0][0]['cost'], 2)
assert_equal(G[0][0]['weight'], 1.0)
示例15: test_symmetric
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import from_numpy_array [as 别名]
def test_symmetric(self):
"""Tests that a symmetric array has edges added only once to an
undirected multigraph when using :func:`networkx.from_numpy_array`.
"""
A = np.array([[0, 1], [1, 0]])
G = nx.from_numpy_array(A, create_using=nx.MultiGraph)
expected = nx.MultiGraph()
expected.add_edge(0, 1, weight=1)
assert_graphs_equal(G, expected)