Note that there are some explanatory texts on larger screens.

plurals
  1. PODistance calculation on matrix using numpy
    text
    copied!<p>I am trying to implement a K-means algorithm in Python (I know there is libraries for that, but I want to learn how to implement it myself.) Here is the function I am havin problem with:</p> <pre><code>def AssignPoints(points, centroids): """ Takes two arguments: points is a numpy array such that points.shape = m , n where m is number of examples, and n is number of dimensions. centroids is numpy array such that centroids.shape = k , n where k is number of centroids. k &lt; m should hold. Returns: numpy array A such that A.shape = (m,) and A[i] is index of the centroid which points[i] is assigned to. """ m ,n = points.shape temp = [] for i in xrange(n): temp.append(np.subtract.outer(points[:,i],centroids[:,i])) distances = np.hypot(*temp) return distances.argmin(axis=1) </code></pre> <p>Purpose of this function, given m points in n dimensional space, and k centroids in n dimensional space, produce a numpy array of (x1 x2 x3 x4 ... xm) where x1 is the index of centroid which is closest to first point. This was working fine, until I tried it with 4 dimensional examples. When I try to put 4 dimensional examples, I get this error:</p> <pre><code> File "/path/to/the/kmeans.py", line 28, in AssignPoints distances = np.hypot(*temp) ValueError: invalid number of arguments </code></pre> <p>How can I fix this, or if I can't, how do you suggest I calculate what I am trying to calculate here?</p> <h2>My Answer</h2> <pre><code>def AssignPoints(points, centroids): m ,n = points.shape temp = [] for i in xrange(n): temp.append(np.subtract.outer(points[:,i],centroids[:,i])) for i in xrange(len(temp)): temp[i] = temp[i] ** 2 distances = np.add.reduce(temp) ** 0.5 return distances.argmin(axis=1) </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload