本文整理汇总了Python中networkx.common_neighbors函数的典型用法代码示例。如果您正苦于以下问题:Python common_neighbors函数的具体用法?Python common_neighbors怎么用?Python common_neighbors使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了common_neighbors函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: predict
def predict(u, v):
cnbors = list(nx.common_neighbors(G, u, v))
mult_val = G.degree(u) * G.degree(v)
if mult_val == 0:
return 0
else:
return len(cnbors)/ mult_val
示例2: common_neighbors
def common_neighbors(features, G):
nb_common_neighbors = []
for i in range(features.shape[0]):
a = features['From'][i]
b = features['To'][i]
nb_common_neighbors.append(len(sorted(nx.common_neighbors(G, a, b)))) # ajoute le nombre de voisins communs
return nb_common_neighbors
示例3: predict
def predict(u, v):
Cu = _community(G, u, community)
Cv = _community(G, v, community)
cnbors = list(nx.common_neighbors(G, u, v))
neighbors = (sum(_community(G, w, community) == Cu for w in cnbors)
if Cu == Cv else 0)
return len(cnbors) + neighbors
示例4: get_edge_embeddedness
def get_edge_embeddedness(graph, pairs):
c = Column(1, 'numerical')
value = dict()
for pair in pairs:
value[pair] = len(list(nx.common_neighbors(graph, pair[0], pair[1])))
c.value = value
return c
示例5: __init__
def __init__(self, preparedParameters, filePathResults, filePathAnalyseResult, topRank):
print "Starting Analysing the results", datetime.today()
absFilePath = filePathResults
absfilePathAnalyseResult = filePathAnalyseResult #FormatingDataSets.get_abs_file_path(filePathAnalyseResult)
fResult = open(absFilePath, 'r')
with open(absfilePathAnalyseResult, 'w') as fnodes:
self.success = 0
element = 0
for line in fResult:
element = element+1
FormatingDataSets.printProgressofEvents(element, topRank, "Analysing the results: ")
cols = line.strip().replace('\n','').split('\t')
if len(list(networkx.common_neighbors(preparedParameters.testGraph, cols[len(cols)-2] , cols[len(cols)-1] ))) != 0:
self.success = self.success + 1
fnodes.write(cols[len(cols)-2] + '\t' + cols[len(cols)-1] + '\t' + 'SUCCESS \r\n')
else:
fnodes.write(cols[len(cols)-2] + '\t' + cols[len(cols)-1] + '\t' + 'FAILED \r\n')
if element == topRank:
break
result = float(self.success) / float(topRank) *100
strResult = 'Final Result: \t' + str(result) + '%'
fnodes.write(strResult)
fnodes.write('\n#\t'+str(self.success))
fnodes.close()
print "Analysing the results finished", datetime.today()
示例6: simpleProximity
def simpleProximity(self, s, t): #s and t are the mip node IDs, NOT user/obj ids
proximity = 0.0
sharedWeight = 0.0
for node in nx.common_neighbors(self.mip, s, t):
sharedWeight = sharedWeight + self.mip[s][node]['weight'] + self.mip[t][node]['weight'] #the weight of the path connecting s and t through the current node
proximity = sharedWeight/(self.mip.degree(s, weight = 'weight')+self.mip.degree(t, weight = 'weight')+0.000000000001)
return proximity
示例7: get_TimeofLinks
def get_TimeofLinks(self, graph, node1, node2):
result = []
for node in networkx.common_neighbors(graph, node1, node2):
for n,d in graph.nodes(data=True):
if n == node:
result.append(d['time'])
result.sort(reverse=True)
return result
示例8: adamicAdarProximity
def adamicAdarProximity(self, s, t):
proximity = 0.0
for node in nx.common_neighbors(self.mip, s, t):
weights = self.mip[s][node]['weight'] + self.mip[t][node]['weight'] #the weight of the path connecting s and t through the current node
if weights!=0: #0 essentially means no connection
# print 'weights = '+str(weights)
# print 'degree = '+str(self.mip.degree(node, weight = 'weight'))
proximity = proximity + (weights*(1/(math.log(self.mip.degree(node, weight = 'weight'))+0.00000000000000000000000001))) #gives more weight to "rare" shared neighbors, adding small number to avoid dividing by zero
# print 'proximity = '+str(proximity)
return proximity
示例9: get_BagofWords
def get_BagofWords(self, graph, node1, node2):
result = set()
for node in networkx.common_neighbors(graph, node1, node2):
for n,d in graph.nodes(data=True):
if n == node:
for keyword in ast.literal_eval(d['keywords']):
result.add(keyword)
return result
示例10: get_adamic_adar_score
def get_adamic_adar_score(graph, pairs):
c = Column(1, 'numerical')
value = dict()
for pair in pairs:
common_nei = nx.common_neighbors(graph, pair[0], pair[1])
score = 0.0
for n in common_nei:
score += 1.0 / math.log(len(graph.neighbors(n)) + 1)
value[pair] = score
c.value = value
return c
示例11: generateDataForCalculate
def generateDataForCalculate(self):
if self.trainnigGraph == None:
self.generating_Training_Graph()
_nodes = sorted(self.trainnigGraph.nodes())
adb = Base(self.filePathTrainingGraph + ".calc.pdl")
adb.create('pairNodes', 'common', 'time', 'domain' )
for node in sorted(_nodes):
othernodes = set(n for n in _nodes if n > node)
for other in othernodes:
common = set(networkx.common_neighbors(self.trainnigGraph, node, other))
arestas = self.trainnigGraph.edges([node, other], True)
示例12: merge
def merge(G,edge):
"""Returns a new graph with edge merged, and the new node containing the
information lost in the merge. The weights from common neighbors
are added together, a la Stoer-Wagner algorithm."""
if G.node[edge[1]]['type'] == 'login' or G.node[edge[1]]['type'] == 'email':
edge = edge[::-1] # If login/email is on the right, flip the order, so it's always on the left
nx.set_node_attributes(G,'list',{edge[0]:G.node[edge[0]]['list']+[edge[1]]})
J = nx.contracted_edge(G,(edge[0],edge[1]),self_loops = False) #Contract edge without self-loop
# Weight stuff
N = nx.common_neighbors(G,edge[0],edge[1]) #find common nodes
for i in N:
J[i][edge[0]]['weight'] = G[edge[0]][i]['weight'] + G[edge[1]][i]['weight'] #modify the weight after contraction
return J
示例13: graph_stats
def graph_stats(distance_couple, net):
distances = []
common_neighbors = []
jaccard = []
adamic = []
edge_bet = []
edge_betweeness = nx.edge_betweenness_centrality(net)
for couple in distance_couple:
distances.append(couple[1])
common_neighbors.append(len(list(nx.common_neighbors(net, couple[0][0], couple[0][1]))))
jaccard.append(list(nx.jaccard_coefficient(net, [(couple[0][0], couple[0][1])]))[0][2])
adamic.append(list(nx.adamic_adar_index(net, [(couple[0][0], couple[0][1])]))[0][2])
try:
edge_bet.append(edge_betweeness[couple[0]])
except KeyError:
edge_bet.append(edge_betweeness[(couple[0][1], couple[0][0])])
r_dist = 10.0/max(distances)
r_n = 10.0/max(common_neighbors)
r_j = 10.0/max(jaccard)
r_a = 10.0/max(adamic)
r_e = 10.0/max(edge_bet)
distances = [j * r_dist for j in distances]
common_neighbors = [j * r_n for j in common_neighbors]
jaccard = [j * r_j for j in jaccard]
adamic = [j * r_a for j in adamic]
edge_bet = [j * r_e for j in edge_bet]
plt.loglog(common_neighbors, color='b', label='common_neighbors')
plt.loglog(distances, color='r', label='distances')
plt.savefig('node_similarity/stats_cm.png', format='png')
plt.close()
plt.loglog(jaccard, color='b', label='jaccard')
plt.loglog(distances, color='r', label='distances')
plt.savefig('node_similarity/stats_j.png', format='png')
plt.close()
plt.loglog(adamic, color='b', label='adamic')
plt.loglog(distances, color='r', label='distances')
plt.savefig('node_similarity/stats_aa.png', format='png')
plt.close()
plt.loglog(edge_bet, color='b', label='edge betwenness')
plt.loglog(distances, color='r', label='distances')
plt.savefig('node_similarity/stats_eb.png', format='png')
plt.close()
示例14: get_TimeofLinks
def get_TimeofLinks(self, graph, node1, node2):
result = []
for node in networkx.common_neighbors(graph, node1, node2):
if node in self.times:
if self.debugar:
print "already found the time for paper ", node
else:
if self.debugar:
print "rescuing time from paper: ", str(node)
paper = list(d for n,d in graph.nodes(data=True) if d['node_type'] == 'E' and n == node )
if self.debugar:
print paper[0]['time']
self.times[node] = paper[0]['time']
result.append(self.times[node])
result.sort(reverse=True)
return result
示例15: calculateStability
def calculateStability(self):
balanceTriangle = 0
totalTriangles = 0
for edge, sign in self.edgeSignDict.iteritems():
node1 = int(float(edge.split(",")[0]))
node2 = int(float(edge.split(",")[1]))
commonNeigh = sorted(nx.common_neighbors(self.graph, node1, node2))
for inode in commonNeigh:
sign1n = self.graph.get_edge_data(node1, inode, default={"weight": 10})["weight"]
sign2n = self.graph.get_edge_data(node2, inode, default={"weight": 10})["weight"]
sign12 = self.graph.get_edge_data(node1, node2, default={"weight": 10})["weight"]
mul = sign1n * sign2n * sign12
if mul > 0 and mul < 10:
balanceTriangle += 1
# if (sign1n*sign2n*sign12) != 0:
totalTriangles += 1
print "Balance percentage: " + str((1.0 * balanceTriangle) / totalTriangles)