带有Sklearn的Python LSA

Sch*_*ama 8 python lsa scikit-learn

我目前正在尝试使用Sklearn实现LSA以在多个文档中查找同义词.这是我的代码:

#import the essential tools for lsa
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.decomposition import TruncatedSVD
from sklearn.metrics.pairwise import cosine_similarity
#other imports
from os import listdir

#load data
datafolder = 'data/'
filenames = []
for file in listdir(datafolder):
    if file.endswith(".txt"):
        filenames.append(datafolder+file)

#Document-Term Matrix
cv = CountVectorizer(input='filename',strip_accents='ascii')
dtMatrix = cv.fit_transform(filenames).toarray()
print dtMatrix.shape
featurenames = cv.get_feature_names()
print featurenames

#Tf-idf Transformation
tfidf = TfidfTransformer()
tfidfMatrix = tfidf.fit_transform(dtMatrix).toarray()
print tfidfMatrix.shape

#SVD
#n_components is recommended to be 100 by Sklearn Documentation for LSA
#http://scikit-learn.org/stable/modules/generated/sklearn.decomposition.TruncatedSVD.html
svd = TruncatedSVD(n_components = 100)
svdMatrix = svd.fit_transform(tfidfMatrix)

print svdMatrix

#Cosine-Similarity
#cosine = cosine_similarity(svdMatrix[1], svdMatrix)
Run Code Online (Sandbox Code Playgroud)

现在这是我的问题:Term-DOcument矩阵的形状和tf-idf矩阵是相同的,这是(27,3099).27份文件和3099字.在单值分解之后,矩阵的形状是(27,27).我知道你可以从2行计算余弦相似度以获得相似性,但我不认为通过使用SVD-Matrix,我可以在文档中获得2个单词的相似性.

有人可以向我解释SVD-Matrix代表什么,以及我可以用哪种方式在我的文档中查找同义词?

提前致谢.

Bru*_*hou 5

SVD是一种降维工具,这意味着它可以将功能的顺序(数量)减少到更多representative.

从github上的源代码:

def fit_transform(self, X, y=None):
    """Fit LSI model to X and perform dimensionality reduction on X.
    Parameters
    ----------
    X : {array-like, sparse matrix}, shape (n_samples, n_features)
        Training data.
    Returns
    -------
    X_new : array, shape (n_samples, n_components)
        Reduced version of X. This will always be a dense array.
    """
Run Code Online (Sandbox Code Playgroud)

我们可以看到返回的矩阵包含具有减少的组件数量的样本.然后,您可以使用距离计算方法来确定任何两行的相似性.

这里还给出了一个简单的LSA通过SVD的例子.