本文整理汇总了Python中networkx.pagerank_numpy函数的典型用法代码示例。如果您正苦于以下问题:Python pagerank_numpy函数的具体用法?Python pagerank_numpy怎么用?Python pagerank_numpy使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了pagerank_numpy函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: personal_page_rank
def personal_page_rank(self, p_vector, reverse=False):
'''
Personal_Page_Rank: Get the personal pagerank of the supplied input vector
Input:
- p_vector: A hash-map of input values for a selection (or all) nodes
(if supplied nodes aren't in the graph, they will be ignored)
Output:
- A vector of diffused heats in hash-map (key,value) format
'''
input_pvec = None
# without initializing this vector the initial probabilities will be flat
# and this will be equivalent to standard page rank
if p_vector:
input_pvec = {}
# doesn't seem to be necessary for a non-zero epsilon now, but
# leave this as a place holder
epsilon = 0.0
for node in self.G.nodes(data=False):
if node in p_vector:
input_pvec[node] = p_vector[node]
else:
input_pvec[node] = epsilon
if reverse:
return nx.pagerank_numpy(self.G_reversed, 0.85, input_pvec)
else:
return nx.pagerank_numpy(self.G, 0.85, input_pvec)
示例2: test_numpy_pagerank
def test_numpy_pagerank(self):
G = self.G
p = networkx.pagerank_numpy(G, alpha=0.9)
for n in G:
assert_almost_equal(p[n], G.pagerank[n], places=4)
personalize = dict((n, random.random()) for n in G)
p = networkx.pagerank_numpy(G, alpha=0.9, personalization=personalize)
示例3: main
def main():
disapprove, cooperate = build_graph(gdelt_data_iter())
# Computer pagerank for disapprove Graph node
print("Computing pagerank for disapprove graph")
pagerank1 = nx.pagerank_numpy(disapprove, alpha=0.90)
print("Computing pagerank for cooperate graph")
pagerank2 = nx.pagerank_numpy(cooperate, alpha=0.90)
max1 = max(pagerank1.values())
key1 = ''
key2 = ''
for key in pagerank1.keys():
if pagerank1[key] == max1:
key1 = key
max2 = max(pagerank2.values())
for key in pagerank2.keys():
if pagerank2[key] == max2:
key2 = key
with open('results/disapprove_graph_page_rank.csv', 'w') as f1:
for line in str(pagerank1):
f1.write(line)
with open('results/cooperate_graph_page_rank.csv', 'w') as f2:
for line in str(pagerank2):
f2.write(line)
print("Maximum Page rank for disapprove graph is: %s %s" % (key1, max1))
print("Maximum Page rank for cooperate graph is: %s %s" % (key2, max2))
示例4: test_numpy_pagerank
def test_numpy_pagerank(self):
try:
import numpy
except ImportError:
raise SkipTest('numpy not available.')
G=self.G
p=networkx.pagerank_numpy(G,alpha=0.9)
for n in G:
assert_almost_equal(p[n],G.pagerank[n],places=4)
personalize = dict((n,random.random()) for n in G)
p=networkx.pagerank_numpy(G,alpha=0.9, personalization=personalize)
示例5: pagerank
def pagerank(graph, weighted=True):
""" Pagerank algorithm with beta = 0.85.
If unweighted, then every outgoing edge is considered uniformly.
Otherwise, outgoing edges are weighted by their given weights.
Returns:
An array where the ith element corresponds to the pagerank score
of agent i in the trust graph.
"""
if weighted:
return np.array(nx.pagerank_numpy(graph).values())
else:
return np.array(nx.pagerank_numpy(graph, weight=None).values())
示例6: OrigPagerank
def OrigPagerank(self):
''' returns a 2d array containing the pagerank of the origin node for all edges
'''
probas = np.dot(
np.array(nx.pagerank_numpy(self).values(),dtype=float).reshape(-1,1),
np.ones((1,self.number_of_nodes())))
return probas
示例7: draw_graph
def draw_graph(nodes, edges, graphs_dir, default_lang='all'):
lang_graph = nx.MultiDiGraph()
lang_graph.add_nodes_from(nodes)
for edge in edges:
if edges[edge] == 0:
lang_graph.add_edge(edge[0], edge[1])
else:
lang_graph.add_edge(edge[0], edge[1], weight=float(edges[edge]), label=str(edges[edge]))
# print graph info in stdout
# degree centrality
print('-----------------\n\n')
print(default_lang)
print(nx.info(lang_graph))
try:
# When ties are associated to some positive aspects such as friendship or collaboration,
# indegree is often interpreted as a form of popularity, and outdegree as gregariousness.
DC = nx.degree_centrality(lang_graph)
max_dc = max(DC.values())
max_dc_list = [item for item in DC.items() if item[1] == max_dc]
except ZeroDivisionError:
max_dc_list = []
# https://ru.wikipedia.org/wiki/%D0%9A%D0%BE%D0%BC%D0%BF%D0%BB%D0%B5%D0%BA%D1%81%D0%BD%D1%8B%D0%B5_%D1%81%D0%B5%D1%82%D0%B8
print('maxdc', str(max_dc_list), sep=': ')
# assortativity coef
AC = nx.degree_assortativity_coefficient(lang_graph)
print('AC', str(AC), sep=': ')
# connectivity
print("Слабо-связный граф: ", nx.is_weakly_connected(lang_graph))
print("количество слабосвязанных компонент: ", nx.number_weakly_connected_components(lang_graph))
print("Сильно-связный граф: ", nx.is_strongly_connected(lang_graph))
print("количество сильносвязанных компонент: ", nx.number_strongly_connected_components(lang_graph))
print("рекурсивные? компоненты: ", nx.number_attracting_components(lang_graph))
print("число вершинной связности: ", nx.node_connectivity(lang_graph))
print("число рёберной связности: ", nx.edge_connectivity(lang_graph))
# other info
print("average degree connectivity: ", nx.average_degree_connectivity(lang_graph))
print("average neighbor degree: ", sorted(nx.average_neighbor_degree(lang_graph).items(),
key=itemgetter(1), reverse=True))
# best for small graphs, and our graphs are pretty small
print("pagerank: ", sorted(nx.pagerank_numpy(lang_graph).items(), key=itemgetter(1), reverse=True))
plt.figure(figsize=(16.0, 9.0), dpi=80)
plt.axis('off')
pos = graphviz_layout(lang_graph)
nx.draw_networkx_edges(lang_graph, pos, alpha=0.5, arrows=True)
nx.draw_networkx(lang_graph, pos, node_size=1000, font_size=12, with_labels=True, node_color='green')
nx.draw_networkx_edge_labels(lang_graph, pos, edges)
# saving file to draw it with dot-graphviz
# changing overall graph view, default is top-bottom
lang_graph.graph['graph'] = {'rankdir': 'LR'}
# marking with blue nodes with maximum degree centrality
for max_dc_node in max_dc_list:
lang_graph.node[max_dc_node[0]]['fontcolor'] = 'blue'
write_dot(lang_graph, os.path.join(graphs_dir, default_lang + '_links.dot'))
# plt.show()
plt.savefig(os.path.join(graphs_dir, 'python_' + default_lang + '_graph.png'), dpi=100)
plt.close()
示例8: getRandomPageRanks
def getRandomPageRanks(filename):
Ga=nx.read_graphml(sys.argv[1])
# create a copy of the graph and extract giant component
# get component size distribution
cc=nx.connected_components(Ga)
cc_dict={}
for x in range(0,len(cc)):
try:
cc_dict[len(cc[x])].append(x)
except KeyError:
cc_dict[len(cc[x])]=[]
cc_dict[len(cc[x])].append(x)
isolates=nx.isolates(Ga)
rg=nx.fast_gnp_random_graph(Ga.number_of_nodes(),2.0*Ga.number_of_edges()/(Ga.number_of_nodes()*(Ga.number_of_nodes()-1)))
c_rg=nx.average_clustering(rg)
rg_cc=nx.connected_component_subgraphs(rg)[0]
rg_asp=nx.algorithms.shortest_paths.generic.average_shortest_path_length(rg_cc)
p_rg=community.best_partition(rg_cc)
m_rg=community.modularity(p_rg,rg_cc)
pageranks = nx.pagerank_numpy(rg)
return pageranks
示例9: features_matrix
def features_matrix(graph, anchors, use_dist=True, use_pgrs=True,
use_pgr=True, use_comm=False, use_comm_centr=False):
node_feats = []
n = len(graph)
if use_dist:
dists = nx.all_pairs_shortest_path_length(graph)
if use_pgr:
pageranks = nx.pagerank_numpy(graph)
if use_pgrs:
pgr_anchor = [anchored_pagerank(graph, anchor) for anchor in anchors]
if use_comm_centr:
communicability_centrality = nx.communicability_centrality(graph)
if use_comm:
communicability = nx.communicability(graph)
for node in graph.nodes():
assert node == len(node_feats)
feats = []
if use_dist:
feats += [dists[node][anchor] for anchor in anchors]
if use_pgrs:
feats += [pgr[node]*n for pgr in pgr_anchor]
if use_pgr:
feats.append(pageranks[node]*n)
if use_comm_centr:
feats.append(communicability_centrality[node])
if use_comm:
feats += [communicability[node][anchor] for anchor in anchors]
node_feats.append(np.array(feats))
return node_feats
示例10: features_dict
def features_dict(graph, anchors, use_dist=True, use_pgrs=True,
use_pgr=True, use_comm=False, use_comm_centr=False):
node_feats = {}
n = len(graph)
if use_dist:
# dists = nx.all_pairs_shortest_path_length(graph)
dists = dists_to_anchors(graph, anchors)
if use_pgr:
pageranks = nx.pagerank_numpy(graph)
if use_pgrs:
# pgr_anchor = [anchored_pagerank(graph, anchor) for anchor in anchors]
pgr_anchor = pageranks_to_anchors(graph, anchors)
if use_comm_centr:
communicability_centrality = nx.communicability_centrality(graph)
if use_comm:
communicability = nx.communicability(graph)
for node in graph.nodes():
feats = []
if use_dist:
feats += [dists[node][anchor] for anchor in anchors]
if use_pgrs:
feats += [pgr_anchor[anchor][node]*n
for anchor in range(len(anchors))]
# feats += [pgr[node]*n for pgr in pgr_anchor]
if use_pgr:
feats.append(pageranks[node]*n)
if use_comm_centr:
feats.append(communicability_centrality[node])
if use_comm:
feats += [communicability[node][anchor] for anchor in anchors]
node_feats[node] = np.array(feats)
return node_feats
示例11: TargPagerank
def TargPagerank(self):
''' returns a 2d array containing the pagerank of the target node for all edges
'''
probas = np.dot(
np.ones((self.number_of_nodes(),1)),
np.array(nx.pagerank_numpy(self).values(),dtype=float).reshape(1,-1)
)
return probas
示例12: parse_nci
def parse_nci(graph_name='nci1.graph', with_structural_features=False):
path = "%s/data/nci/" % (current_dir,)
if graph_name == 'nci1.graph':
maxval = 37
elif graph_name == 'nci109.graph':
maxval = 38
with open(path+graph_name,'r') as f:
raw = cp.load(f)
n_classes = 2
n_graphs = len(raw['graph'])
A = []
rX = []
Y = np.zeros((n_graphs, n_classes), dtype='int32')
for i in range(n_graphs):
# Set label
Y[i][raw['labels'][i]] = 1
# Parse graph
G = raw['graph'][i]
n_nodes = len(G)
a = np.zeros((n_nodes,n_nodes), dtype='float32')
x = np.zeros((n_nodes,maxval), dtype='float32')
for node, meta in G.iteritems():
x[node,meta['label'][0] - 1] = 1
for neighbor in meta['neighbors']:
a[node, neighbor] = 1
A.append(a)
rX.append(x)
if with_structural_features:
import networkx as nx
for i in range(len(rX)):
struct_feat = np.zeros((rX[i].shape[0], 3))
# degree
struct_feat[:,0] = A[i].sum(1)
G = nx.from_numpy_matrix(A[i])
# pagerank
prank = nx.pagerank_numpy(G)
struct_feat[:,1] = np.asarray([prank[k] for k in range(A[i].shape[0])])
# clustering
clust = nx.clustering(G)
struct_feat[:,2] = np.asarray([clust[k] for k in range(A[i].shape[0])])
rX[i] = np.hstack((rX[i],struct_feat))
return A, rX, Y
示例13: get_pagerank
def get_pagerank(self, damping_factor=0.85):
""" Computes normalized page rank of current graph
"""
pagerank = np.array(nx.pagerank_numpy(self.graph.graph, alpha=damping_factor)).tolist()
vals = list(pagerank.values())
vals /= npl.norm(vals)
return vals
示例14: test_numpy_pagerank
def test_numpy_pagerank(self):
try:
import numpy
except ImportError:
raise SkipTest('numpy not available.')
G=self.G
p=networkx.pagerank_numpy(G,alpha=0.9)
for n in G:
assert_almost_equal(p[n],G.pagerank[n],places=4)
示例15: test_numpy_pagerank
def test_numpy_pagerank(self):
G=self.G
try:
p=networkx.pagerank_numpy(G,alpha=0.9,
tol=1.e-08)
for (a,b) in zip(p,self.G.pagerank):
assert_almost_equal(a,b)
except ImportError:
print "Skipping pagerank_numpy test"