第二天-文本預(yù)處理,語(yǔ)言模型,循環(huán)神經(jīng)網(wǎng)絡(luò)

文本預(yù)處理

文本是一類序列數(shù)據(jù),一篇文章可以看作是字符或單詞的序列牍帚,本節(jié)將介紹文本數(shù)據(jù)的常見(jiàn)預(yù)處理步驟柜某,預(yù)處理通常包括四個(gè)步驟:

  1. 讀入文本
  2. 分詞
  3. 建立字典,將每個(gè)詞映射到一個(gè)唯一的索引(index)
  4. 將文本從詞的序列轉(zhuǎn)換為索引的序列咪啡,方便輸入模型

讀入文本

我們用一部英文小說(shuō),即H. G. Well的Time Machine暮屡,作為示例撤摸,展示文本預(yù)處理的具體過(guò)程。

import collections
import re

def read_time_machine():
    with open('/home/kesci/input/timemachine7163/timemachine.txt', 'r') as f:
        lines = [re.sub('[^a-z]+', ' ', line.strip().lower()) for line in f]
    return lines


lines = read_time_machine()
print('# sentences %d' % len(lines))
# sentences 3221

分詞

我們對(duì)每個(gè)句子進(jìn)行分詞褒纲,也就是將一個(gè)句子劃分成若干個(gè)詞(token)准夷,轉(zhuǎn)換為一個(gè)詞的序列。

def tokenize(sentences, token='word'):
    """Split sentences into word or char tokens"""
    if token == 'word':
        return [sentence.split(' ') for sentence in sentences]
    elif token == 'char':
        return [list(sentence) for sentence in sentences]
    else:
        print('ERROR: unkown token type '+token)

tokens = tokenize(lines)
tokens[0:10]
[['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']]

建立字典

為了方便模型處理莺掠,我們需要將字符串轉(zhuǎn)換為數(shù)字衫嵌。因此我們需要先構(gòu)建一個(gè)字典(vocabulary)角雷,將每個(gè)詞映射到一個(gè)唯一的索引編號(hào)璧亚。

class Vocab(object):
    def __init__(self, tokens, min_freq=0, use_special_tokens=False):
        counter = count_corpus(tokens)  # : 
        self.token_freqs = list(counter.items())
        self.idx_to_token = []
        if use_special_tokens:
            # padding, begin of sentence, end of sentence, unknown
            self.pad, self.bos, self.eos, self.unk = (0, 1, 2, 3)
            self.idx_to_token += ['', '', '', '']
        else:
            self.unk = 0
            self.idx_to_token += ['']
        self.idx_to_token += [token for token, freq in self.token_freqs
                        if freq >= min_freq and token not in self.idx_to_token]
        self.token_to_idx = dict()
        for idx, token in enumerate(self.idx_to_token):
            self.token_to_idx[token] = idx

    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(self, indices):
        if not isinstance(indices, (list, tuple)):
            return self.idx_to_token[indices]
        return [self.idx_to_token[index] for index in indices]

def count_corpus(sentences):
    tokens = [tk for st in sentences for tk in st]
    return collections.Counter(tokens)  # 返回一個(gè)字典,記錄每個(gè)詞的出現(xiàn)次數(shù)

我們看一個(gè)例子辩诞,這里我們嘗試用Time Machine作為語(yǔ)料構(gòu)建字典

vocab = Vocab(tokens)
print(list(vocab.token_to_idx.items())[0:20])
[('', 0), ('the', 1), ('time', 2), ('machine', 3), ('by', 4), ('h', 5), ('g', 6), ('wells', 7), ('i', 8), ('traveller', 9), ('for', 10), ('so', 11), ('it', 12), ('will', 13), ('be', 14), ('convenient', 15), ('to', 16), ('speak', 17), ('of', 18), ('him', 19)]

將詞轉(zhuǎn)為索引

使用字典唇兑,我們可以將原文本中的句子從單詞序列轉(zhuǎn)換為索引序列

for i in range(0, 10):
    print('words:', tokens[i])
    print('indices:', vocab[tokens[i]])
words: ['the', 'time', 'machine', 'by', 'h', 'g', 'wells', '']
indices: [1, 2, 3, 4, 5, 6, 7, 0]
words: ['']
indices: [0]
words: ['']
indices: [0]
words: ['']
indices: [0]
words: ['']
indices: [0]
words: ['i']
indices: [8]
words: ['']
indices: [0]
words: ['']
indices: [0]
words: ['the', 'time', 'traveller', 'for', 'so', 'it', 'will', 'be', 'convenient', 'to', 'speak', 'of', 'him', '']
indices: [1, 2, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 0]
words: ['was', 'expounding', 'a', 'recondite', 'matter', 'to', 'us', 'his', 'grey', 'eyes', 'shone', 'and']
indices: [20, 21, 22, 23, 24, 16, 25, 26, 27, 28, 29, 30]

用現(xiàn)有工具進(jìn)行分詞

我們前面介紹的分詞方式非常簡(jiǎn)單酒朵,它至少有以下幾個(gè)缺點(diǎn):

  1. 標(biāo)點(diǎn)符號(hào)通常可以提供語(yǔ)義信息扎附,但是我們的方法直接將其丟棄了
  2. 類似“shouldn't", "doesn't"這樣的詞會(huì)被錯(cuò)誤地處理
  3. 類似"Mr.", "Dr."這樣的詞會(huì)被錯(cuò)誤地處理

我們可以通過(guò)引入更復(fù)雜的規(guī)則來(lái)解決這些問(wèn)題蔫耽,但是事實(shí)上,有一些現(xiàn)有的工具可以很好地進(jìn)行分詞留夜,我們?cè)谶@里簡(jiǎn)單介紹其中的兩個(gè):spaCyNLTK匙铡。

下面是一個(gè)簡(jiǎn)單的例子:

text = "Mr. Chen doesn't agree with my suggestion."

spaCy:

import spacy
nlp = spacy.load('en_core_web_sm')
doc = nlp(text)
print([token.text for token in doc])
['Mr.', 'Chen', 'does', "n't", 'agree', 'with', 'my', 'suggestion', '.']

NLTK:

from nltk.tokenize import word_tokenize
from nltk import data
data.path.append('/home/kesci/input/nltk_data3784/nltk_data')
print(word_tokenize(text))

語(yǔ)言模型

一段自然語(yǔ)言文本可以看作是一個(gè)離散時(shí)間序列,給定一個(gè)長(zhǎng)度為T的詞的序列w_1, w_2, \ldots, w_T碍粥,語(yǔ)言模型的目標(biāo)就是評(píng)估該序列是否合理鳖眼,即計(jì)算該序列的概率:

P(w_1, w_2, \ldots, w_T).

本節(jié)我們介紹基于統(tǒng)計(jì)的語(yǔ)言模型,主要是n元語(yǔ)法(n-gram)嚼摩。在后續(xù)內(nèi)容中钦讳,我們將會(huì)介紹基于神經(jīng)網(wǎng)絡(luò)的語(yǔ)言模型。

語(yǔ)言模型

假設(shè)序列w_1, w_2, \ldots, w_T中的每個(gè)詞是依次生成的低斋,我們有

\begin{align*} P(w_1, w_2, \ldots, w_T) &= \prod_{t=1}^T P(w_t \mid w_1, \ldots, w_{t-1})\\ &= P(w_1)P(w_2 \mid w_1) \cdots P(w_T \mid w_1w_2\cdots w_{T-1}) \end{align*}

例如,一段含有4個(gè)詞的文本序列的概率

P(w_1, w_2, w_3, w_4) = P(w_1) P(w_2 \mid w_1) P(w_3 \mid w_1, w_2) P(w_4 \mid w_1, w_2, w_3).

語(yǔ)言模型的參數(shù)就是詞的概率以及給定前幾個(gè)詞情況下的條件概率匪凡。設(shè)訓(xùn)練數(shù)據(jù)集為一個(gè)大型文本語(yǔ)料庫(kù)膊畴,如維基百科的所有條目,詞的概率可以通過(guò)該詞在訓(xùn)練數(shù)據(jù)集中的相對(duì)詞頻來(lái)計(jì)算病游,例如唇跨,w_1的概率可以計(jì)算為:

\hat P(w_1) = \frac{n(w_1)}{n}

其中n(w_1)為語(yǔ)料庫(kù)中以w_1作為第一個(gè)詞的文本的數(shù)量稠通,n為語(yǔ)料庫(kù)中文本的總數(shù)量。

類似的买猖,給定w_1情況下改橘,w_2的條件概率可以計(jì)算為:

\hat P(w_2 \mid w_1) = \frac{n(w_1, w_2)}{n(w_1)}

其中n(w_1, w_2)為語(yǔ)料庫(kù)中以w_1作為第一個(gè)詞,w_2作為第二個(gè)詞的文本的數(shù)量玉控。

n元語(yǔ)法

序列長(zhǎng)度增加飞主,計(jì)算和存儲(chǔ)多個(gè)詞共同出現(xiàn)的概率的復(fù)雜度會(huì)呈指數(shù)級(jí)增加。n元語(yǔ)法通過(guò)馬爾可夫假設(shè)簡(jiǎn)化模型高诺,馬爾科夫假設(shè)是指一個(gè)詞的出現(xiàn)只與前面n個(gè)詞相關(guān)碌识,即n階馬爾可夫鏈(Markov chain of order n),如果n=1虱而,那么有P(w_3 \mid w_1, w_2) = P(w_3 \mid w_2)筏餐。基于n-1階馬爾可夫鏈牡拇,我們可以將語(yǔ)言模型改寫(xiě)為

P(w_1, w_2, \ldots, w_T) = \prod_{t=1}^T P(w_t \mid w_{t-(n-1)}, \ldots, w_{t-1}) .

以上也叫n元語(yǔ)法(n-grams)魁瞪,它是基于n - 1階馬爾可夫鏈的概率語(yǔ)言模型。例如惠呼,當(dāng)n=2時(shí)导俘,含有4個(gè)詞的文本序列的概率就可以改寫(xiě)為:

\begin{align*} P(w_1, w_2, w_3, w_4) &= P(w_1) P(w_2 \mid w_1) P(w_3 \mid w_1, w_2) P(w_4 \mid w_1, w_2, w_3)\\ &= P(w_1) P(w_2 \mid w_1) P(w_3 \mid w_2) P(w_4 \mid w_3) \end{align*}

當(dāng)n分別為1、2和3時(shí)罢杉,我們將其分別稱作一元語(yǔ)法(unigram)趟畏、二元語(yǔ)法(bigram)和三元語(yǔ)法(trigram)。例如滩租,長(zhǎng)度為4的序列w_1, w_2, w_3, w_4在一元語(yǔ)法赋秀、二元語(yǔ)法和三元語(yǔ)法中的概率分別為

\begin{aligned} P(w_1, w_2, w_3, w_4) &= P(w_1) P(w_2) P(w_3) P(w_4) ,\\ P(w_1, w_2, w_3, w_4) &= P(w_1) P(w_2 \mid w_1) P(w_3 \mid w_2) P(w_4 \mid w_3) ,\\ P(w_1, w_2, w_3, w_4) &= P(w_1) P(w_2 \mid w_1) P(w_3 \mid w_1, w_2) P(w_4 \mid w_2, w_3) . \end{aligned}

當(dāng)n較小時(shí),n元語(yǔ)法往往并不準(zhǔn)確律想。例如猎莲,在一元語(yǔ)法中,由三個(gè)詞組成的句子“你走先”和“你先走”的概率是一樣的技即。然而著洼,當(dāng)n較大時(shí),n元語(yǔ)法需要計(jì)算并存儲(chǔ)大量的詞頻和多詞相鄰頻率而叼。

思考:n元語(yǔ)法可能有哪些缺陷身笤?

  1. 參數(shù)空間過(guò)大
  2. 數(shù)據(jù)稀疏

語(yǔ)言模型數(shù)據(jù)集

讀取數(shù)據(jù)集

with open('/home/kesci/input/jaychou_lyrics4703/jaychou_lyrics.txt') as f:
    corpus_chars = f.read()
print(len(corpus_chars))
print(corpus_chars[: 40])
corpus_chars = corpus_chars.replace('\n', ' ').replace('\r', ' ')
corpus_chars = corpus_chars[: 10000]
63282
想要有直升機(jī)
想要和你飛到宇宙去
想要和你融化在一起
融化在宇宙里
我每天每天每

建立字符索引

idx_to_char = list(set(corpus_chars)) # 去重,得到索引到字符的映射
char_to_idx = {char: i for i, char in enumerate(idx_to_char)} # 字符到索引的映射
vocab_size = len(char_to_idx)
print(vocab_size)

corpus_indices = [char_to_idx[char] for char in corpus_chars]  # 將每個(gè)字符轉(zhuǎn)化為索引葵陵,得到一個(gè)索引的序列
sample = corpus_indices[: 20]
print('chars:', ''.join([idx_to_char[idx] for idx in sample]))
print('indices:', sample)
1027
chars: 想要有直升機(jī) 想要和你飛到宇宙去 想要和
indices: [824, 903, 535, 895, 691, 561, 239, 824, 903, 559, 849, 19, 179, 32, 746, 1000, 239, 824, 903, 559]

定義函數(shù)load_data_jay_lyrics液荸,在后續(xù)章節(jié)中直接調(diào)用。

def load_data_jay_lyrics():
    with open('/home/kesci/input/jaychou_lyrics4703/jaychou_lyrics.txt') as f:
        corpus_chars = f.read()
    corpus_chars = corpus_chars.replace('\n', ' ').replace('\r', ' ')
    corpus_chars = corpus_chars[0:10000]
    idx_to_char = list(set(corpus_chars))
    char_to_idx = dict([(char, i) for i, char in enumerate(idx_to_char)])
    vocab_size = len(char_to_idx)
    corpus_indices = [char_to_idx[char] for char in corpus_chars]
    return corpus_indices, char_to_idx, idx_to_char, vocab_size

時(shí)序數(shù)據(jù)的采樣

在訓(xùn)練中我們需要每次隨機(jī)讀取小批量樣本和標(biāo)簽脱篙。與之前章節(jié)的實(shí)驗(yàn)數(shù)據(jù)不同的是娇钱,時(shí)序數(shù)據(jù)的一個(gè)樣本通常包含連續(xù)的字符伤柄。假設(shè)時(shí)間步數(shù)為5,樣本序列為5個(gè)字符文搂,即“想”“要”“有”“直”“升”适刀。該樣本的標(biāo)簽序列為這些字符分別在訓(xùn)練集中的下一個(gè)字符,即“要”“有”“直”“升”“機(jī)”煤蹭,即X=“想要有直升”笔喉,Y=“要有直升機(jī)”。

現(xiàn)在我們考慮序列“想要有直升機(jī)疯兼,想要和你飛到宇宙去”然遏,如果時(shí)間步數(shù)為5,有以下可能的樣本和標(biāo)簽:

  • X:“想要有直升”吧彪,Y:“要有直升機(jī)”
  • X:“要有直升機(jī)”待侵,Y:“有直升機(jī),”
  • X:“有直升機(jī)姨裸,”秧倾,Y:“直升機(jī),想”
  • ...
  • X:“要和你飛到”傀缩,Y:“和你飛到宇”
  • X:“和你飛到宇”那先,Y:“你飛到宇宙”
  • X:“你飛到宇宙”,Y:“飛到宇宙去”

可以看到赡艰,如果序列的長(zhǎng)度為T售淡,時(shí)間步數(shù)為n,那么一共有T-n個(gè)合法的樣本慷垮,但是這些樣本有大量的重合揖闸,我們通常采用更加高效的采樣方式。我們有兩種方式對(duì)時(shí)序數(shù)據(jù)進(jìn)行采樣料身,分別是隨機(jī)采樣和相鄰采樣汤纸。

隨機(jī)采樣

下面的代碼每次從數(shù)據(jù)里隨機(jī)采樣一個(gè)小批量。其中批量大小batch_size是每個(gè)小批量的樣本數(shù)芹血,num_steps是每個(gè)樣本所包含的時(shí)間步數(shù)贮泞。
在隨機(jī)采樣中,每個(gè)樣本是原始序列上任意截取的一段序列幔烛,相鄰的兩個(gè)隨機(jī)小批量在原始序列上的位置不一定相毗鄰啃擦。

import torch
import random
def data_iter_random(corpus_indices, batch_size, num_steps, device=None):
    # 減1是因?yàn)閷?duì)于長(zhǎng)度為n的序列,X最多只有包含其中的前n - 1個(gè)字符
    num_examples = (len(corpus_indices) - 1) // num_steps  # 下取整饿悬,得到不重疊情況下的樣本個(gè)數(shù)
    example_indices = [i * num_steps for i in range(num_examples)]  # 每個(gè)樣本的第一個(gè)字符在corpus_indices中的下標(biāo)
    random.shuffle(example_indices)

    def _data(i):
        # 返回從i開(kāi)始的長(zhǎng)為num_steps的序列
        return corpus_indices[i: i + num_steps]
    if device is None:
        device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    
    for i in range(0, num_examples, batch_size):
        # 每次選出batch_size個(gè)隨機(jī)樣本
        batch_indices = example_indices[i: i + batch_size]  # 當(dāng)前batch的各個(gè)樣本的首字符的下標(biāo)
        X = [_data(j) for j in batch_indices]
        Y = [_data(j + 1) for j in batch_indices]
        yield torch.tensor(X, device=device), torch.tensor(Y, device=device)

測(cè)試一下這個(gè)函數(shù)令蛉,我們輸入從0到29的連續(xù)整數(shù)作為一個(gè)人工序列,設(shè)批量大小和時(shí)間步數(shù)分別為2和6乡恕,打印隨機(jī)采樣每次讀取的小批量樣本的輸入X和標(biāo)簽Y言询。

my_seq = list(range(10))
for X, Y in data_iter_random(my_seq, batch_size=2, num_steps=2):
    print('X: ', X, '\nY:', Y, '\n')
X:  tensor([[4, 5],
        [6, 7]]) 
Y: tensor([[5, 6],
        [7, 8]]) 

X:  tensor([[2, 3],
        [0, 1]]) 
Y: tensor([[3, 4],
        [1, 2]]) 

相鄰采樣

在相鄰采樣中,相鄰的兩個(gè)隨機(jī)小批量在原始序列上的位置相毗鄰傲宜。

def data_iter_consecutive(corpus_indices, batch_size, num_steps, device=None):
    if device is None:
        device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    corpus_len = len(corpus_indices) // batch_size * batch_size  # 保留下來(lái)的序列的長(zhǎng)度
    corpus_indices = corpus_indices[: corpus_len]  # 僅保留前corpus_len個(gè)字符
    indices = torch.tensor(corpus_indices, device=device)
    indices = indices.view(batch_size, -1)  # resize成(batch_size, )
    batch_num = (indices.shape[1] - 1) // num_steps
    for i in range(batch_num):
        i = i * num_steps
        X = indices[:, i: i + num_steps]
        Y = indices[:, i + 1: i + num_steps + 1]
        yield X, Y

同樣的設(shè)置下运杭,打印相鄰采樣每次讀取的小批量樣本的輸入X和標(biāo)簽Y。相鄰的兩個(gè)隨機(jī)小批量在原始序列上的位置相毗鄰函卒。

for X, Y in data_iter_consecutive(my_seq, batch_size=2, num_steps=2):
    print('X: ', X, '\nY:', Y, '\n')
X:  tensor([[0, 1],
        [5, 6]]) 
Y: tensor([[1, 2],
        [6, 7]]) 

X:  tensor([[2, 3],
        [7, 8]]) 
Y: tensor([[3, 4],
        [8, 9]]) 

循環(huán)神經(jīng)網(wǎng)絡(luò)

本節(jié)介紹循環(huán)神經(jīng)網(wǎng)絡(luò)辆憔,下圖展示了如何基于循環(huán)神經(jīng)網(wǎng)絡(luò)實(shí)現(xiàn)語(yǔ)言模型。我們的目的是基于當(dāng)前的輸入與過(guò)去的輸入序列报嵌,預(yù)測(cè)序列的下一個(gè)字符虱咧。循環(huán)神經(jīng)網(wǎng)絡(luò)引入一個(gè)隱藏變量H,用H_{t}表示H在時(shí)間步t的值锚国。H_{t}的計(jì)算基于X_{t}H_{t-1}腕巡,可以認(rèn)為H_{t}記錄了到當(dāng)前字符為止的序列信息,利用H_{t}對(duì)序列的下一個(gè)字符進(jìn)行預(yù)測(cè)血筑。

Image Name

循環(huán)神經(jīng)網(wǎng)絡(luò)的構(gòu)造

我們先看循環(huán)神經(jīng)網(wǎng)絡(luò)的具體構(gòu)造绘沉。假設(shè)\boldsymbol{X}_t \in \mathbb{R}^{n \times d}是時(shí)間步t的小批量輸入,\boldsymbol{H}_t \in \mathbb{R}^{n \times h}是該時(shí)間步的隱藏變量豺总,則:

\boldsymbol{H}_t = \phi(\boldsymbol{X}_t \boldsymbol{W}_{xh} + \boldsymbol{H}_{t-1} \boldsymbol{W}_{hh} + \boldsymbol车伞_h).

其中,\boldsymbol{W}_{xh} \in \mathbb{R}^{d \times h}喻喳,\boldsymbol{W}_{hh} \in \mathbb{R}^{h \times h}另玖,\boldsymbol_{h} \in \mathbb{R}^{1 \times h}表伦,\phi函數(shù)是非線性激活函數(shù)谦去。由于引入了\boldsymbol{H}_{t-1} \boldsymbol{W}_{hh}H_{t}能夠捕捉截至當(dāng)前時(shí)間步的序列的歷史信息绑榴,就像是神經(jīng)網(wǎng)絡(luò)當(dāng)前時(shí)間步的狀態(tài)或記憶一樣哪轿。由于H_{t}的計(jì)算基于H_{t-1},上式的計(jì)算是循環(huán)的翔怎,使用循環(huán)計(jì)算的網(wǎng)絡(luò)即循環(huán)神經(jīng)網(wǎng)絡(luò)(recurrent neural network)窃诉。

在時(shí)間步t,輸出層的輸出為:

\boldsymbol{O}_t = \boldsymbol{H}_t \boldsymbol{W}_{hq} + \boldsymbol赤套_q.

其中\boldsymbol{W}_{hq} \in \mathbb{R}^{h \times q}飘痛,\boldsymbol_q \in \mathbb{R}^{1 \times q}容握。

從零開(kāi)始實(shí)現(xiàn)循環(huán)神經(jīng)網(wǎng)絡(luò)

我們先嘗試從零開(kāi)始實(shí)現(xiàn)一個(gè)基于字符級(jí)循環(huán)神經(jīng)網(wǎng)絡(luò)的語(yǔ)言模型宣脉,這里我們使用周杰倫的歌詞作為語(yǔ)料,首先我們讀入數(shù)據(jù):

import torch
import torch.nn as nn
import time
import math
import sys
sys.path.append("/home/kesci/input")
import d2l_jay9460 as d2l
(corpus_indices, char_to_idx, idx_to_char, vocab_size) = d2l.load_data_jay_lyrics()
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

one-hot向量

我們需要將字符表示成向量剔氏,這里采用one-hot向量塑猖。假設(shè)詞典大小是N竹祷,每次字符對(duì)應(yīng)一個(gè)從0N-1的唯一的索引,則該字符的向量是一個(gè)長(zhǎng)度為N的向量羊苟,若字符的索引是i塑陵,則該向量的第i個(gè)位置為1,其他位置為0蜡励。下面分別展示了索引為0和2的one-hot向量令花,向量長(zhǎng)度等于詞典大小。

def one_hot(x, n_class, dtype=torch.float32):
    result = torch.zeros(x.shape[0], n_class, dtype=dtype, device=x.device)  # shape: (n, n_class)
    result.scatter_(1, x.long().view(-1, 1), 1)  # result[i, x[i, 0]] = 1
    return result
    
x = torch.tensor([0, 2])
x_one_hot = one_hot(x, vocab_size)
print(x_one_hot)
print(x_one_hot.shape)
print(x_one_hot.sum(axis=1))
tensor([[1., 0., 0.,  ..., 0., 0., 0.],
        [0., 0., 1.,  ..., 0., 0., 0.]])
torch.Size([2, 1027])
tensor([1., 1.])

我們每次采樣的小批量的形狀是(批量大小, 時(shí)間步數(shù))凉倚。下面的函數(shù)將這樣的小批量變換成數(shù)個(gè)形狀為(批量大小, 詞典大屑娑肌)的矩陣,矩陣個(gè)數(shù)等于時(shí)間步數(shù)稽寒。也就是說(shuō)扮碧,時(shí)間步t的輸入為\boldsymbol{X}_t \in \mathbb{R}^{n \times d},其中n為批量大小杏糙,d為詞向量大小芬萍,即one-hot向量長(zhǎng)度(詞典大小)搔啊。

def to_onehot(X, n_class):
    return [one_hot(X[:, i], n_class) for i in range(X.shape[1])]

X = torch.arange(10).view(2, 5)
inputs = to_onehot(X, vocab_size)
print(len(inputs), inputs[0].shape)
5 torch.Size([2, 1027])

初始化模型參數(shù)

num_inputs, num_hiddens, num_outputs = vocab_size, 256, vocab_size
# num_inputs: d
# num_hiddens: h, 隱藏單元的個(gè)數(shù)是超參數(shù)
# num_outputs: q

def get_params():
    def _one(shape):
        param = torch.zeros(shape, device=device, dtype=torch.float32)
        nn.init.normal_(param, 0, 0.01)
        return torch.nn.Parameter(param)

    # 隱藏層參數(shù)
    W_xh = _one((num_inputs, num_hiddens))
    W_hh = _one((num_hiddens, num_hiddens))
    b_h = torch.nn.Parameter(torch.zeros(num_hiddens, device=device))
    # 輸出層參數(shù)
    W_hq = _one((num_hiddens, num_outputs))
    b_q = torch.nn.Parameter(torch.zeros(num_outputs, device=device))
    return (W_xh, W_hh, b_h, W_hq, b_q)

定義模型

函數(shù)rnn用循環(huán)的方式依次完成循環(huán)神經(jīng)網(wǎng)絡(luò)每個(gè)時(shí)間步的計(jì)算柬祠。

def rnn(inputs, state, params):
    # inputs和outputs皆為num_steps個(gè)形狀為(batch_size, vocab_size)的矩陣
    W_xh, W_hh, b_h, W_hq, b_q = params
    H, = state
    outputs = []
    for X in inputs:
        H = torch.tanh(torch.matmul(X, W_xh) + torch.matmul(H, W_hh) + b_h)
        Y = torch.matmul(H, W_hq) + b_q
        outputs.append(Y)
    return outputs, (H,)

函數(shù)init_rnn_state初始化隱藏變量,這里的返回值是一個(gè)元組负芋。

def init_rnn_state(batch_size, num_hiddens, device):
    return (torch.zeros((batch_size, num_hiddens), device=device), )

做個(gè)簡(jiǎn)單的測(cè)試來(lái)觀察輸出結(jié)果的個(gè)數(shù)(時(shí)間步數(shù))漫蛔,以及第一個(gè)時(shí)間步的輸出層輸出的形狀和隱藏狀態(tài)的形狀。

print(X.shape)
print(num_hiddens)
print(vocab_size)
state = init_rnn_state(X.shape[0], num_hiddens, device)
inputs = to_onehot(X.to(device), vocab_size)
params = get_params()
outputs, state_new = rnn(inputs, state, params)
print(len(inputs), inputs[0].shape)
print(len(outputs), outputs[0].shape)
print(len(state), state[0].shape)
print(len(state_new), state_new[0].shape)
torch.Size([2, 5])
256
1027
5 torch.Size([2, 1027])
5 torch.Size([2, 1027])
1 torch.Size([2, 256])
1 torch.Size([2, 256])

裁剪梯度

循環(huán)神經(jīng)網(wǎng)絡(luò)中較容易出現(xiàn)梯度衰減或梯度爆炸旧蛾,這會(huì)導(dǎo)致網(wǎng)絡(luò)幾乎無(wú)法訓(xùn)練莽龟。裁剪梯度(clip gradient)是一種應(yīng)對(duì)梯度爆炸的方法。假設(shè)我們把所有模型參數(shù)的梯度拼接成一個(gè)向量 \boldsymbol{g}锨天,并設(shè)裁剪的閾值是\theta毯盈。裁剪后的梯度

\min\left(\frac{\theta}{\|\boldsymbol{g}\|}, 1\right)\boldsymbol{g}

L_2范數(shù)不超過(guò)\theta

def grad_clipping(params, theta, device):
    norm = torch.tensor([0.0], device=device)
    for param in params:
        norm += (param.grad.data ** 2).sum()
    norm = norm.sqrt().item()
    if norm > theta:
        for param in params:
            param.grad.data *= (theta / norm)

定義預(yù)測(cè)函數(shù)

以下函數(shù)基于前綴prefix(含有數(shù)個(gè)字符的字符串)來(lái)預(yù)測(cè)接下來(lái)的num_chars個(gè)字符病袄。這個(gè)函數(shù)稍顯復(fù)雜搂赋,其中我們將循環(huán)神經(jīng)單元rnn設(shè)置成了函數(shù)參數(shù),這樣在后面小節(jié)介紹其他循環(huán)神經(jīng)網(wǎng)絡(luò)時(shí)能重復(fù)使用這個(gè)函數(shù)益缠。

def predict_rnn(prefix, num_chars, rnn, params, init_rnn_state,
                num_hiddens, vocab_size, device, idx_to_char, char_to_idx):
    state = init_rnn_state(1, num_hiddens, device)
    output = [char_to_idx[prefix[0]]]   # output記錄prefix加上預(yù)測(cè)的num_chars個(gè)字符
    for t in range(num_chars + len(prefix) - 1):
        # 將上一時(shí)間步的輸出作為當(dāng)前時(shí)間步的輸入
        X = to_onehot(torch.tensor([[output[-1]]], device=device), vocab_size)
        # 計(jì)算輸出和更新隱藏狀態(tài)
        (Y, state) = rnn(X, state, params)
        # 下一個(gè)時(shí)間步的輸入是prefix里的字符或者當(dāng)前的最佳預(yù)測(cè)字符
        if t < len(prefix) - 1:
            output.append(char_to_idx[prefix[t + 1]])
        else:
            output.append(Y[0].argmax(dim=1).item())
    return ''.join([idx_to_char[i] for i in output])

我們先測(cè)試一下predict_rnn函數(shù)脑奠。我們將根據(jù)前綴“分開(kāi)”創(chuàng)作長(zhǎng)度為10個(gè)字符(不考慮前綴長(zhǎng)度)的一段歌詞。因?yàn)槟P蛥?shù)為隨機(jī)值幅慌,所以預(yù)測(cè)結(jié)果也是隨機(jī)的宋欺。

predict_rnn('分開(kāi)', 10, rnn, params, init_rnn_state, num_hiddens, vocab_size,
            device, idx_to_char, char_to_idx)
'分開(kāi)玫東香代丘恨妥雕微蕃'

困惑度

我們通常使用困惑度(perplexity)來(lái)評(píng)價(jià)語(yǔ)言模型的好壞。回憶一下“softmax回歸”一節(jié)中交叉熵?fù)p失函數(shù)的定義齿诞。困惑度是對(duì)交叉熵?fù)p失函數(shù)做指數(shù)運(yùn)算后得到的值酸休。特別地,

  • 最佳情況下祷杈,模型總是把標(biāo)簽類別的概率預(yù)測(cè)為1雨席,此時(shí)困惑度為1;
  • 最壞情況下吠式,模型總是把標(biāo)簽類別的概率預(yù)測(cè)為0,此時(shí)困惑度為正無(wú)窮抽米;
  • 基線情況下特占,模型總是預(yù)測(cè)所有類別的概率都相同,此時(shí)困惑度為類別個(gè)數(shù)云茸。

顯然是目,任何一個(gè)有效模型的困惑度必須小于類別個(gè)數(shù)。在本例中标捺,困惑度必須小于詞典大小vocab_size懊纳。

定義模型訓(xùn)練函數(shù)

跟之前章節(jié)的模型訓(xùn)練函數(shù)相比,這里的模型訓(xùn)練函數(shù)有以下幾點(diǎn)不同:

  1. 使用困惑度評(píng)價(jià)模型亡容。
  2. 在迭代模型參數(shù)前裁剪梯度嗤疯。
  3. 對(duì)時(shí)序數(shù)據(jù)采用不同采樣方法將導(dǎo)致隱藏狀態(tài)初始化的不同。
def train_and_predict_rnn(rnn, get_params, init_rnn_state, num_hiddens,
                          vocab_size, device, corpus_indices, idx_to_char,
                          char_to_idx, is_random_iter, num_epochs, num_steps,
                          lr, clipping_theta, batch_size, pred_period,
                          pred_len, prefixes):
    if is_random_iter:
        data_iter_fn = d2l.data_iter_random
    else:
        data_iter_fn = d2l.data_iter_consecutive
    params = get_params()
    loss = nn.CrossEntropyLoss()

    for epoch in range(num_epochs):
        if not is_random_iter:  # 如使用相鄰采樣闺兢,在epoch開(kāi)始時(shí)初始化隱藏狀態(tài)
            state = init_rnn_state(batch_size, num_hiddens, device)
        l_sum, n, start = 0.0, 0, time.time()
        data_iter = data_iter_fn(corpus_indices, batch_size, num_steps, device)
        for X, Y in data_iter:
            if is_random_iter:  # 如使用隨機(jī)采樣茂缚,在每個(gè)小批量更新前初始化隱藏狀態(tài)
                state = init_rnn_state(batch_size, num_hiddens, device)
            else:  # 否則需要使用detach函數(shù)從計(jì)算圖分離隱藏狀態(tài)
                for s in state:
                    s.detach_()
            # inputs是num_steps個(gè)形狀為(batch_size, vocab_size)的矩陣
            inputs = to_onehot(X, vocab_size)
            # outputs有num_steps個(gè)形狀為(batch_size, vocab_size)的矩陣
            (outputs, state) = rnn(inputs, state, params)
            # 拼接之后形狀為(num_steps * batch_size, vocab_size)
            outputs = torch.cat(outputs, dim=0)
            # Y的形狀是(batch_size, num_steps),轉(zhuǎn)置后再變成形狀為
            # (num_steps * batch_size,)的向量屋谭,這樣跟輸出的行一一對(duì)應(yīng)
            y = torch.flatten(Y.T)
            # 使用交叉熵?fù)p失計(jì)算平均分類誤差
            l = loss(outputs, y.long())
            
            # 梯度清0
            if params[0].grad is not None:
                for param in params:
                    param.grad.data.zero_()
            l.backward()
            grad_clipping(params, clipping_theta, device)  # 裁剪梯度
            d2l.sgd(params, lr, 1)  # 因?yàn)檎`差已經(jīng)取過(guò)均值脚囊,梯度不用再做平均
            l_sum += l.item() * y.shape[0]
            n += y.shape[0]

        if (epoch + 1) % pred_period == 0:
            print('epoch %d, perplexity %f, time %.2f sec' % (
                epoch + 1, math.exp(l_sum / n), time.time() - start))
            for prefix in prefixes:
                print(' -', predict_rnn(prefix, pred_len, rnn, params, init_rnn_state,
                    num_hiddens, vocab_size, device, idx_to_char, char_to_idx))

訓(xùn)練模型并創(chuàng)作歌詞

現(xiàn)在我們可以訓(xùn)練模型了。首先桐磁,設(shè)置模型超參數(shù)悔耘。我們將根據(jù)前綴“分開(kāi)”和“不分開(kāi)”分別創(chuàng)作長(zhǎng)度為50個(gè)字符(不考慮前綴長(zhǎng)度)的一段歌詞。我們每過(guò)50個(gè)迭代周期便根據(jù)當(dāng)前訓(xùn)練的模型創(chuàng)作一段歌詞我擂。

num_epochs, num_steps, batch_size, lr, clipping_theta = 250, 35, 32, 1e2, 1e-2
pred_period, pred_len, prefixes = 50, 50, ['分開(kāi)', '不分開(kāi)']

下面采用隨機(jī)采樣訓(xùn)練模型并創(chuàng)作歌詞衬以。

train_and_predict_rnn(rnn, get_params, init_rnn_state, num_hiddens,
                      vocab_size, device, corpus_indices, idx_to_char,
                      char_to_idx, True, num_epochs, num_steps, lr,
                      clipping_theta, batch_size, pred_period, pred_len,
                      prefixes)

接下來(lái)采用相鄰采樣訓(xùn)練模型并創(chuàng)作歌詞。

train_and_predict_rnn(rnn, get_params, init_rnn_state, num_hiddens,
                      vocab_size, device, corpus_indices, idx_to_char,
                      char_to_idx, False, num_epochs, num_steps, lr,
                      clipping_theta, batch_size, pred_period, pred_len,
                      prefixes)

循環(huán)神經(jīng)網(wǎng)絡(luò)的簡(jiǎn)介實(shí)現(xiàn)

定義模型

我們使用Pytorch中的nn.RNN來(lái)構(gòu)造循環(huán)神經(jīng)網(wǎng)絡(luò)校摩。在本節(jié)中泄鹏,我們主要關(guān)注nn.RNN的以下幾個(gè)構(gòu)造函數(shù)參數(shù):

  • input_size - The number of expected features in the input x
  • hidden_size – The number of features in the hidden state h
  • nonlinearity – The non-linearity to use. Can be either 'tanh' or 'relu'. Default: 'tanh'
  • batch_first – If True, then the input and output tensors are provided as (batch_size, num_steps, input_size). Default: False

這里的batch_first決定了輸入的形狀,我們使用默認(rèn)的參數(shù)False秧耗,對(duì)應(yīng)的輸入形狀是 (num_steps, batch_size, input_size)备籽。

forward函數(shù)的參數(shù)為:

  • input of shape (num_steps, batch_size, input_size): tensor containing the features of the input sequence.
  • h_0 of shape (num_layers * num_directions, batch_size, hidden_size): tensor containing the initial hidden state for each element in the batch. Defaults to zero if not provided. If the RNN is bidirectional, num_directions should be 2, else it should be 1.

forward函數(shù)的返回值是:

  • output of shape (num_steps, batch_size, num_directions * hidden_size): tensor containing the output features (h_t) from the last layer of the RNN, for each t.
  • h_n of shape (num_layers * num_directions, batch_size, hidden_size): tensor containing the hidden state for t = num_steps.

現(xiàn)在我們構(gòu)造一個(gè)nn.RNN實(shí)例,并用一個(gè)簡(jiǎn)單的例子來(lái)看一下輸出的形狀。

rnn_layer = nn.RNN(input_size=vocab_size, hidden_size=num_hiddens)
num_steps, batch_size = 35, 2
X = torch.rand(num_steps, batch_size, vocab_size)
state = None
Y, state_new = rnn_layer(X, state)
print(Y.shape, state_new.shape)

我們定義一個(gè)完整的基于循環(huán)神經(jīng)網(wǎng)絡(luò)的語(yǔ)言模型车猬。

class RNNModel(nn.Module):
    def __init__(self, rnn_layer, vocab_size):
        super(RNNModel, self).__init__()
        self.rnn = rnn_layer
        self.hidden_size = rnn_layer.hidden_size * (2 if rnn_layer.bidirectional else 1) 
        self.vocab_size = vocab_size
        self.dense = nn.Linear(self.hidden_size, vocab_size)

    def forward(self, inputs, state):
        # inputs.shape: (batch_size, num_steps)
        X = to_onehot(inputs, vocab_size)
        X = torch.stack(X)  # X.shape: (num_steps, batch_size, vocab_size)
        hiddens, state = self.rnn(X, state)
        hiddens = hiddens.view(-1, hiddens.shape[-1])  # hiddens.shape: (num_steps * batch_size, hidden_size)
        output = self.dense(hiddens)
        return output, state

類似的霉猛,我們需要實(shí)現(xiàn)一個(gè)預(yù)測(cè)函數(shù),與前面的區(qū)別在于前向計(jì)算和初始化隱藏狀態(tài)珠闰。

def predict_rnn_pytorch(prefix, num_chars, model, vocab_size, device, idx_to_char,
                      char_to_idx):
    state = None
    output = [char_to_idx[prefix[0]]]  # output記錄prefix加上預(yù)測(cè)的num_chars個(gè)字符
    for t in range(num_chars + len(prefix) - 1):
        X = torch.tensor([output[-1]], device=device).view(1, 1)
        (Y, state) = model(X, state)  # 前向計(jì)算不需要傳入模型參數(shù)
        if t < len(prefix) - 1:
            output.append(char_to_idx[prefix[t + 1]])
        else:
            output.append(Y.argmax(dim=1).item())
    return ''.join([idx_to_char[i] for i in output])

使用權(quán)重為隨機(jī)值的模型來(lái)預(yù)測(cè)一次惜浅。

model = RNNModel(rnn_layer, vocab_size).to(device)
predict_rnn_pytorch('分開(kāi)', 10, model, vocab_size, device, idx_to_char, char_to_idx)

接下來(lái)實(shí)現(xiàn)訓(xùn)練函數(shù),這里只使用了相鄰采樣伏嗜。

def train_and_predict_rnn_pytorch(model, num_hiddens, vocab_size, device,
                                corpus_indices, idx_to_char, char_to_idx,
                                num_epochs, num_steps, lr, clipping_theta,
                                batch_size, pred_period, pred_len, prefixes):
    loss = nn.CrossEntropyLoss()
    optimizer = torch.optim.Adam(model.parameters(), lr=lr)
    model.to(device)
    for epoch in range(num_epochs):
        l_sum, n, start = 0.0, 0, time.time()
        data_iter = d2l.data_iter_consecutive(corpus_indices, batch_size, num_steps, device) # 相鄰采樣
        state = None
        for X, Y in data_iter:
            if state is not None:
                # 使用detach函數(shù)從計(jì)算圖分離隱藏狀態(tài)
                if isinstance (state, tuple): # LSTM, state:(h, c)  
                    state[0].detach_()
                    state[1].detach_()
                else: 
                    state.detach_()
            (output, state) = model(X, state) # output.shape: (num_steps * batch_size, vocab_size)
            y = torch.flatten(Y.T)
            l = loss(output, y.long())
            
            optimizer.zero_grad()
            l.backward()
            grad_clipping(model.parameters(), clipping_theta, device)
            optimizer.step()
            l_sum += l.item() * y.shape[0]
            n += y.shape[0]
        

        if (epoch + 1) % pred_period == 0:
            print('epoch %d, perplexity %f, time %.2f sec' % (
                epoch + 1, math.exp(l_sum / n), time.time() - start))
            for prefix in prefixes:
                print(' -', predict_rnn_pytorch(
                    prefix, pred_len, model, vocab_size, device, idx_to_char,
                    char_to_idx))

訓(xùn)練模型:

num_epochs, batch_size, lr, clipping_theta = 250, 32, 1e-3, 1e-2
pred_period, pred_len, prefixes = 50, 50, ['分開(kāi)', '不分開(kāi)']
train_and_predict_rnn_pytorch(model, num_hiddens, vocab_size, device,
                            corpus_indices, idx_to_char, char_to_idx,
                            num_epochs, num_steps, lr, clipping_theta,
                            batch_size, pred_period, pred_len, prefixes)
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末坛悉,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子承绸,更是在濱河造成了極大的恐慌裸影,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,366評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件军熏,死亡現(xiàn)場(chǎng)離奇詭異轩猩,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)荡澎,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,521評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門均践,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人摩幔,你說(shuō)我怎么就攤上這事彤委。” “怎么了或衡?”我有些...
    開(kāi)封第一講書(shū)人閱讀 165,689評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵葫慎,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我薇宠,道長(zhǎng)偷办,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,925評(píng)論 1 295
  • 正文 為了忘掉前任澄港,我火速辦了婚禮椒涯,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘回梧。我一直安慰自己废岂,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,942評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布狱意。 她就那樣靜靜地躺著湖苞,像睡著了一般。 火紅的嫁衣襯著肌膚如雪详囤。 梳的紋絲不亂的頭發(fā)上财骨,一...
    開(kāi)封第一講書(shū)人閱讀 51,727評(píng)論 1 305
  • 那天镐作,我揣著相機(jī)與錄音,去河邊找鬼隆箩。 笑死该贾,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的捌臊。 我是一名探鬼主播杨蛋,決...
    沈念sama閱讀 40,447評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼理澎!你這毒婦竟也來(lái)了逞力?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 39,349評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤糠爬,失蹤者是張志新(化名)和其女友劉穎寇荧,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體秩铆,經(jīng)...
    沈念sama閱讀 45,820評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,990評(píng)論 3 337
  • 正文 我和宋清朗相戀三年灯变,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了殴玛。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,127評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡添祸,死狀恐怖滚粟,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情刃泌,我是刑警寧澤凡壤,帶...
    沈念sama閱讀 35,812評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站耙替,受9級(jí)特大地震影響亚侠,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜俗扇,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,471評(píng)論 3 331
  • 文/蒙蒙 一硝烂、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧铜幽,春花似錦滞谢、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,017評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至到忽,卻和暖如春橄教,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,142評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工颤陶, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留颗管,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,388評(píng)論 3 373
  • 正文 我出身青樓滓走,卻偏偏與公主長(zhǎng)得像垦江,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子搅方,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,066評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容