如何使用从网站到word2vec gensim的废弃数据

ohtdti5x  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(302)

我对mysql、gensim和word2vec还很陌生,我还在通过我的个人项目学习如何使用它们。
我有数据,我做网络报废,所以它不是硬编码(我用instagram账号从几个帖子中获取标签数据,所以我的数据是instagram标签)
我试图在下面的代码中使用这些数据:

import pymysql.cursors
import re
from gensim.models import Word2Vec

# Connect to the database

connection = pymysql.connect(host=secrets[0],
user=username,
password=password,
db='test',
charset='charsetExample',
cursorclass=pymysql.cursors.DictCursor)

try:
    # connection to database
    with connection.cursor() as cursor:
    # cursor is iterator / 'Select' - caption is column 
     # post is the table 
     cursor.execute("SELECT caption FROM posts LIMIT 1000")
     data = cursor.fetchall()
     # list of captions
      captions = [d['caption'].lower() for d in data]
     # hashtags = [re.findall(r"#([A-Za-z_0-9]+)", caption) for caption in captions]
    # hashtags = [hashtag for hashtag in hashtags if hashtag != []]
    model = Word2Vec(captions, min_count=1)
    model = Word2Vec(hashtags) 
    res = model.wv.most_similar("fitness")

    print(captions)
    print(res)

finally:
    connection.close()

这是我正在研究的部分,但不确定如何做:

res = model.wv.most_similar("fitness")

现在我想用 most_similar() 方法来查看它是如何工作的。我想做的是 most_similar("value") 我想用我的数据,这将是每一个标签,我通过取消instagram网站的价值。
谢谢您!

fzwojiic

fzwojiic1#

好的,那么,你必须自己训练word2vec模型。你要做的是确保你的标签实际上没有 # 符号和小写。
现在,按post对hashtags进行分组。所以,如果某个帖子有标签 #red , #Wine , #party ,您应该从中列出一个如下所示的列表: [red, wine, party] . 对每篇文章重复上述步骤,并将每篇文章的列表保存到新列表中。所以这个输出应该是列表列表: [[red, wine, party], [post_2_hashtags], ...] . 现在您可以将其输入到word2vec模型中,并使用以下行对其进行训练:

model = gensim.models.Word2Vec(
    documents,
    size=150,
    window=10,
    min_count=2,
    workers=10)
model.train(documents, total_examples=len(documents), epochs=10)
model.save("word2vec.model")
``` `documents` 是在上一步中创建的列表的列表。然后可以使用 `model = gensim.models.Word2Vec.load("word2vec.model")` . 其余的都一样。你还在用吗 `most_similar()` 方法获取最相似的单词(在本例中为hashtag)。
唯一需要注意的是向量的大小( `size` 中的参数 `word2vec.model` ). 你在训练前定义它。如果你有大量的数据,你可以把它设置为一个更大的数字,如果你有少量的数据,你可以把它设置为一个更小的数字。但这是你必须弄清楚的,因为你是唯一一个能看到你拥有的数据的人。试着玩这个游戏 `size` 参数和评估模型 `most_similar()` 方法。
我希望这足够清楚:)

相关问题