gensim #2 迭代计算

关于文档转向量、计算相似度这些算法,许多经典的库中都有,比如sklearn就可以实现#1中的整个流程。

gensim的优势在于2点:

  1. 所有向量使用稀疏表示,占用内存小得多。
  2. 支持结合Python的迭代计算,内存友好。

下面展示如何迭代完成#1中的过程:

// 假设数据来自MongoDB
// 有一个库db_name,内有集合collection_name,每个文档都有一个字段doc,表示文字字符串
import gensim
from pymongo import MongoClient

connection = MongoClient()
collection = connection.db_name.collection_name

# mongoDB原生支持迭代查询,对Python很友好
# cursor = collection.find()

dictionary = gensim.corpora.Dictionary(doc.get('doc').split() for doc in collection.find())

# 创建一个生成器
def iter_vectors():
    for doc in collection.find():
        yield dictionary.doc2bow(doc.get('doc'))

model_tfidf = gensim.models.TfidfModel(iter_vectors(), id2word=dictionary)

index_tmp_file = '/tmp/gensim/test'
index = gensim.similarities.Similarity(
    index_tmp_file,
    model_tfidf[iter_vectors()],
    num_features=len(dictionary)
)

for similarity in index:
  # 这里输出#1中相似度矩阵的每一行
  print(similarity)

整个过程中,始终只有一条来源数据在内存中。这样无论来源数据有多少,都不会爆内存。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容