我有一个相当大的数据集,我正在计算SVD然后我想找回矩阵。我的矩阵形状是:(33388,104),这是很多列和行。我想要80%的能量,即k=51
。
当我在返回时返回我的矩阵时,我收到以下错误:
operands could not be broadcast together with shapes (33388,51) (51,51)
img is a numpy array of an image file
k is the number of singular vectors to use
如何更正我的功能以修复此错误?
def rank_k_approx(img, k):
"""Return a rank-k approximation
img: an image (as a 2D grayscale array)
k: number of singular vectors used"""
u, sigma, vt = np.linalg.svd(img)
energy = np.linalg.norm(sigma)**2
approx_energy = np.linalg.norm(sigma[:k])**2
percentage = approx_energy*100/energy
print ("Energy retained = %4.2f"%percentage)
return u[:,:k]*np.diag(sigma[:k])*vt[:k,:]
答案 0 :(得分:1)
np.linalg.svd
的输出是ndarray
个对象,运算符*
是元素乘法。您想要计算矩阵乘积,需要使用np.dot()
或@
运算符。
乘法应该是:
u[:, :k].dot(np.diag(sigma[:k])).dot(vt[:k])