本文介绍了稀疏矩阵:ValueError:矩阵类型必须为"f","d","F"或"D"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过使用scipy在稀疏矩阵上进行SVD​​:

I want to do SVD on a sparse matrix by using scipy:

from svd import compute_svd
print("The size of raw matrix: "+str(len(raw_matrix))+" * "+str(len(raw_matrix[0])))

from scipy.sparse import dok_matrix
dok = dok_matrix(raw_matrix)

matrix = compute_svd( dok )

compute_svd函数是我的自定义模块,如下所示:

The function compute_svd is my customized module like this:

def compute_svd( matrix ):
    from scipy.sparse import linalg
    from scipy import dot, mat
    # e.g., matrix = [[2,1,0,0], [4,3,0,0]]
#    matrix = mat( matrix );
#    print "Original matrix:"
#    print matrix
    U, s, V = linalg.svds( matrix )
    print "U:"
    print U
    print "sigma:"
    print s
    print "VT:"
    print V
    dimensions = 1
    rows,cols = matrix.shape
    #Dimension reduction, build SIGMA'
    for index in xrange(dimensions, rows):
        s[index]=0
    print "reduced sigma:"
    print s
    #Reconstruct MATRIX'
#    from scipy import dot
    reconstructedMatrix= dot(dot(U,linalg.diagsvd(s,len(matrix),len(V))),V)
    #Print transform
    print "reconstructed:"
    print reconstructedMatrix

    return reconstructedMatrix

我得到一个例外:

Traceback (most recent call last):
  File "D:\workspace\PyQuEST\src\Practice\baseline_lsi.py", line 96, in <module>
    matrix = compute_svd( dok )
  File "D:\workspace\PyQuEST\src\Practice\svd.py", line 13, in compute_svd
    U, s, V = linalg.svds( matrix )
  File "D:\Program\Python26\lib\site-packages\scipy\sparse\linalg\eigen\arpack\arpack.py", line 1596, in svds
    eigvals, eigvec = eigensolver(XH_X, k=k, tol=tol ** 2)
  File "D:\Program\Python26\lib\site-packages\scipy\sparse\linalg\eigen\arpack\arpack.py", line 1541, in eigsh
    ncv, v0, maxiter, which, tol)
  File "D:\Program\Python26\lib\site-packages\scipy\sparse\linalg\eigen\arpack\arpack.py", line 519, in __init__
    ncv, v0, maxiter, which, tol)
  File "D:\Program\Python26\lib\site-packages\scipy\sparse\linalg\eigen\arpack\arpack.py", line 326, in __init__
    raise ValueError("matrix type must be 'f', 'd', 'F', or 'D'")
ValueError: matrix type must be 'f', 'd', 'F', or 'D'

这是我第一次这样做.我该如何解决?有任何想法吗?谢谢!

This is my first time to do this. How should I fix it? Any ideas? Thank you!

推荐答案

添加到Anycorn的答案中,是的,您需要转换矩阵以使其浮动或加倍.可以使用以下功能完成此操作: asfptype()来自scipy.sparse.coo_matrix

Adding to Anycorn's answer, yes you need to upcast your matrix to float or double. This can be done using the function:asfptype() from scipy.sparse.coo_matrix

在致电linalg.svds之前,添加以下行以对其进行广播:

Add this line to upcast it before you call linalg.svds:

matrix = matrix.asfptype()
U, s, V = linalg.svds( matrix )

这篇关于稀疏矩阵:ValueError:矩阵类型必须为"f","d","F"或"D"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 01:30