• word2vec和bert的基本使用方法


    1.word2vec的使用方法

    word2vec生成词向量的可以分为三步:
    分词->训练->调用模型

    # 数据集是我随便找的一篇小说
    import jieba
    from gensim.models import word2vec
    
    # 数据预处理
    def load_train_data(filename):
        # 数据预处理
        sentences=[]
        with open(filename, 'r', encoding='utf-8') as reader:
            for line in reader:
                line = line.strip()
                if len(line) >= 10:
                    sentences.append(line)
        return sentences
    # 使用结巴分词
    def segment(sentences):
        words=[]
        for sentence in sentences:
            # word=pseg.cut(sentence) # 带分词的词性
            word=jieba.cut(sentence) # 只是分词,不带词性,分完词之后,使用一个list装起来
            result=''
            for w in word:
                result+=' '+w
            words.append(result)
        # 读取每一行文本,将所有的文本写
        with open('F:\\python\\NLPBase\\data\\test.txt','a',encoding='utf-8') as fw:
            for result in words:
                fw.write(result)
                pass
            fw.close()
        return words
    # 生成word2vec模型,生成词向量
    def word2vect(filepath):
        sentences = word2vec.LineSentence(filepath)
        model = word2vec.Word2Vec(sentences, hs=1, min_count=1, window=3, vector_size=10)
        model.save('model')  # 保存模型
    
    #======================================
    # 加载数据集
    sentences=load_train_data('F:\\python\\NLPBase\\data\\dataset.txt')
    # 分词
    words=segment(sentences)
    #训练
    word2vect('F:\\python\\NLPBase\\data\\test.txt')
    model = word2vec.Word2Vec.load('model')  # 加载模型
    # 找出一个词向量最近的词集合
    for val in model.wv.similar_by_word("南方", topn=10):
        print(val[0], val[1])
        pass
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49

    结果:
    image.png

    2.bert的简单使用

    bert的使用可以简单的分成三步:
    加载bert分词器->加载bert模型->分词->将token转为vocabulary索引->训练->生成词向量
    注意:这个其中有一个bert数据的加载,如果是从网上下载的文件一般有三份东西,json包,bert预训练模型,语料表,一旦下载过来了这三个文件的名称就不能修改了,不然就会出错。

    import torch
    from pytorch_pretrained_bert import BertModel, BertTokenizer
    # 注意这个bert的配置文件可以从网上下载,也可以直接加载网上的,我这里是直接加载网上的,如果你下载了这些配置文件到本地,则就直接填写路径就可以了
    # 加载bert的分词器
    tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
    # 加载bert模型,这个路径文件夹下有bert_config.json配置文件和model.bin模型权重文件
    bert = BertModel.from_pretrained('bert-base-uncased')
    # 分词
    s = "I'm not sure, this can work, lol -.-"
    tokens = tokenizer.tokenize(s)
    # "i\\'\\m\\not\\sure\\,\\this\\can\\work\\,\\lo\\##l\\-\\.\\-"
    # 将token转为vocabulary索引
    ids = torch.tensor([tokenizer.convert_tokens_to_ids(tokens)])
    # 放到bert模型中训练
    result = bert(ids, output_all_encoded_layers=True)
    print(result)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    结果
    image.png

    3.总结

    bert和word2vec其实都是生成词向量,区别就是在于,word2vec中的词向量是固定的,他只会把意思相近的词放在相近的位置。
    image.png
    但是这样的做法有点不妥的地方就是,不同的文章中的语意是不一样的。比如:
    image.png
    比如这两句话中的it指代的意思不一样的,所以it与每一个词的关系也不一样。
    image.png
    所以就引入了Transformer中的self-attention机制。使得每个词之间与上下文之间的权重不一样,这样就能更好的表达词语之间的语义信息,这就是bert。

  • 相关阅读:
    Java中的常用线程安全集合
    Parcel配置public静态文件目录
    Go语言进阶,详解并发中的通道机制
    STM32通用定时器输入捕获
    虚拟机的ubuntu 22.04无法联网问题解决
    Linux软件包管理— rpm包中文件提取
    Python编程 字符串组成方式
    计算机专业应该学哪些课程?或许我们还有更大的进步空间
    java 注解信息说明
    【算法题】2651. 计算列车到站时间
  • 原文地址:https://blog.csdn.net/qq_35653657/article/details/126003346