看完这篇Converting NumPy array into Python List structure? ,我有:
import numpy as np
print np.array(centroids).tolist()
print "here\n"
print old_centroids
print type(np.array(centroids).tolist())
print type(old_centroids)
给出:
[[-0.30485176069166947, -0.2874083792427779, 0.0677763505876472], ...,[0.09384637511656496, -0.015282322735474268, -0.05854574606104108]]
here
[array([-0.30485176, -0.28740838, 0.06777635]), ..., array([-0.03415291, -0.10915068, 0.07733185]), array([ 0.09384638, -0.01528232, -0.05854575])]
<type 'list'>
<type 'list'>
但是,当我在做的时候:
return old_centroids == np.array(centroids).tolist()
我遇到了这个错误:
return old_centroids == np.array(centroids).tolist()
ValueError: The truth value of an array with more than one element is ambiguous.
如何解决这个问题?
centroids 的类型是<type 'numpy.ndarray'>它们是这样计算的:
from sklearn import decomposition
centroids = pca.transform(mean_centroids)
请注意,如果没有 PCA,我会这样做:
return old_centroids == centroids
EDIT_0:
Check if two unordered lists are equal建议 set() ,因此我做了:
return set(old_centroids) == set(np.array(centroids).tolist()) # or set(centroids)
得到:
TypeError: unhashable type: 'list'
请您参考如下方法:
由于您比较的是浮点值,因此最好使用 numpy.allclose()因此,将您的值保存在 numpy 数组形式中:
return np.allclose(np.array(old_centroids), np.array(centroids))
(请注意,我将一维数组列表转换为二维数组;从技术上讲,您可以分别为 old_centroids 和 centroids,如果你愿意的话。)
编辑(根据评论):如果 old_centroids 和 centroids 可能有不同的形状,在 allclose() 之前检查它:
old = np.array(old_centroids)
new = np.array(centroids)
return old.shape == new.shape and np.allclose(old, new)
