稀疏观测矩阵上的分层聚类

Sie*_*yer 5 python hierarchical-clustering scipy

我正在尝试对大型稀疏观察矩阵执行分层聚类。该矩阵表示多个用户的电影评分。我的目标是根据他们的电影偏好对相似的用户进行聚类。但是,我需要一个树状图,而不是单一的部门。为了做到这一点,我尝试使用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')
Run Code Online (Sandbox Code Playgroud)

这适用于小数据集:

在此处输入图片说明

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

hpa*_*ulj 1

From将参数scipy/cluster/hierarchy.py linkage处理y为:

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.")
Run Code Online (Sandbox Code Playgroud)

当我应用asarray到 a时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]: ()
Run Code Online (Sandbox Code Playgroud)

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

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