[英]Transforming words into Latent Semantic Analysis (LSA) Vectors
将句子或单词变成向量与使用文档一样没有区别,一个句子就像一个简短的文档,一个单词就像一个非常简短的单词。 从第一个链接开始,我们具有将文档映射到向量的代码:
def makeVector(self, wordString): """ @pre: unique(vectorIndex) """ #Initialise vector with 0's vector = [0] * len(self.vectorKeywordIndex) wordList = self.parser.tokenise(wordString) wordList = self.parser.removeStopWords(wordList) for word in wordList: vector[self.vectorKeywordIndex[word]] += 1; #Use simple Term Count Model return vector
可以使用相同的功能将句子或单个单词映射到向量。 只需将它们传递给此函数即可。 对于一个单词, wordList
的结果将是一个保存单个值的数组,类似于: ["word"]
,然后在映射后,结果向量将是一个单位向量 ,该向量在关联维度中包含1
在其他维度中包含0
s。
例:
vectorKeywordIndex
(代表词汇表中的所有单词):
{"hello" : 0, "world" : 1, "this" : 2, "is" : 3, "me" : 4, "answer" : 5}
文件"this is me"
: [0, 0, 1, 1, 1, 0]
文档"hello answer me"
: [1, 0, 0, 0, 1, 1]
"hello answer me"
[1, 0, 0, 0, 1, 1]
单词"hello"
: [1, 0, 0, 0, 0, 0]
单词"me"
: [0, 0, 0, 0, 1, 0]
之后,可以使用以下代码通过余弦相似度等几个标准来评估相似度:
def cosine(vector1, vector2): """ related documents j and q are in the concept space by comparing the vectors using the code: cosine = ( V1 * V2 ) / ||V1|| x ||V2|| """ return float(dot(vector1,vector2) / (norm(vector1) * norm(vector2)))
或使用scikit-learn的sklearn.metrics.pairwise.cosine_similarity 。
from sklearn.metrics.pairwise import cosine_similarity
sim = cosine_similarity(x, y)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.