[docs]defhits(G,max_iter=100,tol=1.0e-8,nstart=None,normalized=True):"""Return HITS hubs and authorities values for nodes. The HITS algorithm computes two numbers for a node. Authorities estimates the node value based on the incoming links. Hubs estimates the node value based on outgoing links. Parameters ---------- G : graph A NetworkX graph max_iter : interger, optional Maximum number of iterations in power method. tol : float, optional Error tolerance used to check convergence in power method iteration. nstart : dictionary, optional Starting value of each node for power method iteration. normalized : bool (default=True) Normalize results by the sum of all of the values. Returns ------- (hubs,authorities) : two-tuple of dictionaries Two dictionaries keyed by node containing the hub and authority values. Examples -------- >>> G=nx.path_graph(4) >>> h,a=nx.hits(G) Notes ----- The eigenvector calculation is done by the power iteration method and has no guarantee of convergence. The iteration will stop after max_iter iterations or an error tolerance of number_of_nodes(G)*tol has been reached. The HITS algorithm was designed for directed graphs but this algorithm does not check if the input graph is directed and will execute on undirected graphs. References ---------- .. [1] A. Langville and C. Meyer, "A survey of eigenvector methods of web information retrieval." http://citeseer.ist.psu.edu/713792.html .. [2] Jon Kleinberg, Authoritative sources in a hyperlinked environment Journal of the ACM 46 (5): 604-32, 1999. doi:10.1145/324133.324140. http://www.cs.cornell.edu/home/kleinber/auth.pdf. """iftype(G)==nx.MultiGraphortype(G)==nx.MultiDiGraph:raiseException("hits() not defined for graphs with multiedges.")iflen(G)==0:return{},{}# choose fixed starting vector if not givenifnstartisNone:h=dict.fromkeys(G,1.0/G.number_of_nodes())else:h=nstart# normalize starting vectors=1.0/sum(h.values())forkinh:h[k]*=si=0whileTrue:# power iteration: make up to max_iter iterationshlast=hh=dict.fromkeys(hlast.keys(),0)a=dict.fromkeys(hlast.keys(),0)# this "matrix multiply" looks odd because it is# doing a left multiply a^T=hlast^T*Gforninh:fornbrinG[n]:a[nbr]+=hlast[n]*G[n][nbr].get('weight',1)# now multiply h=Gaforninh:fornbrinG[n]:h[n]+=a[nbr]*G[n][nbr].get('weight',1)# normalize vectors=1.0/max(h.values())forninh:h[n]*=s# normalize vectors=1.0/max(a.values())fornina:a[n]*=s# check convergence, l1 normerr=sum([abs(h[n]-hlast[n])forninh])iferr<tol:breakifi>max_iter:raiseNetworkXError(\
"HITS: power iteration failed to converge in %d iterations."%(i+1))i+=1ifnormalized:s=1.0/sum(a.values())fornina:a[n]*=ss=1.0/sum(h.values())forninh:h[n]*=sreturnh,a

[docs]defhits_scipy(G,max_iter=100,tol=1.0e-6,normalized=True):"""Return HITS hubs and authorities values for nodes. The HITS algorithm computes two numbers for a node. Authorities estimates the node value based on the incoming links. Hubs estimates the node value based on outgoing links. Parameters ---------- G : graph A NetworkX graph max_iter : interger, optional Maximum number of iterations in power method. tol : float, optional Error tolerance used to check convergence in power method iteration. nstart : dictionary, optional Starting value of each node for power method iteration. normalized : bool (default=True) Normalize results by the sum of all of the values. Returns ------- (hubs,authorities) : two-tuple of dictionaries Two dictionaries keyed by node containing the hub and authority values. Examples -------- >>> G=nx.path_graph(4) >>> h,a=nx.hits(G) Notes ----- This implementation uses SciPy sparse matrices. The eigenvector calculation is done by the power iteration method and has no guarantee of convergence. The iteration will stop after max_iter iterations or an error tolerance of number_of_nodes(G)*tol has been reached. The HITS algorithm was designed for directed graphs but this algorithm does not check if the input graph is directed and will execute on undirected graphs. References ---------- .. [1] A. Langville and C. Meyer, "A survey of eigenvector methods of web information retrieval." http://citeseer.ist.psu.edu/713792.html .. [2] Jon Kleinberg, Authoritative sources in a hyperlinked environment Journal of the ACM 46 (5): 604-632, 1999. doi:10.1145/324133.324140. http://www.cs.cornell.edu/home/kleinber/auth.pdf. """try:importscipy.sparseimportnumpyasnpexceptImportError:raiseImportError(\
"hits_scipy() requires SciPy: http://scipy.org/")iflen(G)==0:return{},{}M=nx.to_scipy_sparse_matrix(G,nodelist=G.nodes())(n,m)=M.shape# should be squareA=M.T*M# authority matrixx=scipy.ones((n,1))/n# initial guess# power iteration on authority matrixi=0whileTrue:xlast=xx=A*xx=x/x.max()# check convergence, l1 normerr=scipy.absolute(x-xlast).sum()iferr<tol:breakifi>max_iter:raiseNetworkXError(\
"HITS: power iteration failed to converge in %d iterations."%(i+1))i+=1a=np.asarray(x).flatten()# h=M*ah=np.asarray(M*a).flatten()ifnormalized:h=h/h.sum()a=a/a.sum()hubs=dict(zip(G.nodes(),map(float,h)))authorities=dict(zip(G.nodes(),map(float,a)))returnhubs,authorities

# fixture for nose testsdefsetup_module(module):fromnoseimportSkipTesttry:importnumpyexcept:raiseSkipTest("NumPy not available")try:importscipyexcept:raiseSkipTest("SciPy not available")