【问题标题】:Check for equal lists检查相等的列表
【发布时间】:2016-05-16 04:16:55
【问题描述】:

读完这个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 的类型是&lt;type 'numpy.ndarray'&gt;,它们的计算方式如下:

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'

【问题讨论】:

    标签: python python-2.7 numpy types scikit-learn


    【解决方案1】:

    由于您要比较浮点值,因此最好使用numpy.allclose(),因此,请将值保留在numpy 数组形式中:

    return np.allclose(np.array(old_centroids), np.array(centroids))
    

    (请注意,我将一维数组列表转换为二维数组;从技术上讲,如果您愿意,您可以为old_centroidscentroids 中的每对元素分别应用allclose()。)

    编辑(根据评论):如果old_centroidscentroids可能有不同的形状,在allclose()之前检查一下:

    old = np.array(old_centroids)
    new = np.array(centroids)
    return old.shape == new.shape and np.allclose(old, new)
    

    【讨论】:

    • r = all(less_equal(abs(x-y), atol + rtol * abs(y))) ValueError: operands could not be broadcast together with shapes (25,0) (25,3)。是不是因为一开始,old_centroids 只是一个包含 25 个空列表的列表?
    • 嗯,您的问题中的打印输出中肯定不会填充空列表。如果old_centroids 内容有其他变体,请添加可执行示例。如果这是唯一的其他变体,只需在比较之前检查数组大小是否大于 0。
    • fjarri,太长了,我的问题已经很大了。 old_centroids 在第一次迭代 only 时由 25 个空列表组成,然后得到你在我的问题中看到的那个,我们不能绕过这个吗?在致电allclose() 之前进行虚拟检查?
    猜你喜欢
    • 1970-01-01
    • 2016-09-13
    • 2012-01-10
    • 1970-01-01
    • 1970-01-01
    • 2019-11-04
    • 1970-01-01
    • 1970-01-01
    • 2022-08-22
    相关资源
    最近更新 更多