【问题标题】:Hierarchical clustering on sparse observation matrix稀疏观测矩阵的层次聚类
【发布时间】:2017-11-23 10:58:53
【问题描述】:

我正在尝试对大型稀疏观察矩阵执行层次聚类。该矩阵表示许多用户的电影评分。 我的目标是根据他们的电影偏好对相似的用户进行聚类。但是,我需要一个树状图,而不是单一的划分。为了做到这一点,我尝试使用 SciPy

R = dok_matrix((nrows, ncols), dtype=np.float32)

for user in ratings:
    for item in ratings[user]:
        R[item, user] = ratings[user][item]

Z = hierarchy.linkage(R.transpose().toarray(), method='ward')

这适用于小型数据集:

但是,我(显然)在扩展时遇到了内存问题。 如果有什么方法可以将 sparse 矩阵提供给算法?

【问题讨论】:

  • 您使用哪个包进行集群?正是该代码及其文档将说明它是否可以与稀疏矩阵一起使用。一些scikit-learn 函数适用于稀疏,但不是全部。
  • 正如我所说,我使用 SciPy。该方法的文档没有说明稀疏矩阵。 Scikit 不允许以简单的方式生成树状图(如果我错了,请纠正我)。
  • 你使用的是一维压缩距离矩阵吗?
  • 不,我使用观察矩阵,而不是距离。
  • Scipy 的分层链接也接受一维压缩距离矩阵。

标签: python scipy hierarchical-clustering


【解决方案1】:

来自scipy/cluster/hierarchy.py linkagey 参数处理为:

y = _convert_to_double(np.asarray(y, order='c'))

if y.ndim == 1:
    distance.is_valid_y(y, throw=True, name='y')
    [y] = _copy_arrays_if_base_present([y])
elif y.ndim == 2:
    if method in _EUCLIDEAN_METHODS and metric != 'euclidean':
        raise ValueError("Method '{0}' requires the distance metric "
                         "to be Euclidean".format(method))
    y = distance.pdist(y, metric)
else:
    raise ValueError("`y` must be 1 or 2 dimensional.")

当我将 asarray 应用于 dok 时,我得到一个 0d 对象数组。它只是将字典包装在一个数组中。

In [905]: M=sparse.dok_matrix([[1,0,0,2,3],[0,0,0,0,1]])
In [906]: M
Out[906]: 
<2x5 sparse matrix of type '<class 'numpy.int32'>'
    with 4 stored elements in Dictionary Of Keys format>
In [908]: m = np.asarray(M)
In [909]: m
Out[909]: 
array(<2x5 sparse matrix of type '<class 'numpy.int32'>'
    with 4 stored elements in Dictionary Of Keys format>, dtype=object)
In [910]: m.shape
Out[910]: ()

linkage 接受一维压缩样式距离矩阵,或等效的二维距离矩阵。

进一步查看linkage,我推断ward 使用nn_chain,它在编译的scipy/cluster/_hierarchy.cpython-35m-i386-linux-gnu.so 文件中。这使得该方法的工作部分更加远离普通 Python 程序员。

【讨论】:

猜你喜欢
  • 2012-09-05
  • 2013-04-01
  • 1970-01-01
  • 2012-05-23
  • 1970-01-01
  • 2011-03-11
  • 1970-01-01
  • 2018-01-19
  • 1970-01-01
相关资源
最近更新 更多