igraph-help
[Top][All Lists]

## Re: [igraph] Re: graph.knn in python

 From: Tamás Nepusz Subject: Re: [igraph] Re: graph.knn in python Date: Mon, 7 Feb 2011 23:14:34 +0100

```Hi Simone,

> can this be considered a valid substitute of the knn function?
>
> vs = g.vs()
> vcount = g.vcount()
> neisets = [set(g.neighbors(i)) for i in xrange(vcount)]
> deg = [g.degree(i) for i in xrange(vcount)]
> for u in vs:
>       neiavedeg = []
>       for v in neisets[u.index]:
>               neiavedeg.append(deg[v])
>       u["neideg"] = (sum(neiavedeg) / float(len(neiavedeg)) if len(neiavedeg)
> > 0 else 0)
I've simplified your code a bit:

deg = g.degree()
for u in g.vs:
neiavedeg = [deg[v] for v in g.neighbors(u)]
u["neideg"] = (sum(neiavedeg) / float(len(neiavedeg))) if neiavedeg else 0

Things to note here:

1. Edge weights are not handled; things can become more complicated if the
edges have weights.
2. You can simply use g.degree() to query the degrees of all the vertices, so
you don't have to built the deg vector item by item.
3. g.neighbors() accepts a Vertex object as well as a vertex index, so no need
to use u.index there.
4. Since you query the neighbors of each vertex only once, there is no
performance gain when you store the neighbor sets in advance (unless you want
to use them again).

--
Tamas

```