乘以S
和V
正是使用 SVD/LSA 执行降维所必须做的。
>>> C = np.array([[1, 0, 1, 0, 0, 0],
... [0, 1, 0, 0, 0, 0],
... [1, 1, 0, 0, 0, 0],
... [1, 0, 0, 1, 1, 0],
... [0, 0, 0, 1, 0, 1]])
>>> from scipy.linalg import svd
>>> U, s, VT = svd(C, full_matrices=False)
>>> s[2:] = 0
>>> np.dot(np.diag(s), VT)
array([[ 1.61889806, 0.60487661, 0.44034748, 0.96569316, 0.70302032,
0.26267284],
[-0.45671719, -0.84256593, -0.29617436, 0.99731918, 0.35057241,
0.64674677],
[ 0. , 0. , 0. , 0. , 0. ,
0. ],
[ 0. , 0. , 0. , 0. , 0. ,
0. ],
[ 0. , 0. , 0. , 0. , 0. ,
0. ]])
这给出了一个矩阵,其中除了最后几行之外的所有行都是零,因此可以将它们删除,实际上这是您将在应用程序中使用的矩阵:
>>> np.dot(np.diag(s[:2]), VT[:2])
array([[ 1.61889806, 0.60487661, 0.44034748, 0.96569316, 0.70302032,
0.26267284],
[-0.45671719, -0.84256593, -0.29617436, 0.99731918, 0.35057241,
0.64674677]])
PDF 在第 10 页上描述的是获得输入的低秩重构的方法C
。Rank != 维度,以及重构矩阵的剪切大小和密度使其在 LSA 中使用不切实际;它的目的主要是数学。您可以用它做的一件事是检查重建对于 的各种值有多好k
:
>>> U, s, VT = svd(C, full_matrices=False)
>>> C2 = np.dot(U[:, :2], np.dot(np.diag(s[:2]), VT[:2]))
>>> from scipy.spatial.distance import euclidean
>>> euclidean(C2.ravel(), C.ravel()) # Frobenius norm of C2 - C
1.6677932876555255
>>> C3 = np.dot(U[:, :3], np.dot(np.diag(s[:3]), VT[:3]))
>>> euclidean(C3.ravel(), C.ravel())
1.0747879905228703
针对 scikit-learn 的健全性检查TruncatedSVD
(完全披露:我写了那个):
>>> from sklearn.decomposition import TruncatedSVD
>>> TruncatedSVD(n_components=2).fit_transform(C.T)
array([[ 1.61889806, -0.45671719],
[ 0.60487661, -0.84256593],
[ 0.44034748, -0.29617436],
[ 0.96569316, 0.99731918],
[ 0.70302032, 0.35057241],
[ 0.26267284, 0.64674677]])