<p dir="auto"><em>Original ticket <a href="http://projects.scipy.org/scipy/ticket/1009" rel="nofollow">http://projects.scipy.org/scipy/ticket/1009</a> on 2009-09-30 by trac user jap, assigned to unknown.</em></p>
<p dir="auto">If there are large values in the observation matrix, the vq.kmeans method fails with the following error:</p>
<p dir="auto">(Pdb) centroids, distortion = vq.kmeans(erow, centroids, iter=1)<br>
*** UnboundLocalError: local variable 'best_book' referenced before assignment</p>
<p dir="auto">This can be fixed by applying the attached patch.</p>
<p dir="auto"><em>Original ticket <a href="http://projects.scipy.org/scipy/ticket/1077" rel="nofollow">http://projects.scipy.org/scipy/ticket/1077</a> on 2009-12-28 by <a class="user-mention notranslate" data-hovercard-type="user" data-hovercard-url="/users/kwgoodman/hovercard" data-octo-click="hovercard-link-click" data-octo-dimensions="link_type:self" href="https://github.com/kwgoodman">@kwgoodman</a>, assigned to unknown.</em></p>
<p dir="auto">Just for fun I tried kmeans on a problem that has a LOT of features. I got an error:</p>
<div class="snippet-clipboard-content notranslate position-relative overflow-auto" data-snippet-clipboard-copy-content="UnboundLocalError: local variable 'best_book' referenced before assignment"><pre class="notranslate"><code class="notranslate">UnboundLocalError: local variable 'best_book' referenced before assignment
</code></pre></div>
<p dir="auto">The exception is raised because all sets of randomly selected starting centroids gave a distance greater than the initialized value of best_dist (100k) and therefore best_book is never assigned. Increasing the hard coded best_dist solved the problem.</p>
<p dir="auto">In the patch below I initialize best_dist to np.inf:</p>
<div class="snippet-clipboard-content notranslate position-relative overflow-auto" data-snippet-clipboard-copy-content="Index: scipy/cluster/vq.py
===================================================================
--- scipy/cluster/vq.py (revision 6151)
+++ scipy/cluster/vq.py (working copy)
@@ -485,7 +485,7 @@
         result = _kmeans(obs, guess, thresh = thresh)
     else:
         #initialize best distance value to a large value
-        best_dist = 100000
+        best_dist = np.inf
         No = obs.shape[0]
         k = k_or_guess
         if k &lt; 1:"><pre class="notranslate"><code class="notranslate">Index: scipy/cluster/vq.py
===================================================================
--- scipy/cluster/vq.py (revision 6151)
+++ scipy/cluster/vq.py (working copy)
@@ -485,7 +485,7 @@
         result = _kmeans(obs, guess, thresh = thresh)
     else:
         #initialize best distance value to a large value
-        best_dist = 100000
+        best_dist = np.inf
         No = obs.shape[0]
         k = k_or_guess
         if k &lt; 1:
</code></pre></div>