将 word2vec 模型查询的结果保存在 csv 文件中?

2024-05-07

我正在语料库上训练 word2vec 模型,然后查询该模型。

这工作正常,但我正在运行一个实验,需要针对不同的条件调用模型,保存每个条件的模型,查询每个条件的模型,然后将查询的输出保存到 csv 文件中,例如进一步分析所有条件。

我研究了 gensim 文档并四处搜索,但不知道该怎么做。

我问了 gensim 的人,他们说由于“most_similar”的结果是一个 python 对象,我可以用 pickle 保存它或保存为 txt、csv,无论我想要什么格式。

听起来不错,但我不知道如何开始。这是我的代码 - 你能帮我“填补空白”,即使是一些简单的事情,我可以进一步研究并自己扩展吗?

#train the model
trained_model = gensim.models.Word2Vec(some hyperparamters)

#save the model in the format that is appropriate for querying by writing it to disk and call it stored_model
trained_model.save(some_filename)

#read in the stored model from disk and call it retrieved_model
retrieved_model = gensim.models.Word2Vec.load(some_filename)

#query the retrieved model
#each of these queries produces a tuple of 10 'word', cosine similarity pairs
retrieved_model.wv.most_similar(positive=['smartthings', 'amazon'], negative=['samsung'])
retrieved_model.wv.most_similar(positive=['light', 'nest'], negative=['hue'])
retrieved_model.wv.most_similar(positive=['shopping', 'new_york_times'], negative=['ebay'])
.
.
.
#store the results of all these queries in a csv so they can be analyzed.
?

正如我的评论中所述,您可以像这样保存和加载模型对象:

# Save model
filename = 'stored_model.wv' # Can be any arbitrary filename
trained_model.save(filename) 

# Reload model
retrieved_model = gensim.models.Word2Vec.load(filename)

为了检索多个查询,我建议定义一个查询列表并迭代它以检索所有结果。

# Define queries (this is the only user input required!)
my_queries = [{'positive' : ['smartthings','amazon'],
               'negative' : ['samsung']},
              {'positive' : ['light','nest'],
               'negative' : ['hue']},
               #<and so forth...>
              ]

# Initialize empty result list
query_results = []

# Collect query results
for query in my_queries:
    result = retrieved_model.wv.most_similar(**query)
    query_results.append(result)

最后,您可以使用结果列表以您想要的格式写入 csv 文件。可以构造文件的标头来表示查询。

# Open the file
with open("my_results.csv", "w") as outfile:

    # Construct the header
    header = []
    for query in my_queries:
        head = 'pos:'+'+'.join(query['positive'])+'__neg:'+'+'.join(query['negative']) 
        # First resulting head: 'pos:smartthings+amazon__neg:samsung'
        header.append(head)

    # Write the header
    # Note the additional empty fields (,_,) because each head needs two columns
    outfile.write(",_,".join(header)+",_\n")

    # Write the second row to label the columns
    outfile.write(",".join(["word,cos_sim" for i in range(len(header))])+'\n')

    # Write the data
    for i in range(len(query_results[0])):
        row_results = [r[0]+','+str(r[1]) for r in query_results[i]]
        outfile.write(",".join(row_results)+'\n')

请注意,这仅在每个查询检索相同数量的项目时才有效(默认情况下是这种情况,但可以使用topn关键字参数most_similar).

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将 word2vec 模型查询的结果保存在 csv 文件中? 的相关文章

随机推荐