【问题标题】:How to cluster boolean observations in Python?如何在 Python 中对布尔观测值进行聚类?
【发布时间】:2021-04-04 06:26:54
【问题描述】:

您如何根据对哪些项目一起出现的观察来对项目进行聚类?

我遇到了如下问题。假设我正在研究儿童游戏,想知道哪些游戏倾向于一起玩。我已经确定了 12 个游戏,连续 100 个休息时间去了操场,并观察了孩子们每次都在玩哪些游戏。我的观察结果实际上是布尔值:1 如果当时玩游戏,否则为 0,如下面的数据框所示(实际上随机数在这里效果不佳,但它们显示了我正在使用的数据的类型)。

import random
import numpy as np
import pandas as pd
random.seed(0)
games=['Game %d'%i for i in range(0,12)]
observations=pd.DataFrame((np.random.rand(100, 12)*0.55).round(), columns=games)

我想知道哪些游戏倾向于一起玩。

到目前为止,我使用的方法是创建一个矩阵,其中包含每对一起观察到的次数,并从中创建一个“距离”矩阵:

observedTogether=np.array([[(observations[g1]==observations[g2]).sum()
    for g2 in games] for g1 in games])
distancesMatrix=1-observedTogether/observedTogether.max()

然后将其用作聚类算法的输入:

from scipy.cluster.hierarchy import dendrogram, linkage
Z = linkage(distancesMatrix, 'single') 
dendrogram(Z, orientation='right', labels=games)
plt.show()

它提供如下输出:

问题在于,生成的聚类与真实数据看起来不太令人信服,并且该警告消息让我怀疑我做错了什么。谷歌搜索该消息表明其他人也做错了,因为我找不到解释它的含义;不可否认,消息是正确的 - 矩阵一个距离矩阵。

我应该怎么做?

【问题讨论】:

    标签: python boolean cluster-analysis


    【解决方案1】:

    啊——找到了。 2 Dendrograms + Heatmap from condensed correlationmatrix with scipy

    使用以下方法修复错误消息“ClusterWarning: scipy.cluster: 对称非负空心观察矩阵看起来可疑地像未压缩的距离矩阵”:

    from scipy.spatial.distance import squareform
    Z = linkage(squareform(distancesMatrix), 'complete') 
    

    【讨论】:

      猜你喜欢
      • 2017-12-30
      • 2012-07-28
      • 2010-10-13
      • 2020-04-20
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      • 2018-02-25
      • 2011-03-16
      相关资源
      最近更新 更多