gpt4 book ai didi

python - 如何检测使 k-均值余弦崩溃 Matlab 的零向量?

转载 作者:太空宇宙 更新时间:2023-11-04 01:35:19 25 4
gpt4 key购买 nike

我在大型数据集上运行 kmeans,但我总是收到以下错误:

Error using kmeans (line 145)
Some points have small relative magnitudes, making them effectively zero.
Either remove those points, or choose a distance other than 'cosine'.

Error in runkmeans (line 7)
[L, C]=kmeans(data, 10, 'Distance', 'cosine', 'EmptyAction', 'drop')

我的问题是,即使我将所有向量都加 1,我仍然会遇到此错误。我希望它能通过,但显然仍然有太多的零(这就是造成它的原因,对吧?)。

我的问题是:使 Matlab 确定一个点“相对较小”和“实际上为零”的条件是什么?

在将数据移交给 Matlab 之前,我想使用 Python 从我的数据集中删除所有这些点,因为我需要将我的结果与我在 Python 中处理的黄金标准进行比较。

提前致谢!

编辑答案

下面给出了正确答案,但如果有人通过谷歌找到这个问题,这里是你如何在 python 中从你的矩阵中删除“有效零向量”。每一行 (!) 都是一个数据点,因此如果您运行的是 kmeans,则需要在 python 或 Matlab 中进行转置:

def getxnorm(data):
return np.sqrt(np.sum(data ** 2, axis=1))

def remove_zero_vector(data, startxnorm, excluded=[]):
eps = 2.2204e-016
xnorm = getxnorm(data)
if np.min(xnorm) <= (eps * np.max(xnorm)):
local_index=np.transpose(np.where(xnorm == np.min(xnorm)))[0][0]
global_index=np.transpose(np.where(startxnorm == np.min(xnorm)))[0][0]
data=np.delete(data, local_index, 0) # data with zero vector removed
excluded.append(global_index) # add global index to list of excluded vectors
return remove_zero_vector(data, startxnorm, excluded)
else:
return (data, excluded)

我敢肯定有更 scipythonic 的方式来做到这一点,但它会做 :-)

最佳答案

如果您使用 this kmeans ,那么抛出错误的相关代码是:

case 'cosine'
Xnorm = sqrt(sum(X.^2, 2));
if any(min(Xnorm) <= eps * max(Xnorm))
error(['Some points have small relative magnitudes, making them ', ...
'effectively zero.\nEither remove those points, or choose a ', ...
'distance other than ''cosine''.'], []);
end

这就是你的测试。如您所见,重要的是相对大小,因此对所有内容加一只会让事情变得更糟(max(Xnorm) 也变得更大)。一个好的解决方法可能是按常数缩放所有数据。

关于python - 如何检测使 k-均值余弦崩溃 Matlab 的零向量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10509167/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com