介绍转换并在一个demo语料库上演示它们的使用。
import logging logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
在本教程中,将展示如何将文档从一种矢量表示转换为另一种矢量表示。 此过程有两个
目标:
- 要找出语料库中的隐藏结构,请发现单词之间的关系,并使用它们以一种新颖的(希望)更具语义的方式描述文档。
- 使文档表示更加紧凑。 这既提高了效率(新的表示消耗了更少的资源)又提高了效率(忽略了边际数据趋势,降低了噪声)。
创建语料库
首先,我们需要创建一个语料库。此步骤与上一教程中的步骤相同。如果完成了,请随时跳到下一部分。
from collections import defaultdict from gensim import corpora documents = [ "Human machine interface for lab abc computer applications", "A survey of user opinion of computer system response time", "The EPS user interface management system", "System and human system engineering testing of EPS", "Relation of user perceived response time to error measurement", "The generation of random binary unordered trees", "The intersection graph of paths in trees", "Graph minors IV Widths of trees and well quasi ordering", "Graph minors A survey", ] # remove common words and tokenize stoplist = set('for a of the and to in'.split()) texts = [ [word for word in document.lower().split() if word not in stoplist] for document in documents ] # remove words that appear only once frequency = defaultdict(int) 33for text in texts: for token in text: frequency[token] += 1 texts = [ [token for token in text if frequency[token] > 1] for text in texts ] dictionary = corpora.Dictionary(texts) corpus = [dictionary.doc2bow(text) for text in texts]
创建转换模型
转换是标准的Python对象,通常通过训练语料库进行初始化:
from gensim import models tfidf = models.TfidfModel(corpus) # step 1 -- initialize a model
我们使用了教程1中的旧语料库来初始化(训练)转换模型。 不同的转换可能需要不同的初始化参数。 在TfIdf模型的情况下,“训练”仅包括一次遍历提供的语料库并计算其所有特征的文档频率。 训练其他模型(例如潜在语义分析或潜在狄利克雷分配)的工作量更大,因此需要花费更多时间。
转换向量
从现在开始,tfidf被视为只读对象,可用于将任何矢量从旧表示形式(单词袋整数计数)转换为新表示形式(TfIdf实值权重):
doc_bow = [(0, 1), (1, 1)] print(tfidf[doc_bow]) # step 2 -- use the model to transform vectors
输出
[(0, 0.7071067811865476), (1, 0.7071067811865476)]
或者:
corpus_tfidf = tfidf[corpus] for doc in corpus_tfidf: print(doc)
[(0, 0.5773502691896257), (1, 0.5773502691896257), (2, 0.5773502691896257)] [(0, 0.44424552527467476), (3, 0.44424552527467476), (4, 0.44424552527467476), (5, 0.3244870206138555), (6, 0.44424552527467476), (7, 0.3244870206138555)] [(2, 0.5710059809418182), (5, 0.4170757362022777), (7, 0.4170757362022777), (8, 0.5710059809418182)] [(1, 0.49182558987264147), (5, 0.7184811607083769), (8, 0.49182558987264147)] [(3, 0.6282580468670046), (6, 0.6282580468670046), (7, 0.45889394536615247)] [(9, 1.0)] [(9, 0.7071067811865475), (10, 0.7071067811865475)] [(9, 0.5080429008916749), (10, 0.5080429008916749), (11, 0.695546419520037)] [(4, 0.6282580468670046), (10, 0.45889394536615247), (11, 0.6282580468670046)]
https://radimrehurek.com/gensim/auto_examples/core/run_topics_and_transformations.html