中文分词(上)——获取和Word2Vec模型构建

1. 写在前面

本文所采用的语料库为复旦中文文本分类语料库,包含20个类别。具体代码和资源点此进行下载

2. 文件读取

首先,我们先完成读取一篇文本文档,去除stopwords,只保留中文字符后进行分词。以下代码包括两个函数:

  1. extract_words_one_file()可以对单个文件进行处理,提取所有中文分词并返回值。
  2. 单个文档实现功能之后,我们想要遍历文件夹下的所有文本文件并进行处理。extract_words_folder()可以实现此功能,并以制定格式和要求保存数据。

建议在看此部分代码之前,先看看数据集的层次结构,方便代码理解

import re,os,jieba
import numpy as np
import pandas as pd
import jieba.analyse

#从一个文本文件中提取中文分词,以句子或文章的形式保存在列表里
def extract_words_one_file(filepath,all=True):
    # all指的是是否以全文的形式保存所有分词。
    # True则表示一个文章的所有分词都储存在一个列表里,
    # False则表示每个句子的分词分别存在一个列表里,再以文章的形式储存列表

    def open_file(file_text):
        with open(file_text,'r',errors='ignore',encoding='utf-8') as fp:
            content=fp.readlines()
        return content

    # 只保留中文字符
    def remove(text):
        remove_chars=r'^\u4e00-\u9fa5'
        return re.sub(remove_chars,'',text)

    # 打开stopwords文件函数申明
    def open_stop(file_stop):
        stopwords=[line.strip() for line in open(file_stop,'r',encoding='utf-8-sig').readlines()]
        return stopwords

    # 利用jieba进行分词
    def seg_sentence(sentence):
        sentence_seged=jieba.cut(sentence.strip())
        stopwords=open_stop('data/stopwords/hit_stopwords.txt')
        outstr=''
        for word in sentence_seged:
            if word not in stopwords:
                outstr+=word
                outstr+=' '
        # strip()移除掉首位空格
        return outstr.strip()

    # 打开要加载的文件
    inputs=open_file(filepath)

    # 获取每一句中的分词
    words_in_sentence=[]
    for line in inputs:
        line_delete=remove(line)
        # 返回值是字符串
        line_seg=seg_sentence(line_delete)
        words_in_sentence.append(line_seg)

    print('words_in_sentence_1:',words_in_sentence)
    words_in_sentence=[x for x in words_in_sentence if x!='']
    print('words_in_sentence_2:', words_in_sentence)

    # 利用空格切割获取所有分词
    alltokens=[]
    chinesewords_sentence=[]
    for i in range(len(words_in_sentence)):
        # \s为空白
        word=re.split(r'\s',words_in_sentence[i])
        alltokens.append(word)

    print('alltokens:',alltokens)

    # 对每一个句子产生的分词所存储的列别,删除空词
    for element in alltokens:
        element=[x for x in element if x!='']
        chinesewords_sentence.append(element)

    print('chinesewords_sentence:',chinesewords_sentence)

    # 获取所有分词的列表
    chinesewords_article=[i for k in chinesewords_sentence for i in k]

    print('chinesewords_article:',chinesewords_article)

    if all==True:
        return chinesewords_article
    else:
        return chinesewords_sentence

#对一个文件夹下的多个文件夹中的文件进行批量处理,获取对应的中文分词以句子或全文形式保存
def extract_words_folder(path, all=True):
    # all指的是是否以全文的形式保存所有分词。
    # True则表示所有的分词储存在一个列表里,
    # False则表示每个句子的分词分别存在一个列表里,再以文章的形式储存列表

    # path='data/stopwords'
    files=os.listdir(path)
    features=[]

    # 遍历文件
    for i in range(len(files)):
        dirs=os.listdir(path+'/'+files[i])
        # 遍历该子文件下的所有文件并按照句子或全文形式抽取分词
        for f in dirs:
            if all==True:
                word_single_text=extract_words_one_file(path+'/'+files[i]+'/'+f,all=True)
                word_with_label = [word_single_text, files[i], f]  # 将所属种类和文件名一并保存
                features.append(word_with_label)
            else:
                word_single_text = extract_words_one_file(path + "/" + files[i] + "/" + f, all=False)
                features.append(word_single_text)

    if all == True:
        return pd.DataFrame(features, columns=['Words', 'Category', 'File'])  # 将分词、种类和文件名以dataframe储存
    else:
        return features


article_features = extract_words_folder(path='data/fudan-utf8/train',all = True)
#以csv形式保存dataframe
article_features.to_csv("article_features_train_raw.csv",encoding='utf_8',index=False)

#以文本格式保存句子分词
sent_features = extract_words_folder(path='data/fudan-utf8/train',all = False)
with open("word_sentence_train.txt", "w", encoding='utf-8') as f:
    f.write(str(sent_features))

3. 数据预处理

为了方便之后数据的一致性,我没有将所有的数据都一并保存,之后再划分训练集测试集,而是之前手动划分,自己创建了一个test的文件夹,分别提取训练集和测试集的数据,然后分别存入了两个csv文件当中。我在划分的时候也发现,不同类别的样本数量差别很大,有的上千,有的还不过百。因此,我只选取了其中最多的九个类别,去除了剩余的11个类别。因为这些样本数量过少的类别相比于其他悬殊的样本数量,很难让模型作出无偏见的判定。

import pandas as pd
import numpy as np

# raw data preprocessing 用于保存学习的数据到对应的文件
train=pd.read_csv('data/article_features_train_raw.csv')
test=pd.read_csv('data/article_features_test_raw.csv')

# 部分种类因为样本数太少,无法训练出结果,因此删掉,只保留9个数量比较多的类别
# train文件夹中的Enviroment拼写错误,为了和test统一替换成正确的拼写
train.Category.replace('C31-Enviornment','C31-Environment',inplace=True)
train=train[(train['Category'] == 'C3-Art')|(train['Category'] == 'C11-Space')|(train['Category'] == 'C19-Computer')
             |(train['Category'] == 'C31-Environment')|(train['Category'] == 'C32-Agriculture')
             |(train['Category'] == 'C34-Economy')|(train['Category'] == 'C38-Politics')|(train['Category'] == 'C39-Sports')
             |(train['Category'] == 'C7-History')]
test = test[(test['Category'] == 'C3-Art')|(test['Category'] == 'C11-Space')|(test['Category'] == 'C19-Computer')
             |(test['Category'] =='C31-Environment')|(test['Category'] == 'C32-Agriculture')
             |(test['Category'] == 'C34-Economy')|(test['Category'] == 'C38-Politics')|(test['Category'] == 'C39-Sports')
             |(test['Category'] == 'C7-History')]

#定义标签替换字典
label2category = {0: 'C11-Space', 1: 'C19-Computer', 2: 'C3-Art', 3: 'C31-Environment', 4: 'C32-Agriculture',
                  5: 'C34-Economy', 6:'C38-Politics',7:'C39-Sports',8:'C7-History'}
category2label = dict(zip(label2category.values(), label2category.keys()))

train['label'] = train.Category.replace(category2label)
test['label'] = test.Category.replace(category2label)
train = train.reset_index(drop=True)
test = test.reset_index(drop=True)

#保存新数据
train.to_csv("article_features_train.csv",encoding='utf_8_sig',index=False)
test.to_csv("article_features_test.csv",encoding='utf_8_sig',index=False)

4. Word2Vec模型

分词提取完毕后,我们需要用一定的方式表示这些分词,将这些计算机无法处理的非结构化信息转化为可计算的结构化信息。one-hot方法是其中之一,它的原理很好理解,首先生成一个初始值为零的长度为所有词的列表。若文章或句子包含某词,则该词对应位置为1,否则为0。但是其在表示大规模文本的时候往往出现过于稀疏的现象,也无法表示词语与词语间的关系,所以只是在比较简单的实践中使用。

本文我们所采取的文本表示方法是词嵌入中的Word2Vec。通俗的来说,就是根据训练将分词用多维向量表示。其2种训练模式为通过上下文来预测当前词和通过当前词来预测上下文。

4.1 数据导入

gensim版本为4.1.2

import gensim
#导入数据
with open("word_sentence.txt", "r") as f: #打开文件
    word_sentence = f.read() #读取文件

sent_feature = eval(word_sentence)

#我们只选取分词数大于3的句子进行W2v模型训练
sent_words = [i for k in sent_feature for i in k if len(i)>3]
4.2 只利用提取的分词训练模型

在第二部分中,我们已经将分词按句子形式保存到了文本文件中,现在,我们便利用它直接进行训练获得模型。

model = gensim.models.Word2Vec(sent_words, sg=1, size=100, window=3,iter=5,
                               min_count=3, negative=3, sample=0.001, hs=1)
#模型保存
model.wv.save_word2vec_format('./word2vec_model.txt', binary=False)
4.3 在已有词向量的基础上训练模型
# 采用第三方预训练模型
w2v_model=gensim.models.Word2Vec(vector_size=300,window=3,sg=1,min_count=3)
w2v_model.build_vocab(sent_words)
# 再加载第三方预训练模型
third_model=gensim.models.KeyedVectors.load_word2vec_format('data/fudan-utf8/sgns.merge.word',binary=False)
# 通过 intersect_word2vec_format()方法merge词向量:
w2v_model.build_vocab([list(third_model.vocab.key_to_index())],update=True)
w2v_model.intersect_word2vec_format('data/fudan-utf8/sgns.merge.word',binary=False,lockf=1.0)
w2v_model.train(sent_words, total_examples=w2v_model.corpus_count, epochs=5)
print("Model training finished.")

w2v_model.wv.save_word2vec_format('./word2vec_ensemble.txt', binary=False)
print("Model saved.")

参考

知乎 不忘初心

  • 0
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值