finding euclidean distance,better code?
Gabriel Genellina
gagsl-py2 at yahoo.com.ar
Mon Mar 17 09:17:46 EDT 2008
En Mon, 17 Mar 2008 03:04:16 -0200, devnew at gmail.com <devnew at gmail.com>
escribi�:
> while trying to write a function that processes some numpy arrays and
> calculate euclidean distance ,i ended up with this code
> (though i used numpy ,i believe my problem has more to do with python
> coding style..so am posting it here)
>
> for image in range(numimgs):
> distance = abs(input_wk - weights[image, :])
> if image==0:
> #copy from distance to mindistance
> mindistance=distance.copy()
> if sum(mindistance) > sum(distance):
> imgindex=image
> mindistance=distance.copy()
> if max(mindistance) > 0.0:
> #normalise mindistance
> mindistance=mindistance/(max(mindistance)+1)
> dist=sum(mindistance)
>
> this gets me the euclidean distance value.
It looks like you're rather computing a distance derived from the 1-norm
(sum of coordinates; like in a city with square blocks).
I'd save the sum(mindistance) value to avoid recomputing it in every
iteration.
> I want to know if the way i
> coded it can be improved,made more compact....if someone can give
> suggestions it will be a great help .
The code is pretty legible as it is now. Anyway, using min() and a
generator:
_, imgindex = min((sum(abs(input_wk - weights[image, :])),image) for image
in xrange(numimgs))
mindistance = abs(input_wk - weights[imgindex, :])
# normalize and sum again
--
Gabriel Genellina
More information about the Python-list
mailing list