本文整理汇总了Python中networkx.from_numpy_matrix方法的典型用法代码示例。如果您正苦于以下问题:Python networkx.from_numpy_matrix方法的具体用法?Python networkx.from_numpy_matrix怎么用?Python networkx.from_numpy_matrix使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类networkx
的用法示例。
在下文中一共展示了networkx.from_numpy_matrix方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _calc_graph_func
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import from_numpy_matrix [as 别名]
def _calc_graph_func(p):
con, times_chunk, graph_func = p
vals = []
now = time.time()
for run, t in enumerate(times_chunk):
utils.time_to_go(now, run, len(times_chunk), 10)
con_t = con[:, :, t]
g = nx.from_numpy_matrix(con_t)
if graph_func == 'closeness_centrality':
x = nx.closeness_centrality(g)
elif graph_func == 'degree_centrality':
x = nx.degree_centrality(g)
elif graph_func == 'eigenvector_centrality':
x = nx.eigenvector_centrality(g, max_iter=10000)
elif graph_func == 'katz_centrality':
x = nx.katz_centrality(g, max_iter=100000)
else:
raise Exception('Wrong graph func!')
vals.append([x[k] for k in range(len(x))])
vals = np.array(vals)
return vals, times_chunk
示例2: time_align_visualize
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import from_numpy_matrix [as 别名]
def time_align_visualize(alignments, time, y, namespace='time_align'):
plt.figure()
heat = np.flip(alignments + alignments.T +
np.eye(alignments.shape[0]), axis=0)
sns.heatmap(heat, cmap="YlGnBu", vmin=0, vmax=1)
plt.savefig(namespace + '_heatmap.svg')
G = nx.from_numpy_matrix(alignments)
G = nx.maximum_spanning_tree(G)
pos = {}
for i in range(len(G.nodes)):
pos[i] = np.array([time[i], y[i]])
mst_edges = set(nx.maximum_spanning_tree(G).edges())
weights = [ G[u][v]['weight'] if (not (u, v) in mst_edges) else 8
for u, v in G.edges() ]
plt.figure()
nx.draw(G, pos, edges=G.edges(), width=10)
plt.ylim([-1, 1])
plt.savefig(namespace + '.svg')
示例3: neighborhoods_weights_to_root
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import from_numpy_matrix [as 别名]
def neighborhoods_weights_to_root(adjacency, sequence, size):
def _neighborhoods_weights_to_root(adjacency, sequence):
graph = nx.from_numpy_matrix(adjacency)
neighborhoods = np.zeros((sequence.shape[0], size), dtype=np.int32)
neighborhoods.fill(-1)
for i in xrange(0, sequence.shape[0]):
n = sequence[i]
if n < 0:
break
shortest = nx.single_source_dijkstra_path_length(graph, n).items()
shortest = sorted(shortest, key=lambda v: v[1])
shortest = shortest[:size]
for j in xrange(0, min(size, len(shortest))):
neighborhoods[i][j] = shortest[j][0]
return neighborhoods
return tf.py_func(_neighborhoods_weights_to_root, [adjacency, sequence],
tf.int32, stateful=False,
name='neighborhoods_weights_to_root')
示例4: decode_graph
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import from_numpy_matrix [as 别名]
def decode_graph(adj, prefix):
adj = np.asmatrix(adj)
G = nx.from_numpy_matrix(adj)
# G.remove_nodes_from(nx.isolates(G))
print('num of nodes: {}'.format(G.number_of_nodes()))
print('num of edges: {}'.format(G.number_of_edges()))
G_deg = nx.degree_histogram(G)
G_deg_sum = [a * b for a, b in zip(G_deg, range(0, len(G_deg)))]
print('average degree: {}'.format(sum(G_deg_sum) / G.number_of_nodes()))
if nx.is_connected(G):
print('average path length: {}'.format(nx.average_shortest_path_length(G)))
print('average diameter: {}'.format(nx.diameter(G)))
G_cluster = sorted(list(nx.clustering(G).values()))
print('average clustering coefficient: {}'.format(sum(G_cluster) / len(G_cluster)))
cycle_len = []
cycle_all = nx.cycle_basis(G, 0)
for item in cycle_all:
cycle_len.append(len(item))
print('cycles', cycle_len)
print('cycle count', len(cycle_len))
draw_graph(G, prefix=prefix)
示例5: __getitem__
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import from_numpy_matrix [as 别名]
def __getitem__(self, idx):
adj_copy = self.adj_all[idx].copy()
x_batch = np.zeros((self.n, self.max_prev_node)) # here zeros are padded for small graph
x_batch[0,:] = 1 # the first input token is all ones
y_batch = np.zeros((self.n, self.max_prev_node)) # here zeros are padded for small graph
# generate input x, y pairs
len_batch = adj_copy.shape[0]
x_idx = np.random.permutation(adj_copy.shape[0])
adj_copy = adj_copy[np.ix_(x_idx, x_idx)]
adj_copy_matrix = np.asmatrix(adj_copy)
G = nx.from_numpy_matrix(adj_copy_matrix)
# then do bfs in the permuted G
start_idx = np.random.randint(adj_copy.shape[0])
x_idx = np.array(bfs_seq(G, start_idx))
adj_copy = adj_copy[np.ix_(x_idx, x_idx)]
adj_encoded = encode_adj(adj_copy.copy(), max_prev_node=self.max_prev_node)
# get x and y and adj
# for small graph the rest are zero padded
y_batch[0:adj_encoded.shape[0], :] = adj_encoded
x_batch[1:adj_encoded.shape[0] + 1, :] = adj_encoded
return {'x':x_batch,'y':y_batch, 'len':len_batch}
示例6: is_connected
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import from_numpy_matrix [as 别名]
def is_connected(C):
"""
Return `True` if the square connection matrix `C` is connected, i.e., every
unit is reachable from every other unit, otherwise `False`.
Note
----
This function only performs the check if the NetworkX package is available:
https://networkx.github.io/
"""
if nx is None:
return True
G = nx.from_numpy_matrix(C, create_using=nx.DiGraph())
return nx.is_strongly_connected(G)
示例7: test_from_numpy_matrix_type
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import from_numpy_matrix [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)
示例8: test_edmonds1_minbranch
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import from_numpy_matrix [as 别名]
def test_edmonds1_minbranch():
# Using -G_array and min should give the same as optimal_arborescence_1,
# but with all edges negative.
edges = [ (u, v, -w) for (u, v, w) in optimal_arborescence_1 ]
G = nx.DiGraph()
G = nx.from_numpy_matrix(-G_array, create_using=G)
# Quickly make sure max branching is empty.
x = branchings.maximum_branching(G)
x_ = build_branching([])
assert_equal_branchings(x, x_)
# Now test the min branching.
x = branchings.minimum_branching(G)
x_ = build_branching(edges)
assert_equal_branchings(x, x_)
示例9: test_edmonds1_minbranch
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import from_numpy_matrix [as 别名]
def test_edmonds1_minbranch():
# Using -G_array and min should give the same as optimal_arborescence_1,
# but with all edges negative.
edges = [(u, v, -w) for (u, v, w) in optimal_arborescence_1]
G = nx.DiGraph()
G = nx.from_numpy_matrix(-G_array, create_using=G)
# Quickly make sure max branching is empty.
x = branchings.maximum_branching(G)
x_ = build_branching([])
assert_equal_branchings(x, x_)
# Now test the min branching.
x = branchings.minimum_branching(G)
x_ = build_branching(edges)
assert_equal_branchings(x, x_)
示例10: test_from_numpy_matrix_type
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import from_numpy_matrix [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)
示例11: sort_words
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import from_numpy_matrix [as 别名]
def sort_words(vertex_source, window = 2, pagerank_config = {'alpha': 0.85,}):
"""将单词按关键程度从大到小排序
Keyword arguments:
vertex_source -- 二维列表,子列表代表句子,子列表的元素是单词,这些单词用来构造pagerank中的节点
edge_source -- 二维列表,子列表代表句子,子列表的元素是单词,根据单词位置关系构造pagerank中的边
window -- 一个句子中相邻的window个单词,两两之间认为有边
pagerank_config -- pagerank的设置
"""
sorted_words = []
word_index = {}
index_word = {}
_vertex_source = vertex_source
words_number = 0
for word_list in _vertex_source:
for word in word_list:
if not word in word_index:
word_index[word] = words_number
index_word[words_number] = word
words_number += 1
graph = np.zeros((words_number, words_number))
for word_list in _vertex_source:
for w1, w2 in combine(word_list, window):
if w1 in word_index and w2 in word_index:
index1 = word_index[w1]
index2 = word_index[w2]
graph[index1][index2] = 1.0
graph[index2][index1] = 1.0
debug('graph:\n', graph)
nx_graph = nx.from_numpy_matrix(graph)
scores = nx.pagerank(nx_graph, **pagerank_config) # this is a dict
sorted_scores = sorted(scores.items(), key = lambda item: item[1], reverse=True)
for index, score in sorted_scores:
item = AttrDict(word=index_word[index], weight=score)
sorted_words.append(item)
return sorted_words
示例12: plot_graph
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import from_numpy_matrix [as 别名]
def plot_graph(self, am, position=None, cls=None, fig_name='graph.png'):
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
g = nx.from_numpy_matrix(am)
if position is None:
position=nx.drawing.circular_layout(g)
fig = plt.figure()
if cls is None:
cls='r'
else:
# Make a user-defined colormap.
cm1 = mcol.LinearSegmentedColormap.from_list("MyCmapName", ["r", "b"])
# Make a normalizer that will map the time values from
# [start_time,end_time+1] -> [0,1].
cnorm = mcol.Normalize(vmin=0, vmax=1)
# Turn these into an object that can be used to map time values to colors and
# can be passed to plt.colorbar().
cpick = cm.ScalarMappable(norm=cnorm, cmap=cm1)
cpick.set_array([])
cls = cpick.to_rgba(cls)
plt.colorbar(cpick, ax=fig.add_subplot(111))
nx.draw(g, pos=position, node_color=cls, ax=fig.add_subplot(111))
fig.savefig(os.path.join(self.plotdir, fig_name))
示例13: sort_sentences
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import from_numpy_matrix [as 别名]
def sort_sentences(sentences, words, sim_func = get_similarity, pagerank_config = {'alpha': 0.85,}):
"""将句子按照关键程度从大到小排序
Keyword arguments:
sentences -- 列表,元素是句子
words -- 二维列表,子列表和sentences中的句子对应,子列表由单词组成
sim_func -- 计算两个句子的相似性,参数是两个由单词组成的列表
pagerank_config -- pagerank的设置
"""
sorted_sentences = []
_source = words
sentences_num = len(_source)
graph = np.zeros((sentences_num, sentences_num))
for x in xrange(sentences_num):
for y in xrange(x, sentences_num):
similarity = sim_func( _source[x], _source[y] )
graph[x, y] = similarity
graph[y, x] = similarity
nx_graph = nx.from_numpy_matrix(graph)
scores = nx.pagerank(nx_graph, **pagerank_config) # this is a dict
sorted_scores = sorted(scores.items(), key = lambda item: item[1], reverse=True)
for index, score in sorted_scores:
item = AttrDict(index=index, sentence=sentences[index], weight=score)
sorted_sentences.append(item)
return sorted_sentences
示例14: betweenness_centrality
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import from_numpy_matrix [as 别名]
def betweenness_centrality(adjacency, labels=None):
def _betweeness_centrality(adjacency, labels):
graph = nx.from_numpy_matrix(adjacency)
labeling = nx.betweenness_centrality(graph, normalized=False)
labeling = list(labeling.items())
labeling = sorted(labeling, key=lambda n: n[1], reverse=True)
return np.array([labels[n[0]] for n in labeling])
labels = _labels_default(labels, adjacency)
return tf.py_func(_betweeness_centrality, [adjacency, labels], tf.int32,
stateful=False, name='betweenness_centrality')
示例15: _textrank
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import from_numpy_matrix [as 别名]
def _textrank(matrix):
'''returns principal eigenvector
of the adjacency matrix'''
graph = nx.from_numpy_matrix(matrix)
return nx.pagerank(graph)