稀疏矩阵:ValueError:矩阵类型必须为'f','d','F'或'D'

时间:2011-12-27 22:38:28

标签: matrix scipy sparse-matrix

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

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是我自定义的模块,如下所示:

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'

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

2 个答案:

答案 0 :(得分:5)

你必须使用浮动或双打。你似乎使用不支持的矩阵式DOK of int?。

sparse svd:http://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.linalg.svds.html

答案 1 :(得分:0)

Source code

vgg.eval()

可以通过将数据类型从ValueError: matrix type must be 'f', 'd', 'F', or 'D' 更改为int来消除此错误,如下所示:float

...那么这将起作用