【问题标题】:Unable to calculate silhouette_score using a sparse matrix in sklearn [closed]无法使用 sklearn 中的稀疏矩阵计算 silhouette_score [关闭]
【发布时间】:2021-02-24 03:02:48
【问题描述】:

我正在尝试使用稀疏矩阵计算 silhouette_score 或 silhouette_samples,但出现以下错误:

ValueError: diag 需要一个至少为二维的数组

示例代码如下:

edges = [
(1, 2, 0.9),
(1, 3, 0.7),
(1, 4, 0.1),
(1, 5, 0),
(1, 6, 0),
(2, 3, 0.8),
(2, 4, 0.2),
(2, 5, 0),
(2, 6, 0.3),
(3, 4, 0.3),
(3, 5, 0.2),
(3, 6, 0.25),
(4, 5, 0.8),
(4, 6, 0.6),
(5, 6, 0.9),
(7, 8, 1.0)]

gg = nx.Graph()

for u,v, w in edges:
    gg.add_edge(u, v, weight=w)


adj = nx.adjacency_matrix(gg)
adj.setdiag(0)


from sklearn.metrics import silhouette_score, silhouette_samples

print(silhouette_score(adj, metric='precomputed', labels=labels))
silhouette_samples(adj, metric='precomputed', labels=labels)

【问题讨论】:

    标签: scikit-learn scipy sparse-matrix silhouette


    【解决方案1】:

    这是一个错误。你应该报告它。 Relevant code.

    X, labels = check_X_y(X, labels, accept_sparse=['csc', 'csr'])
    
    # Check for non-zero diagonal entries in precomputed distance matrix
    if metric == 'precomputed':
        atol = np.finfo(X.dtype).eps * 100
        if np.any(np.abs(np.diagonal(X)) > atol):
            raise ValueError(
                'The precomputed distance matrix contains non-zero '
                'elements on the diagonal. Use np.fill_diagonal(X, 0).'
            )
    

    虽然输入检查明确接受 CSC/CSR 矩阵,但如果 metric 是 'precomputed',它会将 X 放入不适用于稀疏矩阵的 numpy 函数中。

    【讨论】:

      猜你喜欢
      • 2014-03-05
      • 2018-06-04
      • 2014-10-11
      • 1970-01-01
      • 1970-01-01
      • 2020-12-05
      • 2019-07-04
      • 2017-07-21
      • 1970-01-01
      相关资源
      最近更新 更多