我想要做SVD上的稀疏矩陣通過使用SciPy的:稀疏矩陣:ValueError異常:基質類型必須是 'F', 'd', 'F',或 'd'
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'
這是我第一次這樣做。我應該如何解決它?有任何想法嗎?謝謝!
我想我的問題是compute_svd模塊中。我以前使用過普通矩陣。但我不知道如何轉換爲稀疏矩陣。 – Munichong 2011-12-27 22:49:37
取出稀疏矩陣並將其複製到完整矩陣。 afaik沒有稀疏的svd模塊。 – Anycorn 2011-12-27 22:51:36
它有scipy.sparse.linalg.svds。 http://docs.scipy.org/doc/scipy/reference/sparse.linalg.html – Munichong 2011-12-27 22:59:21