【word2vec实例1】

本博客介绍了一个使用大量中文语料训练Word2Vec模型的过程。从预处理语料到构建并训练Word2Vec模型,详细记录了每一步操作。使用的语料包括问题集,最终目标是创建一个能理解中文语义的词向量模型。
#  coding = utf8
import wordcut
import create_dict
import vectorize
import classify
import pickle
import psutil
import parameters
import os
from collections import deque
import gensim
import numpy as np
import csv
import processHandler


def cos_sim(arrA, arrB):
    return arrA.dot(arrB)/(np.linalg.norm(arrA)*np.linalg.norm(arrB))


# def compare(word_cutter,vectorizer,sentenceA,sentenceB):
#     tokenA = word_cutter.word_cut(sentenceA) # word_cuttter returns a list
#     tokenB = word_cutter.word_cut(sentenceB)
#     vectorA = np.array(vectorizer.vectorize(tokenA))
#     vectorB = np.array(vectorizer.vectorize(tokenB))
#     return cos_sim(vectorA,vectorB)


def main():
    current_dir = os.path.abspath('.')
    stopword_set = set()
    parameter = parameters.Parameters(os.path.join(current_dir, 'config.ini'), stopword_set)
    # w2v_training = os.path.join(current_dir, 'training_set20170810.csv')
    # pickle_path = os.path.join(current_dir, 'corpus')
    sentence_list = deque()
    # answer_path = os.path.join(current_dir, 'answer.csv')
    question_path =os.path.join(current_dir, 'question.csv')
    # concept_des_path =os.path.join(current_dir, 'concept_description.csv')
    w2v_file = os.path.join(current_dir, 'w2v_file_2017012.bin')
    word_cutter = wordcut.WordCutter(overlapping=parameter.overlapping)
    # try using stop-words
    preprocessor = processHandler.Prerocessor(False,False,False)
    # file = open(pickle_path,'rb')
    # pklist = pickle.load(file)
    # file.close()
    trainingset = []
    # i = 0
    # for row in pklist:
    #     temp = row[1].replace('\r','')
    #     temp = temp.replace('\n', '')
    #     trainingset.append(temp)
    #     temp = row[2].replace('\r','')
    #     temp = temp.replace('\n', '')
    #     trainingset.append(temp)
    #     i += 1
    #     if i > 100000:
    #         break
    # del pklist
    # file = open(answer_path,encoding='gb18030')
    # cache = file.readlines()
    # file.close()
    # for item in cache:
    #     temp = item.replace('\n','')
    #     temp = temp.replace('\r', '')
    #     trainingset.append(temp)
    file = open(question_path,encoding='gb18030')
    cache = file.readlines()
    file.close()
    for item in cache:
        temp = item.replace('\n','')
        temp = temp.replace('\r', '')
        trainingset.append(temp)
    # file = open(concept_des_path,encoding='gb18030')
    # cache = file.readlines()
    # file.close()
    # for item in cache:
    #     temp = item.replace('\n','')
    #     temp = temp.replace('\r', '')
    #     trainingset.append(temp)
    # del cache
    while len(trainingset) > 0:
        contain_chinese = False
        last = trainingset.pop()
        for item in last:
            if word_cutter.is_chinese(item):
                contain_chinese = True
                break
        if contain_chinese:
            temp = last
            for symbol in (u'', u'', u'', '!', '?'):
                temp = temp.replace(symbol, ' ')
            temp = temp.split()
            for sentence in temp:
                #print(sentence)
                sentence_list.append(sentence)
    del trainingset
    sentence_token = deque()
    total = len(sentence_list)
    i = 0
    while len(sentence_list) > 0:
        i += 1
        #print(item)
        #print(preprocessor.process_main(item))
        temp = preprocessor.process_main(sentence_list.pop())[-1]
        if temp is not None:
            #print(temp)
            sentence_token.append(temp)
        if i >= 10000:
            print([len(sentence_list), total])
            i = 0
    dic = gensim.models.Word2Vec(sentence_token,size=parameter.n_neuron,workers=3,seed=1024,iter=20) #sg=1 represents using skip-gram #sentence_token,size=parameter.n_neuron,workers=4,seed=1024,iter=20,sg=0
    #dic = gensim.models.Doc2Vec(sentence_token,size=parameter.n_neuron,workers=3,seed=1024,iter=20)
    sentence_token = deque()
    dic.save(w2v_file)
    # dic.save_word2vec_format(w2v_file, binary=True)



if __name__ == '__main__':
    main()
### 中文 Word2Vec 的实际应用案例与教程 #### 背景概述 Word2Vec 是一种高效的词嵌入技术,能够将词语映射到高维空间中的稠密向量,从而捕捉词语间的语义和句法关系[^2]。对于中文文本处理而言,由于其独特的分词需求以及字符级别的复杂性,基于 Word2Vec 的中文实现通常需要额外的数据预处理步骤。 --- #### 数据预处理 在构建中文 Word2Vec 模型之前,数据预处理是一个重要的环节。具体来说,这一步骤包括但不限于以下操作: - **分词**:使用工具如 `jieba` 对中文文本进行切分,以便后续模型能理解单个词语的意义。 - **去停用词**:移除诸如“的”、“是”等高频无意义词汇,减少噪声干扰。 - **清洗数据**:去除 HTML 标签、特殊字符以及其他无关内容。 这一过程可以通过 Python 库轻松实现,例如: ```python import jieba from gensim.models import Word2Vec def preprocess(texts): result = [] for text in texts: words = jieba.lcut(text) # 使用结巴分词 clean_words = [w for w in words if w not在停用词表中] # 去停用词逻辑需自行定义 result.append(clean_words) return result ``` 上述代码展示了如何利用 `jieba` 完成分词并清理数据[^4]。 --- #### 模型构建 一旦完成了数据预处理,就可以着手训练 Word2Vec 模型。以下是基于 Gensim 的简单示例代码: ```python from gensim.models import Word2Vec sentences = [["猫", "喜欢", "吃", "鱼"], ["狗", "喜欢", "啃", "骨头"]] # 预处理后的句子列表 model = Word2Vec( sentences=sentences, vector_size=100, # 向量维度 window=5, # 上下文窗口大小 min_count=1, # 最低词频阈值 workers=4, # 并行计算线程数 sg=1 # 使用 Skip-Gram (sg=1),CBOW (sg=0) ) # 输出某个词的向量表示 print(model.wv["猫"]) ``` 此代码片段说明了如何配置参数来适应不同的应用场景[^3]。 --- #### 实际应用案例 除了基础的词向量生成外,Word2Vec 在多个领域都有广泛的应用价值,比如: 1. **情感分析**:通过比较不同情绪类别的关键词向量距离,评估一段文字的情感倾向。 2. **推荐系统**:结合用户行为日志提取兴趣特征,进而提供个性化建议。 3. **主题建模**:辅助 LDA 等算法更好地发现文档集合的主题分布。 特别值得注意的是,在某些情况下还可以扩展至多语言支持或者跨域迁移学习场景之中[^1]。 --- #### 性能调优技巧 为了获得更高的精度或效率,可以从以下几个方面入手调整设置: - 提升样本规模以增强泛化能力; - 修改超参组合(如增大上下文范围或将最小频率设得更低)探索最佳效果; - 引入负采样机制降低计算成本同时保持质量稳定; 以上策略均有助于改善最终产出的质量水平。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值