[Scipy-svn] r4469 - in trunk/scipy/cluster: . tests

scipy-svn@scip... scipy-svn@scip...
Tue Jun 24 02:46:55 CDT 2008


Author: cdavid
Date: 2008-06-24 02:46:46 -0500 (Tue, 24 Jun 2008)
New Revision: 4469

Modified:
   trunk/scipy/cluster/tests/test_vq.py
   trunk/scipy/cluster/vq.py
Log:
Fix #535 with tests.

Modified: trunk/scipy/cluster/tests/test_vq.py
===================================================================
--- trunk/scipy/cluster/tests/test_vq.py	2008-06-24 00:54:19 UTC (rev 4468)
+++ trunk/scipy/cluster/tests/test_vq.py	2008-06-24 07:46:46 UTC (rev 4469)
@@ -1,7 +1,7 @@
 #! /usr/bin/env python
 
 # David Cournapeau
-# Last Change: Mon Jun 23 11:00 PM 2008 J
+# Last Change: Tue Jun 24 04:00 PM 2008 J
 
 # For now, just copy the tests from sandbox.pyem, so we can check that
 # kmeans works OK for trivial examples.
@@ -161,5 +161,19 @@
             # OK, that's what we expect
             pass
 
+    def test_kmeans_0k(self):
+        """Regression test for #535: fail when k arg is 0."""
+        try:
+            kmeans(X, 0)
+            raise AssertionError("kmeans with 0 clusters should fail.")
+        except ValueError:
+            pass
+
+        try:
+            kmeans2(X, 0)
+            raise AssertionError("kmeans2 with 0 clusters should fail.")
+        except ValueError:
+            pass
+
 if __name__ == "__main__":
     nose.run(argv=['', __file__])

Modified: trunk/scipy/cluster/vq.py
===================================================================
--- trunk/scipy/cluster/vq.py	2008-06-24 00:54:19 UTC (rev 4468)
+++ trunk/scipy/cluster/vq.py	2008-06-24 07:46:46 UTC (rev 4469)
@@ -479,13 +479,17 @@
         raise ValueError, 'iter must be >= to 1.'
     if type(k_or_guess) == type(array([])):
         guess = k_or_guess
+        if guess.size < 1:
+            raise ValueError("Asked for 0 cluster ? initial book was %s" % \
+                             guess)
         result = _kmeans(obs, guess, thresh = thresh)
     else:
         #initialize best distance value to a large value
         best_dist = 100000
         No = obs.shape[0]
         k = k_or_guess
-        #print 'kmeans iter: ',
+        if k < 1:
+            raise ValueError("Asked for 0 cluster ? ")
         for i in range(iter):
             #the intial code book is randomly selected from observations
             guess = take(obs, randint(0, No, k), 0)



More information about the Scipy-svn mailing list