本文整理汇总了Python中networkx.to_numpy_matrix方法的典型用法代码示例。如果您正苦于以下问题:Python networkx.to_numpy_matrix方法的具体用法?Python networkx.to_numpy_matrix怎么用?Python networkx.to_numpy_matrix使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类networkx
的用法示例。
在下文中一共展示了networkx.to_numpy_matrix方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: learn_embedding
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import to_numpy_matrix [as 别名]
def learn_embedding(self):
graph = self.g.G
A = nx.to_numpy_matrix(graph)
# self._beta = 0.0728
# M_g = np.eye(graph.number_of_nodes()) - self._beta * A
# M_l = self._beta * A
M_g = np.eye(graph.number_of_nodes())
M_l = np.dot(A, A)
S = np.dot(np.linalg.inv(M_g), M_l)
# s: \sigma_k
u, s, vt = lg.svds(S, k=self._d // 2)
sigma = np.diagflat(np.sqrt(s))
X1 = np.dot(u, sigma)
X2 = np.dot(vt.T, sigma)
# self._X = X2
self._X = np.concatenate((X1, X2), axis=1)
示例2: test_to_networkx
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import to_numpy_matrix [as 别名]
def test_to_networkx():
x = torch.Tensor([[1, 2], [3, 4]])
pos = torch.Tensor([[0, 0], [1, 1]])
edge_index = torch.tensor([[0, 1, 0], [1, 0, 0]])
edge_attr = torch.Tensor([1, 2, 3])
data = Data(x=x, pos=pos, edge_index=edge_index, weight=edge_attr)
for remove_self_loops in [True, False]:
G = to_networkx(data, node_attrs=['x', 'pos'], edge_attrs=['weight'],
remove_self_loops=remove_self_loops)
assert G.nodes[0]['x'] == [1, 2]
assert G.nodes[1]['x'] == [3, 4]
assert G.nodes[0]['pos'] == [0, 0]
assert G.nodes[1]['pos'] == [1, 1]
if remove_self_loops:
assert nx.to_numpy_matrix(G).tolist() == [[0, 1], [2, 0]]
else:
assert nx.to_numpy_matrix(G).tolist() == [[3, 1], [2, 0]]
示例3: test_to_networkx_undirected
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import to_numpy_matrix [as 别名]
def test_to_networkx_undirected():
x = torch.Tensor([[1, 2], [3, 4]])
pos = torch.Tensor([[0, 0], [1, 1]])
edge_index = torch.tensor([[0, 1, 0], [1, 0, 0]])
edge_attr = torch.Tensor([1, 2, 3])
data = Data(x=x, pos=pos, edge_index=edge_index, weight=edge_attr)
for remove_self_loops in [True, False]:
G = to_networkx(data, node_attrs=['x', 'pos'], edge_attrs=['weight'],
remove_self_loops=remove_self_loops,
to_undirected=True)
assert G.nodes[0]['x'] == [1, 2]
assert G.nodes[1]['x'] == [3, 4]
assert G.nodes[0]['pos'] == [0, 0]
assert G.nodes[1]['pos'] == [1, 1]
if remove_self_loops:
assert nx.to_numpy_matrix(G).tolist() == [[0, 2], [2, 0]]
else:
assert nx.to_numpy_matrix(G).tolist() == [[3, 2], [2, 0]]
示例4: get_observation
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import to_numpy_matrix [as 别名]
def get_observation(self,feature='deg'):
"""
:return: ob, where ob['adj'] is E with dim b x n x n and ob['node']
is F with dim 1 x n x m. NB: n = node_num + node_type_num
"""
n = self.graph.number_of_nodes()
F = np.zeros((1, self.max_node, 1))
F[0,:n+1,0] = 1
E = np.zeros((1, self.max_node, self.max_node))
E[0,:n,:n] = np.asarray(nx.to_numpy_matrix(self.graph))[np.newaxis,:,:]
E[0,:n+1,:n+1] += np.eye(n+1)
ob = {}
if self.is_normalize:
E = self.normalize_adj(E)
ob['adj'] = E
ob['node'] = F
return ob
示例5: __init__
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import to_numpy_matrix [as 别名]
def __init__(self, G_list, max_num_node=None, max_prev_node=None, iteration=20000):
self.adj_all = []
self.len_all = []
for G in G_list:
self.adj_all.append(np.asarray(nx.to_numpy_matrix(G)))
self.len_all.append(G.number_of_nodes())
if max_num_node is None:
self.n = max(self.len_all)
else:
self.n = max_num_node
if max_prev_node is None:
print('calculating max previous node, total iteration: {}'.format(iteration))
self.max_prev_node = max(self.calc_max_prev_node(iter=iteration))
print('max previous node: {}'.format(self.max_prev_node))
else:
self.max_prev_node = max_prev_node
# self.max_prev_node = max_prev_node
# # sort Graph in descending order
# len_batch_order = np.argsort(np.array(self.len_all))[::-1]
# self.len_all = [self.len_all[i] for i in len_batch_order]
# self.adj_all = [self.adj_all[i] for i in len_batch_order]
示例6: networkx_to_adjacency
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import to_numpy_matrix [as 别名]
def networkx_to_adjacency(graph):
"""Simple wrapper for graph to adjacency matrix.
Parameters
----------
graph : object
The networkx graph object.
Returns
-------
matrix : array
The numpy adjacency matrix.
"""
msg = 'Please pass an networkx graph object, not a {}'.format(type(graph))
assert isinstance(graph, nx.Graph), msg
atomic_numbers = list(dict(graph.nodes('atomic_number')).values())
adjacency = np.asarray(nx.to_numpy_matrix(graph, dtype='f'))
assert np.shape(adjacency) == (len(atomic_numbers), len(atomic_numbers))
adjacency += np.diag(atomic_numbers)
return adjacency
示例7: edge_transform
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import to_numpy_matrix [as 别名]
def edge_transform(self, g):
e = {}
for n1, n2, d in g.edges_iter(data=True):
e_t = []
e_t += [float(x) for x in list(d.values())]
e[(n1, n2)] = e_t
return nx.to_numpy_matrix(g), e
示例8: edge_transform
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import to_numpy_matrix [as 别名]
def edge_transform(self, g):
e = {}
for n1, n2, d in g.edges_iter(data=True):
e_t = []
e_t += [1]
e[(n1, n2)] = e_t
return nx.to_numpy_matrix(g), e
示例9: edge_transform
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import to_numpy_matrix [as 别名]
def edge_transform(self, g):
e = {}
for n1, n2, d in g.edges_iter(data=True):
e_t = []
e_t.append(d['label'])
e[(n1, n2)] = e_t
return nx.to_numpy_matrix(g), e
示例10: gen_data
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import to_numpy_matrix [as 别名]
def gen_data(min_num_nodes=20,
max_num_nodes=100,
num_graphs=10,
node_emb_dim=10,
graph_emb_dim=2,
edge_prob=0.5,
seed=123):
"""
Generate synthetic graph data for graph regression, i.e., given node
embedding and graph structure as input, predict a graph embedding
as output.
N.B.: modification to other tasks like node classification is straightforward
A single graph in your dataset should contin:
X: Node embedding, numpy array, shape N X D where N is # nodes
A: Graph structure, numpy array, shape N X N X E where E is # edge types
Y: Graph embedding, numpy array, shape N X O
"""
npr = np.random.RandomState(seed)
N = npr.randint(min_num_nodes, high=max_num_nodes+1, size=num_graphs)
data = []
for ii in range(num_graphs):
data_dict = {}
data_dict['X'] = npr.randn(N[ii], node_emb_dim)
# we assume # edge type = 1, but you can easily extend it to be more than 1
data_dict['A'] = np.expand_dims(
nx.to_numpy_matrix(
nx.fast_gnp_random_graph(N[ii], edge_prob, seed=npr.randint(1000))),
axis=2)
data_dict['Y'] = npr.randn(1, graph_emb_dim)
data += [data_dict]
return data
示例11: adjacency_unweighted
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import to_numpy_matrix [as 别名]
def adjacency_unweighted(segmentation, connectivity=CONNECTIVITY):
"""Computes the adjacency matrix of the Region Adjacency Graph.
Given an segmentation, this method constructs the constructs the
corresponding Region Adjacency Graphh (RAG). Each node in the RAG
represents a set of pixels with the same label in `segmentation`. An edge
between two nodes exist if the nodes are spatial connected.
Args:
segmentation: The segmentation.
connectivity: Integer. Pixels with a squared distance less than
`connectivity` from each other are considered adjacent (optional).
Returns:
An adjacent matrix with shape [num_segments, num_segments].
"""
def _adjacency(segmentation):
graph = RAG(segmentation, connectivity=connectivity)
# Simply return the unweighted adjacency matrix of the computed graph.
return nx.to_numpy_matrix(graph, dtype=np.float32)
return tf.py_func(
_adjacency, [segmentation], tf.float32, stateful=False,
name='adjacency_unweighted')
示例12: makeStochasticABFromNetworkxGraph
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import to_numpy_matrix [as 别名]
def makeStochasticABFromNetworkxGraph(self, nxgraph, alpha,
beta): # takes a nxgraph, alpha, and beta. Returns stochastic initMatrix.
adjMatrix = nx.to_numpy_matrix(nxgraph) # return graph adj matrix as a np matrix
n = adjMatrix.shape[0] # get num nodes
init = InitMatrix(n)
init.make()
for i in range(n):
for j in range(n):
init.setValue(adjMatrix[i, j], i, j)
init.makeStochasticAB(alpha, beta)
return init # there is no gaurentee of self loops since these are other graph types generated as seeds
示例13: makeFromNetworkxGraph
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import to_numpy_matrix [as 别名]
def makeFromNetworkxGraph(self, nxgraph): # takes a nxgraph, Returns initMatrix.
adjMatrix = nx.to_numpy_matrix(nxgraph) # return graph adj matrix as a np matrix
n = adjMatrix.shape[0] # get num nodes
init = InitMatrix(n)
init.make()
for i in range(n):
for j in range(n):
init.setValue(adjMatrix[i, j], i, j)
return init # there is no gaurentee of self loops since these are other graph types generated as seeds
示例14: test_encode_decode_adj
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import to_numpy_matrix [as 别名]
def test_encode_decode_adj():
######## code test ###########
G = nx.ladder_graph(5)
G = nx.grid_2d_graph(20,20)
G = nx.ladder_graph(200)
G = nx.karate_club_graph()
G = nx.connected_caveman_graph(2,3)
print(G.number_of_nodes())
adj = np.asarray(nx.to_numpy_matrix(G))
G = nx.from_numpy_matrix(adj)
#
start_idx = np.random.randint(adj.shape[0])
x_idx = np.array(bfs_seq(G, start_idx))
adj = adj[np.ix_(x_idx, x_idx)]
print('adj\n',adj)
adj_output = encode_adj(adj,max_prev_node=5)
print('adj_output\n',adj_output)
adj_recover = decode_adj(adj_output,max_prev_node=5)
print('adj_recover\n',adj_recover)
print('error\n',np.amin(adj_recover-adj),np.amax(adj_recover-adj))
adj_output = encode_adj_flexible(adj)
for i in range(len(adj_output)):
print(len(adj_output[i]))
adj_recover = decode_adj_flexible(adj_output)
print(adj_recover)
print(np.amin(adj_recover-adj),np.amax(adj_recover-adj))
示例15: test_encode_decode_adj_full
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import to_numpy_matrix [as 别名]
def test_encode_decode_adj_full():
########### code test #############
# G = nx.ladder_graph(10)
G = nx.karate_club_graph()
# get bfs adj
adj = np.asarray(nx.to_numpy_matrix(G))
G = nx.from_numpy_matrix(adj)
start_idx = np.random.randint(adj.shape[0])
x_idx = np.array(bfs_seq(G, start_idx))
adj = adj[np.ix_(x_idx, x_idx)]
adj_output, adj_len = encode_adj_full(adj)
print('adj\n',adj)
print('adj_output[0]\n',adj_output[:,:,0])
print('adj_output[1]\n',adj_output[:,:,1])
# print('adj_len\n',adj_len)
adj_recover = decode_adj_full(adj_output)
print('adj_recover\n', adj_recover)
print('error\n',adj_recover-adj)
print('error_sum\n',np.amax(adj_recover-adj), np.amin(adj_recover-adj))
########## use pytorch dataloader