提供的模型不是 YellowBrick 中的聚类估计器

The supplied model is not a clustering estimator in YellowBrick

我正在尝试使用 YellowBrick 的 KElbowVisualizer 和 SKLearn 的期望最大化算法可视化我的数据的弯头图 class:GaussianMixture。

当我运行这个的时候,我得到了标题中的错误。 (我也尝试过 ClassificationReport,但同样失败)

model = GaussianMixture()

data = get_data(data_name, preprocessor_name, train_split=0.75)
X, y, x_test, y_test = data

visualizer = KElbowVisualizer(model, k=(4,12))
visualizer.fit(X)        # Fit the data to the visualizer
visualizer.show()        # Finalize and render the figure

我在 YellowBrick 中找不到任何东西来帮助我估计期望最大化的组件数量。

您可以使用 sklearn calinski_harabasz_score- 查看相关文档 here

scores = pd.DataFrame()
components = 100
for n in range(2,components):
    model = GaussianMixture(n_components=n)
    y = model.fit_predict(X)
    scores.loc[n,'score'] = calinski_harabasz_score(X,y)
plt.plot(scores.reset_index()['index'],scores['score'])

像这样的东西应该提供类似的功能。

Yellowbrick uses the sklearn estimator type checks to determine if a model is well suited to the visualization. You can use the force_model param 绕过类型检查(尽管 KElbow 文档似乎需要更新)。

然而,即使 force_model=True 让您通过了 YellowbrickTypeError,它仍然并不意味着 GaussianMixtureKElbow 一起工作。这是因为肘部可视化器设置为使用质心聚类 API 并且需要 n_clusters 超参数和 labels_ 学习参数。期望最大化模型不支持此 API。

但是,可以围绕高斯混合模型创建一个包装器,使其可以与肘部可视化器一起使用(并且类似的方法也可以用于分类报告)。

from sklearn.base import ClusterMixin
from sklearn.mixture import GaussianMixture
from yellowbrick.cluster import KElbow
from yellowbrick.datasets import load_nfl

class GMClusters(GaussianMixture, ClusterMixin):

    def __init__(self, n_clusters=1, **kwargs):
        kwargs["n_components"] = n_clusters
        super(GMClusters, self).__init__(**kwargs)

    def fit(self, X):
        super(GMClusters, self).fit(X)
        self.labels_ = self.predict(X)
        return self 


X, _ = load_nfl()
oz = KElbow(GMClusters(), k=(4,12), force_model=True)
oz.fit(X)
oz.show()

这确实产生了一个 KElbow 图(虽然对于这个特定的数据集来说不是很好):

另一个答案提到了 Calinksi Harabasz 分数,您可以在 KElbow 可视化工具中使用它,如下所示:

oz = KElbow(GMClusters(), k=(4,12), metric='calinski_harabasz', force_model=True)
oz.fit(X)
oz.show()

创建包装器并不理想,但对于不适合标准分类器或聚类器 sklearn APIs 的模型类型,它们通常是必需的,这是一个很好的策略对于许多 ML 任务。

基于@bbengfort 的出色回答,我使用了:

class GaussianMixtureCluster(GaussianMixture, ClusterMixin):
    """Subclass of GaussianMixture to make it a ClusterMixin."""

    def fit(self, X):
        super().fit(X)
        self.labels_ = self.predict(X)
        return self

    def get_params(self, **kwargs):
        output = super().get_params(**kwargs)
        output["n_clusters"] = output.get("n_components", None)
        return output

    def set_params(self, **kwargs):
        kwargs["n_components"] = kwargs.pop("n_clusters", None)
        return super().set_params(**kwargs)

这让您可以使用任何评分指标,并适用于最新版本的 YellowBrick。