【问题标题】:'numpy.float64' object is not iterable--working independently but not in for loop'numpy.float64' 对象不可迭代——独立工作但不在 for 循环中
【发布时间】:2021-05-25 08:33:38
【问题描述】:

当我把代码写成:

for i in range(1, k):
        
        idx = np.random.choice(data.shape[0], 1, p=squared_distances/sum(squared_distances))
        
        centroids[i]=data.[idx,:].toarray()
        
        squared_distances=np.min(pairwise_distances(data,centroids[0:i+1],metric='euclidean')**2  
  

我得到一个错误:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-71-dff0c6ebb89d> in <module>
      1 for i in range(1, k):
      2 
----> 3        idx = np.random.choice(data.shape[0], 1, p=squared_distances/sum(squared_distances))
      4 
      5        centroids[i]=data[idx,:].toarray()

TypeError: 'numpy.float64' object is not iterable

但是当我运行独立行时:

idx = np.random.choice(data.shape[0], 1, p=squared_distances/sum(squared_distances))

输出如下:

idx
array([5147])

如果代码在触发上述给定错误的 for 循环中,我想知道问题是什么。

供参考:

squared_distances=array([1.99133472, 1.98831716, 1.97838412, ..., 1.97078411, 1.98142071,
       1.99145465])
data.shape=(59071, 547979)
k=3

【问题讨论】:

  • 您的错误似乎指向另一个名为 tf_idf_norm 的变量。
  • tf_idf_norm 只是一个二维数组
  • 更正了问题中的变量名

标签: python numpy cluster-analysis


【解决方案1】:

错误是由sum(squared_distances) 产生的,这意味着在某些时候squared_distances 不再是numpy.ndarray 并变成numpy.float64。显然,这发生在squared_distances = np.min(...),因为默认情况下np.min 会产生一个标量,计算整个数组的最小值。为防止这种情况发生,您需要根据pairwise_distances 结果的维度为axis 提供正确的axis 参数(np.min(..., axis=0)np.min(..., axis=1))。

【讨论】:

  • 非常感谢。让我试试看。@aparpara
猜你喜欢
  • 2017-05-14
  • 2013-05-27
  • 1970-01-01
  • 1970-01-01
  • 2015-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多