用RNN生成文本的简单例子(过程详细)

将文章字母编码

import time
from collections import namedtuple

import numpy as np
import tensorflow as tf

with open('anna.txt', 'r') as f:
    text=f.read()
vocab = sorted(set(text))#set将文章中的所有不同字符取出,然后sorted排序
vocab_to_int = {c: i for i, c in enumerate(vocab)}#排好序的字符列表进行字典索引
int_to_vocab = dict(enumerate(vocab))#与上字典相反,索引号为键,字符为值
encoded = np.array([vocab_to_int[c] for c in text], dtype=np.int32)#把text中所有字符进行数字编码

将数据生成mini-batches

定义函数,读入文章,sequence长度、step长度为超参数

def get_batches(arr, n_seqs, n_steps):

    # 用sequence和step计算batch大小,得出batch个数,最后不够一个batch的扔掉
    characters_per_batch = n_seqs * n_steps
    n_batches = len(arr)//characters_per_batch
    arr = arr[:n_batches * characters_per_batch]

    # 重新reshape为sequence行,列数自动生成(-1)
    arr = arr.reshape((n_seqs, -1))

    # 生成样本特征batch及目标值batch(目标值为样本值的下一个字母)
    for n in range(0, arr.shape[1], n_steps):
        x = arr[:, n:n+n_steps]
        y = np.zeros_like(x)
        # 目标值往下滚动一个字母,目标batch最后一列可设置为样本特征batch的第一列,不会影响精度
        y[:, :-1], y[:,-1] = x[:, 1:], x[:, 0]

        # x,y为生成器(generater)
        yield x, y

创建输入层

创建输入、目标值占位符,以及keep_prob的占位符(Dropout层用到)

def build_inputs(batch_size, num_steps):
    '''batch_size是每个batch中sequence的长度(batch行数)
        num_steps是batch列数
    '''
    inputs = tf.placeholder(tf.int32, [batch_size, num_steps], name='inputs')
    targets = tf.placeholder(tf.int32, [batch_size, num_steps], name='targets')
    keep_prob = tf.placeholder(tf.float32, name='keep_prob')

    return inputs, targets, keep_prob

创建LSTM单元

  1. 创建隐藏层中的LSTM单元tf.contrib.rnn.BasicLSTMCell(num_units)
  2. 在cell外包裹上Dropouttf.contrib.rnn.DropoutWrapper(lstm, output_keep_prob=keep_prob)
    为什么这么做可以看一下Wojciech Zaremba的论文:Recurrent Neural Netwo

  • 5
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
TensorFlow 中使用 RNN 训练文本数据可以使用 `tf.keras.layers.RNN` 类或其子类(如 `tf.keras.layers.LSTM` 或 `tf.keras.layers.GRU`)。具体来说,首先需要将文本数据转换为可以输入到网络中的数字张量,然后使用 RNN 层将其输入网络进行训练。 下面是一个简单例子,使用 LSTM 层训练文本数据并生成新的文本: ```python import tensorflow as tf from tensorflow.keras.layers import Embedding, LSTM, Dense from tensorflow.keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence import pad_sequences # 训练数据 text = ["hello, how are you?", "I am fine, thank you.", "What is your name?", "My name is ChatGPT."] # 数据预处理 tokenizer = Tokenizer() tokenizer.fit_on_texts(text) sequences = tokenizer.texts_to_sequences(text) data = pad_sequences(sequences) # 构建模型 model = tf.keras.Sequential() model.add(Embedding(len(tokenizer.word_index)+1, 64, input_length=data.shape[1])) model.add(LSTM(64)) model.add(Dense(len(tokenizer.word_index)+1, activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) # 训练模型 model.fit(data, labels, epochs=100) # 根据某些条件生成新的文本 def generate_text(model, tokenizer, seed_text, num_words): in_text = seed_text for i in range(num_words): encoded = tokenizer.texts_to_sequences([in_text])[0] encoded = pad_sequences([encoded], maxlen=data.shape[1]) yhat = model.predict(encoded, verbose=0) yhat = np.argmax(yhat) word = tokenizer.index_word[yhat] in_text += ' ' + word return in_

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值