使用scipy.spatial.distance.pdist
创建精简距离矩阵并将其传递给ward
时出现此错误:
Valid methods when the raw observations are omitted are 'single', 'complete', 'weighted', and 'average' error.
文档虽然说linkage()
函数需要一个压缩距离矩阵。我该如何解决这个问题?
foo = np.random.randint(3, size=(10,10))
scipy.spatial.distance.pdist(foo)
scipy.cluster.hierarchy.linkage(foo)
bar = scipy.spatial.distance.pdist(foo)
scipy.cluster.hierarchy.linkage(bar, method='ward')
给出:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/dist-packages/scipy /cluster/hierarchy.py", line 627, in linkage
raise ValueError("Valid methods when the raw observations are "
ValueError: Valid methods when the raw observations are omitted are 'single', 'complete', 'weighted', and 'average'.
我搜索了一下,发现this link,表示其他一些人有问题,但我无法找到一种解决方法,以scipy接受的形式提供数据。
答案 0 :(得分:2)
来自docstring:
y:ndarray
精简或冗余距离矩阵。压缩距离矩阵是包含距离矩阵的上三角形的平面阵列。这是pdist返回的形式。 或者,n维中的m个观察向量的集合可以作为m×n数组传递。
传入原始观察结果x维数组foo
似乎有效:
scipy.cluster.hierarchy.linkage(foo, method='ward')
给出:
array([[ 1. , 2. , 2.23606798, 2. ],
[ 5. , 8. , 2.23606798, 2. ],
[ 3. , 7. , 2.64575131, 2. ],
[ 9. , 11. , 2.64575131, 3. ],
[ 0. , 10. , 3.31662479, 3. ],
[ 12. , 13. , 3.71483512, 5. ],
[ 6. , 14. , 4.12310563, 4. ],
[ 4. , 16. , 4.17133072, 5. ],
[ 15. , 17. , 5.5136195 , 10. ]])
我同意linkage()
的文档至少可以改进。
答案 1 :(得分:1)
IHeader header = sheet.Header;
header.Center = "This is a &K0000FFblue text";
会返回单个,完整,平均,加权的正确结果。但对于质心,中位数和病房方法,y必须是数据矩阵,如果y是距离矩阵,则会发生错误。我同意文件不清楚。
scipy.cluster.hierarchy.linkage(y, method)
您可以通过将x数据矩阵或Y欧几里德距离矩阵输入到linkage()函数中来测试上面的代码。
我还发现,与R中的等效实现相比,from scipy.cluster.hierarchy import linkage
from scipy.spatial.distance import pdist
inp = np.loadtxt('iris.txt',delimiter=",", usecols=(0,1,2,3))
x = np.asarray(inp)
Y = pdist(x,'euclidean')
res_linkage = linkage(x,"weighted")`
包,hclust
为质心,中位数和病房方法返回不同的恢复。在更新新合并的群集与现有群集的距离时,scipy.cluster.hierarchy.linkage
似乎包含一些错误。