Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

(Solved) schemes for fine-tuning with gensim / (已解决)使用 gensim 进行微调的方案 #170

Open
ShutterZor opened this issue Aug 23, 2024 · 1 comment

Comments

@ShutterZor
Copy link

写在前面: 感谢作者提供的文件。

琢磨了一上午,发现可以配合gensim进行微调,但是我最后一直保存不了模型。

不过我还是把这个方案贡献出来以供大家进行参考。

(ps:写的比较急,例子是从gensim文档里面抄来的,做了一些修改。我不是科班出身,不太能拿得准,但是有值我就默认正确了。欢迎讨论)

import gensim
from gensim.models import Word2Vec, KeyedVectors
from gensim.utils import simple_preprocess

# 加载预训练的词向量模型
pretrained_model_path = 'pretrained_model/baidu_word_ngram.bz2'
pretrained_model = KeyedVectors.load_word2vec_format(pretrained_model_path)

# 准备新的文本数据
new_texts = [
    '这是 新的 文本 数据。',
    '用于 微调 词向量模型。',
    '这行 文本 用来 训练 模型。',
]

# 对新文本数据进行分词处理
processed_texts = [simple_preprocess(text) for text in new_texts]

# 创建一个新的Word2Vec模型
model = Word2Vec(vector_size=pretrained_model.vector_size, min_count=1)

# 使用新的数据建立初始词汇表
model.build_vocab(processed_texts, update=False)

# 从预训练模型中提取词向量
model.wv.add_vectors(pretrained_model.index_to_key, pretrained_model.vectors)

# 微调模型
model.train(processed_texts, epochs=model.epochs, total_examples=model.corpus_count)

# 保存微调后的模型
model.save('test.model')


# 不微调的话用以下方法
fd='pretrained_model/baidu_word_ngram.bz2'
model2 =gensim.models.KeyedVectors.load_word2vec_format(fd)

sentence_obama = '我 有 一个 苹果'
sentence_president = '我 没有 两个 文本'

def preprocess(sentence):
    return sentence.lower().split()

sentence_obama = preprocess(sentence_obama)
sentence_president = preprocess(sentence_president)

print(model2.wmdistance(sentence_obama, sentence_president)) # 0.9176010595871009

# 微调后对 word2vec 调用
print(model.wv.wmdistance(sentence_obama, sentence_president)) # 0.973310878801909

微调之后确实值变了,不过我还是有一些疑惑:

1、这种方法究竟合不合理。
2、无法保存微调后的模型。

@HunterHeidy
Copy link

HunterHeidy commented Aug 23, 2024 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants