【发布时间】:2016-09-14 20:42:35
【问题描述】:
SVD 代表奇异值分解,据说是在文本分类中进行特征缩减的流行技术。我知道原理是this link。
我一直在使用 C#,使用 Accord.Net 库,并且已经在计算 TF-IDF 时得到了一个锯齿状数组 double[][]。
我已经知道我的文档中有 4 个主题。我想用聚类数 k = 4 来测试 Kmean 方法。在使用 Kmean 之前,我想使用 SVD 进行特征缩减。当结果显示时,将近 90% 的文档被分为 1 个组,其他文档被分为 3 个其他集群。这是一个非常糟糕的结果。我已尝试重新运行多次,但结果并没有太大变化。如果我使用 PCA 而不是 SDV,一切都会按预期进行。
所以,我错了。任何知道这一点的人都可以指导我一个示例代码。非常感谢。
注意:我原来的 TF-IDF 行代表文档,列代表术语
这是我的代码:
//to matrix because the function SVD requiring input of matrix, not jagged array
//transpose because the TF-IDF used for SVD has rows representing terms, columns representing documents;
var svd = new SingularValueDecomposition(tfidf.ToMatrix().Transpose());
double[,] U = svd.LeftSingularVectors;
double[,] S = svd.DiagonalMatrix;
double[,] V = svd.RightSingularVectors;
//find the optimal cutoff y so that we retain enough singular values to make up 90% of the energy in S
//http://infolab.stanford.edu/~ullman/mmds/ch11.pdf, page 18-20
double energy = 0;
for (int i = 0; i < S.GetLength(0); i++)
{
energy += Math.Pow(S[i, i], 2);
}
double percent;
int y = S.GetLength(0);
do
{
y--;
double test = 0;
for (int i = 0; i < y; i++)
{
test += Math.Pow(S[i, i], 2);
}
percent = test / energy;
} while (percent >= 0.9);
y = y + 1;
//Uk gets all rows, y first columns of U; Sk get y first rows, y first columns of S; Vk get y first rows, all columns of V
double[,] Uk = U.Submatrix(0, U.GetLength(0) - 1, 0, y - 1);
double[,] Sk = S.Submatrix(0, y - 1, 0, y - 1);
double[,] Vk = V.Submatrix(0, y - 1, 0, V.GetLength(1) - 1);
//reduce dimension according to http://stats.stackexchange.com/questions/107533/how-to-use-svd-for-dimensionality-reduction-to-reduce-the-number-of-columns-fea
//we tranpose again to have the rows being document, columns being term as original TF-IDF
//ToArray because the Kmean below acquiring input of jagged array
tfidf = Uk.Multiply(Sk).Transpose().ToArray();
// if tfidf = Uk.Multiply(Sk).Multiply(Vk).Transpose().ToArray()
// result still bad
// Create a K-Means algorithm using given k and a square Euclidean distance as distance metric.
var kmeans = new KMeans(4, Distance.SquareEuclidean) { Tolerance = 0.05 };
int[] labels = kmeans.Compute(tfidf);
之后,我们通过一些步骤来根据标签知道哪些文档属于哪些组。
【问题讨论】:
标签: c# svd accord.net