本文整理匯總了Python中networkx.to_scipy_sparse_matrix方法的典型用法代碼示例。如果您正苦於以下問題:Python networkx.to_scipy_sparse_matrix方法的具體用法?Python networkx.to_scipy_sparse_matrix怎麽用?Python networkx.to_scipy_sparse_matrix使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類networkx
的用法示例。
在下文中一共展示了networkx.to_scipy_sparse_matrix方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: learn_embedding
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import to_scipy_sparse_matrix [as 別名]
def learn_embedding(self):
graph = self.g.G
graph = graph.to_undirected()
t1 = time()
A = nx.to_scipy_sparse_matrix(graph)
# print(np.sum(A.todense(), axis=0))
normalize(A, norm='l1', axis=1, copy=False)
I_n = sp.eye(graph.number_of_nodes())
I_min_A = I_n - A
print(I_min_A)
u, s, vt = lg.svds(I_min_A, k=self._d + 1, which='SM')
t2 = time()
self._X = vt.T
self._X = self._X[:, 1:]
return self._X, (t2 - t1)
# I_n = sp.eye(graph.number_of_nodes())
示例2: learn_embedding
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import to_scipy_sparse_matrix [as 別名]
def learn_embedding(self, graph=None, edge_f=None,
is_weighted=False, no_python=False):
if not graph and not edge_f:
raise Exception('graph/edge_f needed')
if not graph:
graph = graph_util.loadGraphFromEdgeListTxt(edge_f)
graph = graph.to_undirected()
t1 = time()
A = nx.to_scipy_sparse_matrix(graph)
normalize(A, norm='l1', axis=1, copy=False)
I_n = sp.eye(graph.number_of_nodes())
I_min_A = I_n - A
try:
u, s, vt = lg.svds(I_min_A, k=self._d + 1, which='SM')
except:
u = np.random.randn(A.shape[0], self._d + 1)
s = np.random.randn(self._d + 1, self._d + 1)
vt = np.random.randn(self._d + 1, A.shape[0])
t2 = time()
self._X = vt.T
self._X = self._X[:, 1:]
return self._X, (t2 - t1)
示例3: forceatlas2_networkx_layout
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import to_scipy_sparse_matrix [as 別名]
def forceatlas2_networkx_layout(self, G, pos=None, iterations=100, weight_attr=None):
import networkx
try:
import cynetworkx
except ImportError:
cynetworkx = None
assert (
isinstance(G, networkx.classes.graph.Graph)
or (cynetworkx and isinstance(G, cynetworkx.classes.graph.Graph))
), "Not a networkx graph"
assert isinstance(pos, dict) or (pos is None), "pos must be specified as a dictionary, as in networkx"
M = networkx.to_scipy_sparse_matrix(G, dtype='f', format='lil', weight=weight_attr)
if pos is None:
l = self.forceatlas2(M, pos=None, iterations=iterations)
else:
poslist = numpy.asarray([pos[i] for i in G.nodes()])
l = self.forceatlas2(M, pos=poslist, iterations=iterations)
return dict(zip(G.nodes(), l))
# A layout for igraph.
#
# This function returns an igraph layout
示例4: parse_cora_sparse
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import to_scipy_sparse_matrix [as 別名]
def parse_cora_sparse():
path = "%s/../data/cora/" % (current_dir,)
features, labels, id2index = _parse_cora_features_labels()
n_papers = len(id2index)
graph = nx.Graph()
with open(path + 'cora.cites', 'r') as f:
for line in f.xreadlines():
items = line.strip().split('\t')
tail = id2index[items[0]]
head = id2index[items[1]]
graph.add_edge(head, tail)
adj = nx.to_scipy_sparse_matrix(graph, format='csr')
return adj.astype('float32'), features.astype('float32'), labels.astype('int32')
示例5: learn_embedding
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import to_scipy_sparse_matrix [as 別名]
def learn_embedding(self, graph=None, edge_f=None,
is_weighted=False, no_python=False):
if not graph and not edge_f:
raise Exception('graph/edge_f needed')
if not graph:
graph = graph_util.loadGraphFromEdgeListTxt(edge_f)
graph = graph.to_undirected()
t1 = time()
A = nx.to_scipy_sparse_matrix(graph)
normalize(A, norm='l1', axis=1, copy=False)
I_n = sp.eye(len(graph.nodes))
I_min_A = I_n - A
u, s, vt = lg.svds(I_min_A, k=self._d + 1, which='SM')
t2 = time()
self._X = vt.T
self._X = self._X[:, 1:]
return self._X.real, (t2 - t1)
示例6: convert_from_geodataframe
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import to_scipy_sparse_matrix [as 別名]
def convert_from_geodataframe(gdf):
"""
Convert a GeoDataFrame to other types representing the contiguity relation
of the GeoDataFrame's areas.
Parameters
----------
gdf : GeoDataFrame
Returns
-------
other_formats : tuple
The 1st entry is a sparse adjacency matrix of type
:class:`scipy.sparse.csr_matrix`.
The 2nd entry is a networkx graph.
The 3rd entry is a dict. Each key is an area and each value is an
iterable of the key area's neighbors.
The 4th entry is a PySAL W object.
"""
w = weights.Rook.from_dataframe(gdf)
graph = w.to_networkx()
adj = nx.to_scipy_sparse_matrix(graph)
neighbor_dict = w.neighbors
return adj, graph, neighbor_dict, w
示例7: prepare_params
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import to_scipy_sparse_matrix [as 別名]
def prepare_params(g, data):
params = {}
params['infeats'] = data.features.astype('float32') # Only support float32 as feature for now
# Generate adjacency matrix
adjacency = nx.to_scipy_sparse_matrix(g)
params['g_data'] = adjacency.data.astype('float32')
params['indices'] = adjacency.indices.astype('int32')
params['indptr'] = adjacency.indptr.astype('int32')
# Normalization w.r.t. node degrees
degs = [g.in_degree[i] for i in range(g.number_of_nodes())]
params['norm'] = np.power(degs, -0.5).astype('float32')
params['norm'] = params['norm'].reshape((params['norm'].shape[0], 1))
return params
示例8: __init__
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import to_scipy_sparse_matrix [as 別名]
def __init__(self, transform=None):
super(KarateClub, self).__init__('.', transform, None, None)
G = nx.karate_club_graph()
adj = nx.to_scipy_sparse_matrix(G).tocoo()
row = torch.from_numpy(adj.row.astype(np.int64)).to(torch.long)
col = torch.from_numpy(adj.col.astype(np.int64)).to(torch.long)
edge_index = torch.stack([row, col], dim=0)
data = Data(edge_index=edge_index)
data.num_nodes = edge_index.max().item() + 1
data.x = torch.eye(data.num_nodes, dtype=torch.float)
y = [0 if G.nodes[i]['club'] == 'Mr. Hi' else 1 for i in G.nodes]
data.y = torch.tensor(y)
self.data, self.slices = self.collate([data])
示例9: learn_embedding
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import to_scipy_sparse_matrix [as 別名]
def learn_embedding(self, graph=None, edge_f=None,
is_weighted=False, no_python=False):
if not graph and not edge_f:
raise Exception('graph/edge_f needed')
if not graph:
graph = graph_util.loadGraphFromEdgeListTxt(edge_f)
t1 = time()
# A = nx.to_scipy_sparse_matrix(graph)
# I = sp.eye(graph.number_of_nodes())
# M_g = I - self._beta*A
# M_l = self._beta*A
A = nx.to_numpy_matrix(graph)
M_g = np.eye(len(graph.nodes)) - self._beta * A
M_l = self._beta * A
S = np.dot(np.linalg.inv(M_g), M_l)
u, s, vt = lg.svds(S, k=self._d // 2)
X1 = np.dot(u, np.diag(np.sqrt(s)))
X2 = np.dot(vt.T, np.diag(np.sqrt(s)))
t2 = time()
self._X = np.concatenate((X1, X2), axis=1)
p_d_p_t = np.dot(u, np.dot(np.diag(s), vt))
eig_err = np.linalg.norm(p_d_p_t - S)
print('SVD error (low rank): %f' % eig_err)
return self._X, (t2 - t1)
示例10: test_identity_graph_matrix
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import to_scipy_sparse_matrix [as 別名]
def test_identity_graph_matrix(self):
"Conversion from graph to sparse matrix to graph."
A = nx.to_scipy_sparse_matrix(self.G1)
self.identity_conversion(self.G1, A, nx.Graph())
示例11: test_identity_digraph_matrix
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import to_scipy_sparse_matrix [as 別名]
def test_identity_digraph_matrix(self):
"Conversion from digraph to sparse matrix to digraph."
A = nx.to_scipy_sparse_matrix(self.G2)
self.identity_conversion(self.G2, A, nx.DiGraph())
示例12: test_identity_weighted_graph_matrix
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import to_scipy_sparse_matrix [as 別名]
def test_identity_weighted_graph_matrix(self):
"""Conversion from weighted graph to sparse matrix to weighted graph."""
A = nx.to_scipy_sparse_matrix(self.G3)
self.identity_conversion(self.G3, A, nx.Graph())
示例13: test_identity_weighted_digraph_matrix
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import to_scipy_sparse_matrix [as 別名]
def test_identity_weighted_digraph_matrix(self):
"""Conversion from weighted digraph to sparse matrix to weighted digraph."""
A = nx.to_scipy_sparse_matrix(self.G4)
self.identity_conversion(self.G4, A, nx.DiGraph())
示例14: test_nodelist
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import to_scipy_sparse_matrix [as 別名]
def test_nodelist(self):
"""Conversion from graph to sparse matrix to graph with nodelist."""
P4 = path_graph(4)
P3 = path_graph(3)
nodelist = P3.nodes()
A = nx.to_scipy_sparse_matrix(P4, nodelist=nodelist)
GA = nx.Graph(A)
self.assert_equal(GA, P3)
# Make nodelist ambiguous by containing duplicates.
nodelist += [nodelist[0]]
assert_raises(nx.NetworkXError, nx.to_numpy_matrix, P3,
nodelist=nodelist)
示例15: test_format_keyword
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import to_scipy_sparse_matrix [as 別名]
def test_format_keyword(self):
WP4 = nx.Graph()
WP4.add_edges_from( (n,n+1,dict(weight=0.5,other=0.3))
for n in range(3) )
P4 = path_graph(4)
A = nx.to_scipy_sparse_matrix(P4, format='csr')
np_assert_equal(A.todense(),
nx.to_scipy_sparse_matrix(WP4,weight=None).todense())
A = nx.to_scipy_sparse_matrix(P4, format='csc')
np_assert_equal(A.todense(),
nx.to_scipy_sparse_matrix(WP4,weight=None).todense())
A = nx.to_scipy_sparse_matrix(P4, format='coo')
np_assert_equal(A.todense(),
nx.to_scipy_sparse_matrix(WP4,weight=None).todense())
A = nx.to_scipy_sparse_matrix(P4, format='bsr')
np_assert_equal(A.todense(),
nx.to_scipy_sparse_matrix(WP4,weight=None).todense())
A = nx.to_scipy_sparse_matrix(P4, format='lil')
np_assert_equal(A.todense(),
nx.to_scipy_sparse_matrix(WP4,weight=None).todense())
A = nx.to_scipy_sparse_matrix(P4, format='dia')
np_assert_equal(A.todense(),
nx.to_scipy_sparse_matrix(WP4,weight=None).todense())
A = nx.to_scipy_sparse_matrix(P4, format='dok')
np_assert_equal(A.todense(),
nx.to_scipy_sparse_matrix(WP4,weight=None).todense())