• 循环神经网络 - 文本预处理


    文本预处理

    数据存在许多种形式,文本时最常见的例子之一,例如,一篇文章可以被简单地看作是一串单词序列甚至是一串字符序列

    本节中,我们将解析文本的常见预处理步骤;

    1. 将文本作为字符串加载到内存中
    2. 将字符串拆分为词元(如单词和字符)
    3. 建立一个词表,将拆分的词元映射到数字索引
    4. 将文本转换为数字索引序列,方便模型操作
    import collections
    import re
    from d2l import torch as d2l
    
    • 1
    • 2
    • 3

    1 - 读取数据集

    ⾸先,我们从H.G.Well的时光机器中加载⽂本。这是⼀个相当⼩的语料库,只有30000多个单词,但⾜够我们⼩试⽜⼑,⽽现实中的⽂档集合可能会包含数⼗亿个单词。下⾯的函数将数据集读取到由多条⽂本⾏组成的列表中,其中每条⽂本⾏都是⼀个字符串。为简单起⻅,我们在这⾥忽略了标点符号和字⺟⼤写

    #@save
    d2l.DATA_HUB['time_machine'] = (d2l.DATA_URL + 'timemachine.txt','090b5e7e70c295757f55df93cb0a180b9691891a')
    
    def read_time_machine(): #@save
        """将时间机器数据集加载到文本行的列表中"""
        with open(d2l.download('time_machine'),'r') as f:
            lines = f.readlines()
        return [re.sub('[^A-Za-z]+',' ',line).strip().lower() for line in lines]
    
    lines = read_time_machine()
    print(f'# 文本总行数:{len(lines)}')
    print(lines[0])
    print(lines[10])
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    # 文本总行数:3221
    the time machine by h g wells
    twinkled and his usually pale face was flushed and animated the
    
    • 1
    • 2
    • 3

    2 - 词元化

    下面的tokenize函数将文本行列表(lines)作为输入,列表中的每个元素是一个文本序列(如一条文本行)。每个文本序列又被拆分成一个词元列表,词元(token)是文本的基本单元,最后,返回一个由词元列表组成的列表,其中的每个词元都是一个字符串(string)

    def tokenize(lines,token='word'): #@save
        """将文本行拆分为单词或字符词元"""
        if token == 'word':
            return [line.split() for line in lines]
        elif token == 'char':
            return [list(line) for line in lines]
        else:
            print('错误:未知词元类型:' + token)
            
    tokens = tokenize(lines)
    for i in range(11):
        print(tokens[i])
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    ['the', 'time', 'machine', 'by', 'h', 'g', 'wells']
    []
    []
    []
    []
    ['i']
    []
    []
    ['the', 'time', 'traveller', 'for', 'so', 'it', 'will', 'be', 'convenient', 'to', 'speak', 'of', 'him']
    ['was', 'expounding', 'a', 'recondite', 'matter', 'to', 'us', 'his', 'grey', 'eyes', 'shone', 'and']
    ['twinkled', 'and', 'his', 'usually', 'pale', 'face', 'was', 'flushed', 'and', 'animated', 'the']
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    3 - 词表

    词元的类型是字符串,⽽模型需要的输⼊是数字,因此这种类型不⽅便模型使⽤。现在,让我们构建⼀个字典,通常也叫做词表(vocabulary),⽤来将字符串类型的词元映射到从0开始的数字索引中

    1. 将训练集合中的所有文档合并在一起,对它们的唯一词元进行统计,得到的统计结果称之为语料(corpus)
    2. 根据每个唯一词元的出现频率,为其分配一个数字索引
    3. 很少出现的词元通常被移除,降低复杂性。另外,语料库中不存在或已删除的任何词元都将映射到⼀个特定的未知词元“”
    4. 我们可以选择增加一个列表,用于保存哪些被保留的词元,例如;填充词元“”;序列开始词元“”;序列结束词元“
    class Vocab: #@save
        """文本词表"""
        def __init__(self,tokens=None,min_freq=0,reserved_tokens=None):
            if tokens is None:
                tokens = []
            if reserved_tokens is None:
                reserved_tokens = []
            # 按出现频率排序
            counter = count_corpus(tokens)
            self._token_freqs = sorted(counter.items(),key=lambda x: x[1],reverse=True)
            #未知词元的索引为0
            self.idx_to_token = [''] + reserved_tokens
            self.token_to_idx = {token: idx for idx,token in enumerate(self.idx_to_token)}
            
            for token,freq in self._token_freqs:
                if freq < min_freq:
                    break
                if token not in self.token_to_idx:
                    self.idx_to_token.append(token)
                    self.token_to_idx[token] = len(self.idx_to_token) - 1
                    
        def __len__(self):
            return len(self.idx_to_token)
        
        def __getitem__(self,tokens):
            if not isinstance(tokens,(list,tuple)):
                return self.token_to_idx.get(tokens,self.unk)
            return [self.__getitem__(token) for token in tokens]
        
        def to_tokens(slef,indices):
            if not isinstance(indices,(list,tuple)):
                return self.idx_to_token[indices]
            return [self.idex_to_token[index] for index in indices]
        
        @property
        def unk(self): # 未知词元的索引为0
            return 0
        
        @property
        def token_freqs(self):
            return self._token_freqs
        
    def count_corpus(tokens): #@save
        """统计词元的频率"""
        # 这里的tokens是1D列表或2D列表
        if len(tokens) == 0 or isinstance(tokens[0],list):
            # 将词元列表展平成一个列表
            tokens = [token for line in tokens for token in line]
        return collections.Counter(tokens)
    
    • 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

    我们首先使用时光机器数据集作为语料库来构建词表,然后打印前几个高频词元及其索引

    vocab = Vocab(tokens)
    print(list(vocab.token_to_idx.items())[:10])
    
    • 1
    • 2
    [('', 0), ('the', 1), ('i', 2), ('and', 3), ('of', 4), ('a', 5), ('to', 6), ('was', 7), ('in', 8), ('that', 9)]
    
    • 1

    现在,我们可以将每一条文本行转换成一个数字索引列表

    for i in [0,10]:
        print('文本',tokens[i])
        print('索引',vocab[tokens[i]])
    
    • 1
    • 2
    • 3
    文本 ['the', 'time', 'machine', 'by', 'h', 'g', 'wells']
    索引 [1, 19, 50, 40, 2183, 2184, 400]
    文本 ['twinkled', 'and', 'his', 'usually', 'pale', 'face', 'was', 'flushed', 'and', 'animated', 'the']
    索引 [2186, 3, 25, 1044, 362, 113, 7, 1421, 3, 1045, 1]
    
    • 1
    • 2
    • 3
    • 4

    4 - 整合所有功能

    在使⽤上述函数时,我们将所有功能打包到load_corpus_time_machine函数中,该函数返回corpus(词元索引列表)和vocab(时光机器语料库的词表)。我们在这⾥所做的改变是:

    1. 为了简化后面章节中的训练,我们使用字符实现文本词元化
    2. 时光机器数据集中的每个文本行不一定是一个句子或一个段落,还可能是一个单词,因此返回的corpus仅处理为单个列表,而不是使用多词元列表构成的一个列表
    def load_corpus_time_machine(max_tokens=-1): #@save
        """返回时光机器数据集的词元索引列表和词表"""
        lines = read_time_machine()
        tokens = tokenize(lines,'char')
        vocab = Vocab(tokens)
        # 因为时光机器数据集中的每个文本行不一定是一个句子或一个段落
        # 所以将所有文本行展平到一个列表中
        corpus = [vocab[token] for line in tokens for token in line]
        if max_tokens > 0:
            corpus = corpus[:max_tokens]
        return corpus,vocab
    
    corpus,vocab = load_corpus_time_machine()
    len(corpus),len(vocab)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    (170580, 28)
    
    • 1

    5 - 小结

    • 文本是序列数据的一种最常见的形式之一
    • 为了对文本进行预处理,我们通常将文本拆分为词元,构建词表将词元字符映射为数字索引,并将文本数据转换为词元索引以供模型操作
  • 相关阅读:
    ArrayList集合方法(自写)
    SQL注入详解
    【Django 03】QuerySet 和 Instance应用
    5-3 pytorch中的损失函数
    第4章_3——索引的使用
    人在囧途,你该怎么办?
    this is incompatible with sql_mode=only_full_group_by解决方案
    交叉验证和网格验证的方法
    北京程序员的真实一天!!!!!
    面部检测与特征分析:视频实时美颜SDK的核心组件
  • 原文地址:https://blog.csdn.net/mynameisgt/article/details/126798430