word2vec自训练词向量(代码+注释+训练过程和结果)

本文提供了MSRP、SICK、STS数据集的下载链接,介绍了数据预处理步骤,并分享了word2vec训练词向量的Python代码。通过训练,得到7000个词的128维词向量,展示词向量在多维空间的相似性。讨论了训练次数对效果的影响,并提到了预训练词向量的使用方法。
摘要由CSDN通过智能技术生成

数据集MSRP、SICK、STS下载地址分享

百度云:https://pan.baidu.com/s/1sqlCc702owp_T6KjyNT6Yw

提取码: 66nb

运行:网盘中msr_train.zip是msr_train.txt处理后可直接训练的数据,结合word2vec.py代码训练,注意文件路径自行修改

预处理过程:txt文件在excel表格中导入,然后去掉多余部分只保留文本,在另存为.csv文件并utf-8编码,再压缩为.zip文件

word2vec代码(中英文均可训练),代码已更新到网盘中

import collections
import math
import random
import zipfile
import numpy as np
from six.moves import xrange
import tensorflow as tf

def read_data(filename):
    with zipfile.ZipFile(filename) as f:
        data = tf.compat.as_str(f.read(f.namelist()[0])).split()
    return data

# 1.输入训练语料的文件路径(注意要去掉标注,只包含分词结果)
words = read_data('data/msr_train.zip')
print('Data size', len(words))

# 2.设置输出的词向量的词汇量
vocabulary_size = 8000

def build_dataset(words, vocabulary_size):
    count = [['UNK', -1]]
    count.extend(collections.Counter(words).most_common(vocabulary_size - 1))
    dictionary = dict()
    for word, _ in count:
        dictionary[word] = len(dictionary)
    data = list()
    unk_count = 0
    for word in words:
        if word in dictionary:
            index = dictionary[word]
        else:
            index = 0  # dictionary['UNK']
            unk_count += 1
        data.append(index)

    count[0][1] = unk_count
    reverse_dictionary = dict(zip(dictionary.values(), dictionary.keys()))

    return data, count, dictionary, reverse_dictionary

data, count, dictionary, reverse_dictionary = build_dataset(words, vocabulary_size)

# 删除words引用
del words

#******************************   训练开始   ********************************************
data_index = 0
# Step 3: Function to generate a training batch for the skip-gram model.
def generate_batch(batch_size, num_skips, skip_window):
    global data_index
    assert batch_size % num_skips == 0
    assert num_skips <= 2 * skip_window

    batch = np.ndarray(shape=(batch_size), dtype=np.int32)
    labels = np.ndarray(shape=(batch_size, 1), dtype=np.int32)
    span = 2 * skip_window + 1  # [ skip_window target skip_window ]
  
好的,以下是一个简单的 Python 实现 word2vec 模型的示例代码: ```python import numpy as np import re from collections import defaultdict from typing import List def tokenize(text: str) -> List[str]: # 将文本转换为小写,去掉标点符号和数字,并且按空格划分为单词 return re.findall(r'\b[a-z]+\b', text.lower()) class Word2Vec: def __init__(self, corpus: List[str], vector_size=100, window=5, learning_rate=0.01): self.corpus = corpus self.vector_size = vector_size self.window = window self.learning_rate = learning_rate self.word2id = {} self.id2word = {} self.word_freq = defaultdict(int) self.word_count = 0 self.vocab_size = 0 self.w1 = np.random.uniform(-0.5/vector_size, 0.5/vector_size, (vector_size, self.vocab_size)) self.w2 = np.random.uniform(-0.5/vector_size, 0.5/vector_size, (self.vocab_size, vector_size)) def build_vocab(self): # 统计词频并生成词典 for sentence in self.corpus: words = tokenize(sentence) for word in words: self.word_freq[word] += 1 self.word_count += 1 sorted_words = sorted(self.word_freq.items(), key=lambda x: x[1], reverse=True) for i, (word, freq) in enumerate(sorted_words): self.word2id[word] = i self.id2word[i] = word self.vocab_size = len(self.word2id) # 更新权重矩阵 w1 self.w1 = np.random.uniform(-0.5/self.vector_size, 0.5/self.vector_size, (self.vector_size, self.vocab_size)) def train(self): for sentence in self.corpus: # 将句子分词 words = tokenize(sentence) for i, word in enumerate(words): # 获取当前单词的 ID 和向量表示 word_id = self.word2id[word] word_vector = self.w1[:, word_id] # 随机选择一个窗口大小 window_size = np.random.randint(1, self.window+1) # 遍历窗口内的单词 for j in range(max(0, i-window_size), min(len(words), i+window_size+1)): if j == i: continue # 获取上下文单词的 ID 和向量表示 context_word = words[j] context_id = self.word2id[context_word] context_vector = self.w2[context_id, :] # 计算当前单词和上下文单词的相似度 similarity = np.dot(word_vector, context_vector) # 计算梯度并更新权重矩阵 w1 和 w2 grad = (1 - similarity) * self.learning_rate self.w1[:, word_id] += grad * context_vector self.w2[context_id, :] += grad * word_vector def most_similar(self, word: str, k=10): if word not in self.word2id: return [] word_vector = self.w1[:, self.word2id[word]] similarities = np.dot(self.w2, word_vector) top_k = np.argsort(similarities)[::-1][:k+1] return [(self.id2word[i], similarities[i]) for i in top_k if i != self.word2id[word]] ``` 这个示例代码包含了以下几个部分: 1. `tokenize` 函数:对文本进行分词,去掉标点符号和数字,并将所有单词转换为小写。 2. `Word2Vec` 类:初始化函数接受一个文本列表 `corpus`,以及一些超参数,如向量维度 `vector_size`、窗口大小 `window` 和学习率 `learning_rate`。该类包含了以下几个方法: - `build_vocab`:构建词典,统计词频并生成词典,同时初始化权重矩阵 `w1`。 - `train`:训练模型,遍历文本列表中的每个句子,对于每个单词,随机选择一个窗口大小,并遍历窗口内的所有单词,计算当前单词和上下文单词的相似度,并更新权重矩阵 `w1` 和 `w2`。 - `most_similar`:寻找与给定单词最相似的 `k` 个单词,基于余弦相似度计算相似度。 3. 示例代码的主函数:包括读入文本数据、初始化模型、构建词典、训练模型和测试模型等步骤。 需要注意的是,这只是一个简单的示例代码,实际上 word2vec 模型的实现有很多变种和优化,例如使用负采样、层次 softmax 等技术来加速训练和提高效果。
评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值