Keras(三十)使用LSTM实现文本生成

数据资源:莎士比亚数据集

一,处理数据

1,加载训练数据
# https://storage.googleapis.com/download.tensorflow.org/data/shakespeare.txt
input_filepath = "./shakespeare.txt"
text = open(input_filepath, 'r').read()
print(len(text))
print(text[0:100])
2,生成词库
"""
# 1. generate vocab
# 2. build mapping char->id
# 3. data -> id_data
# 4. abcd -> bcd<eos>
"""
vocab = sorted(set(text))
print(len(vocab))
print(vocab)
3,生成词库对应表
char2idx = {char:idx for idx, char in enumerate(vocab)}
print(char2idx)
4,将词库
idx2char = np.array(vocab)
print(idx2char)
5,将文本转化为数字
text_as_int = np.array([char2idx[c] for c in text])
print(text_as_int[0:10])
print(text[0:10])
6,将数据加载都dataset中,并处理数据
def split_input_target(id_text):
    """
    abcde -> abcd, bcde
    """
    return id_text[0:-1], id_text[1:]

# 将数据加载都dataset中
char_dataset = tf.data.Dataset.from_tensor_slices(text_as_int)

# 将数据集每个100个字符进行batch分序列
seq_length = 100
seq_dataset = char_dataset.batch(seq_length + 1,
                                 drop_remainder = True)
# 选择数据查看
for ch_id in char_dataset.take(2):
    print(ch_id, idx2char[ch_id.numpy()])

for seq_id in seq_dataset.take(2):
    print(seq_id)
    print(repr(''.join(idx2char[seq_id.numpy()])))
7,将数据分割成训练和两个部分
seq_dataset = seq_dataset.map(split_input_target)

for item_input, item_output in seq_dataset.take(2):
    print(item_input.numpy())
    print(item_output.numpy())
8,打乱数据,batch分组,batch_size=64
batch_size = 64
buffer_size = 10000

seq_dataset = seq_dataset.shuffle(buffer_size).batch(
    batch_size, drop_remainder=True)

二,构建模型

1,定义模型常量
vocab_size = len(vocab)
embedding_dim = 256
rnn_units = 1024
2,定义model模型
# # 1) 使用 Sequential 定义模型
# def build_model(vocab_size, embedding_dim, rnn_units, batch_size):
#     model = keras.models.Sequential([
#         keras.layers.Embedding(vocab_size, embedding_dim,
#                                batch_input_shape = [batch_size, None]),
#         keras.layers.LSTM(units = rnn_units,
#                           stateful = True,
#                           recurrent_initializer = 'glorot_uniform',
#                           return_sequences = True),
#         keras.layers.Dense(vocab_size),
#     ])
#     return model
#
# model = build_model(
#     vocab_size = vocab_size,
#     embedding_dim = embedding_dim,
#     rnn_units = rnn_units,
#     batch_size = batch_size)
#
# # 2) Model定义模型###############################################################
inputs = keras.Input(batch_input_shape=(batch_size,None))
print(inputs.shape)
outputs = keras.layers.Embedding(vocab_size, embedding_dim)(inputs)
print(outputs.shape)
outputs = keras.layers.LSTM(units = rnn_units,stateful = True,recurrent_initializer='glorot_uniform',
                            return_sequences = True)(outputs)
print(outputs.shape)
outputs = keras.layers.Dense(vocab_size)(outputs)
print(outputs.shape)

model = Model(inputs, outputs)

###############################################################################
model.summary()
3,单个例子测试模型
for input_example_batch, target_example_batch in seq_dataset.take(1):
    example_batch_predictions = model(input_example_batch)
    print(example_batch_predictions.shape)

    
# random sampling.
# greedy, random.
# 测试单个例子的结果
sample_indices = tf.random.categorical(
    logits = example_batch_predictions[0], num_samples = 1)
print(sample_indices)
# (100, 65) -> (100, 1)
sample_indices = tf.squeeze(sample_indices, axis = -1)
print(sample_indices)


# 打印输入,目标,预测的结果
print("Input: ", repr("".join(idx2char[input_example_batch[0]])))
print()
print("Output: ", repr("".join(idx2char[target_example_batch[0]])))
print()
print("Predictions: ", repr("".join(idx2char[sample_indices])))

三,定义损失函数和优化器

def loss(labels, logits):
    return keras.losses.sparse_categorical_crossentropy(
        labels, logits, from_logits=True)

# 定义优化器和自定义损失函数
model.compile(optimizer = 'adam', loss = loss)

# 测试计算单例的损失数
example_loss = loss(target_example_batch, example_batch_predictions)
print(example_loss.shape)
print(example_loss.numpy().mean())

四,callback模块-checkpoints

output_dir = "./text_generation_lstm3_checkpoints"
if not os.path.exists(output_dir):
    os.mkdir(output_dir)
checkpoint_prefix = os.path.join(output_dir, 'ckpt_{epoch}')
checkpoint_callback = keras.callbacks.ModelCheckpoint(
    filepath = checkpoint_prefix,
    save_weights_only = True)

五,训练模型

epochs = 100
history = model.fit(seq_dataset, epochs = epochs,
                    callbacks = [checkpoint_callback])

# 会自动找到最近保存的变量文件
new_checkpoint = tf.train.latest_checkpoint(output_dir)

六,定义预测模型

# 1,Model 定义预测模型 ##########################################################
inputs = keras.Input(batch_input_shape=(1,None))
print(inputs.shape)
outputs = keras.layers.Embedding(vocab_size, embedding_dim)(inputs)
print(outputs.shape)
outputs = keras.layers.LSTM(units = rnn_units,stateful = True,recurrent_initializer='glorot_uniform',
                        return_sequences = True)(outputs)
print(outputs.shape)
outputs = keras.layers.Dense(vocab_size)(outputs)
print(outputs.shape)

model2 = Model(inputs, outputs)

# 2,Sequential 定义预测模型 #####################################################

# def build_model(vocab_size, embedding_dim, rnn_units, batch_size):
#     model = keras.models.Sequential([
#         keras.layers.Embedding(vocab_size, embedding_dim,
#                                batch_input_shape = [batch_size, None]),
#         keras.layers.LSTM(units = rnn_units,
#                           stateful = True,
#                           recurrent_initializer = 'glorot_uniform',
#                           return_sequences = True),
#         keras.layers.Dense(vocab_size),
#     ])
#     return model

# model2 = build_model(vocab_size,
#                       embedding_dim,
#                       rnn_units,
#                       batch_size = 1)
# model2.build(tf.TensorShape([1, None]))
# ##############################################################################


# start ch sequence A,
# A -> model -> b
# A.append(b) -> B
# B(Ab) -> model -> c
# B.append(c) -> C
# C(Abc) -> model -> ...
model2.load_weights(tf.train.latest_checkpoint(output_dir))
model2.summary()

七,预测模型做预测

def generate_text(model, start_string, num_generate = 1000):
    input_eval = [char2idx[ch] for ch in start_string]
    input_eval = tf.expand_dims(input_eval, 0)
    
    text_generated = []
    model.reset_states()
    
    # temperature > 1, random
    # temperature < 1, greedy 
    temperature = 2
    
    for _ in range(num_generate):
        # 1. model inference -> predictions
        # 2. sample -> ch -> text_generated.
        # 3. update input_eval
        
        # predictions : [batch_size, input_eval_len, vocab_size]
        predictions = model(input_eval)
        # predictions: logits -> softmax -> prob
        # softmax: e^xi 
        # eg: 4,2 e^4/(e^4 + e^2) = 0.88, e^2 / (e^4 + e^2) = 0.12
        # eg: 2,1 e^2/(e^2 + e) = 0.73, e / (e^2 + e) = 0.27
        predictions = predictions / temperature
        # predictions : [input_eval_len, vocab_size]
        predictions = tf.squeeze(predictions, 0)
        # predicted_ids: [input_eval_len, 1]
        # a b c -> b c d
        predicted_id = tf.random.categorical(
            predictions, num_samples = 1)[-1, 0].numpy()
        text_generated.append(idx2char[predicted_id])
        # s, x -> rnn -> s', y
        input_eval = tf.expand_dims([predicted_id], 0)
    return start_string + ''.join(text_generated)

new_text = generate_text(model2, "All: ")
print(new_text)

八,总结代码

# -*- coding: utf-8 -*-

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import sklearn
import pandas as pd
import os
import sys
import time
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.models import  Model

print(tf.__version__)
print(sys.version_info)
for module in mpl, np, pd, sklearn, tf, keras:
    print(module.__name__, module.__version__)

# 一,处理数据
# 1,加载训练数据
# https://storage.googleapis.com/download.tensorflow.org/data/shakespeare.txt
input_filepath = "./shakespeare.txt"
text = open(input_filepath, 'r').read()
print(len(text))
print(text[0:100])

# 2,生成词库
"""
# 1. generate vocab
# 2. build mapping char->id
# 3. data -> id_data
# 4. abcd -> bcd<eos>
"""
vocab = sorted(set(text))
print(len(vocab))
print(vocab)

# 3,生成词库对应表
char2idx = {char:idx for idx, char in enumerate(vocab)}
print(char2idx)

# 4,将词库
idx2char = np.array(vocab)
print(idx2char)

# 5,将文本转化为数字
text_as_int = np.array([char2idx[c] for c in text])
print(text_as_int[0:10])
print(text[0:10])

# 6,将数据加载都dataset中,并处理数据
def split_input_target(id_text):
    """
    abcde -> abcd, bcde
    """
    return id_text[0:-1], id_text[1:]

# 将数据加载都dataset中
char_dataset = tf.data.Dataset.from_tensor_slices(text_as_int)

# 将数据集每个100个字符进行batch分序列
seq_length = 100
seq_dataset = char_dataset.batch(seq_length + 1,
                                 drop_remainder = True)
# 选择数据查看
for ch_id in char_dataset.take(2):
    print(ch_id, idx2char[ch_id.numpy()])

for seq_id in seq_dataset.take(2):
    print(seq_id)
    print(repr(''.join(idx2char[seq_id.numpy()])))

# 7,将数据分割成训练和两个部分
seq_dataset = seq_dataset.map(split_input_target)

for item_input, item_output in seq_dataset.take(2):
    print(item_input.numpy())
    print(item_output.numpy())


# 8,打乱数据,batch分组,batch_size=64
batch_size = 64
buffer_size = 10000

seq_dataset = seq_dataset.shuffle(buffer_size).batch(
    batch_size, drop_remainder=True)

# 二,构建模型
# 1,定义模型常量
vocab_size = len(vocab)
embedding_dim = 256
rnn_units = 1024

# 2,定义model模型
# # 1) 使用 Sequential 定义模型
# def build_model(vocab_size, embedding_dim, rnn_units, batch_size):
#     model = keras.models.Sequential([
#         keras.layers.Embedding(vocab_size, embedding_dim,
#                                batch_input_shape = [batch_size, None]),
#         keras.layers.LSTM(units = rnn_units,
#                           stateful = True,
#                           recurrent_initializer = 'glorot_uniform',
#                           return_sequences = True),
#         keras.layers.Dense(vocab_size),
#     ])
#     return model
#
# model = build_model(
#     vocab_size = vocab_size,
#     embedding_dim = embedding_dim,
#     rnn_units = rnn_units,
#     batch_size = batch_size)
#
# # 2) Model定义模型###############################################################
inputs = keras.Input(batch_input_shape=(batch_size,None))
print(inputs.shape)
outputs = keras.layers.Embedding(vocab_size, embedding_dim)(inputs)
print(outputs.shape)
outputs = keras.layers.LSTM(units = rnn_units,stateful = True,recurrent_initializer='glorot_uniform',
                            return_sequences = True)(outputs)
print(outputs.shape)
outputs = keras.layers.Dense(vocab_size)(outputs)
print(outputs.shape)

model = Model(inputs, outputs)

###############################################################################
model.summary()

# 3,单个例子测试模型
for input_example_batch, target_example_batch in seq_dataset.take(1):
    example_batch_predictions = model(input_example_batch)
    print(example_batch_predictions.shape)

    
# random sampling.
# greedy, random.
# 测试单个例子的结果
sample_indices = tf.random.categorical(
    logits = example_batch_predictions[0], num_samples = 1)
print(sample_indices)
# (100, 65) -> (100, 1)
sample_indices = tf.squeeze(sample_indices, axis = -1)
print(sample_indices)


# 打印输入,目标,预测的结果
print("Input: ", repr("".join(idx2char[input_example_batch[0]])))
print()
print("Output: ", repr("".join(idx2char[target_example_batch[0]])))
print()
print("Predictions: ", repr("".join(idx2char[sample_indices])))


# 三,定义损失函数和优化器
def loss(labels, logits):
    return keras.losses.sparse_categorical_crossentropy(
        labels, logits, from_logits=True)

# 定义优化器和自定义损失函数
model.compile(optimizer = 'adam', loss = loss)

# 测试计算单例的损失数
example_loss = loss(target_example_batch, example_batch_predictions)
print(example_loss.shape)
print(example_loss.numpy().mean())


# 四,callback模块-checkpoints
output_dir = "./text_generation_lstm3_checkpoints"
if not os.path.exists(output_dir):
    os.mkdir(output_dir)
checkpoint_prefix = os.path.join(output_dir, 'ckpt_{epoch}')
checkpoint_callback = keras.callbacks.ModelCheckpoint(
    filepath = checkpoint_prefix,
    save_weights_only = True)

# 五,训练模型
epochs = 100
history = model.fit(seq_dataset, epochs = epochs,
                    callbacks = [checkpoint_callback])

# 会自动找到最近保存的变量文件
new_checkpoint = tf.train.latest_checkpoint(output_dir)



# 六,定义预测模型
# 1,Model 定义预测模型 ##########################################################
inputs = keras.Input(batch_input_shape=(1,None))
print(inputs.shape)
outputs = keras.layers.Embedding(vocab_size, embedding_dim)(inputs)
print(outputs.shape)
outputs = keras.layers.LSTM(units = rnn_units,stateful = True,recurrent_initializer='glorot_uniform',
                        return_sequences = True)(outputs)
print(outputs.shape)
outputs = keras.layers.Dense(vocab_size)(outputs)
print(outputs.shape)

model2 = Model(inputs, outputs)

# 2,Sequential 定义预测模型 #####################################################

# def build_model(vocab_size, embedding_dim, rnn_units, batch_size):
#     model = keras.models.Sequential([
#         keras.layers.Embedding(vocab_size, embedding_dim,
#                                batch_input_shape = [batch_size, None]),
#         keras.layers.LSTM(units = rnn_units,
#                           stateful = True,
#                           recurrent_initializer = 'glorot_uniform',
#                           return_sequences = True),
#         keras.layers.Dense(vocab_size),
#     ])
#     return model

# model2 = build_model(vocab_size,
#                       embedding_dim,
#                       rnn_units,
#                       batch_size = 1)
# model2.build(tf.TensorShape([1, None]))
# ##############################################################################


# start ch sequence A,
# A -> model -> b
# A.append(b) -> B
# B(Ab) -> model -> c
# B.append(c) -> C
# C(Abc) -> model -> ...
model2.load_weights(tf.train.latest_checkpoint(output_dir))
model2.summary()


# 七,预测模型做预测
def generate_text(model, start_string, num_generate = 1000):
    input_eval = [char2idx[ch] for ch in start_string]
    input_eval = tf.expand_dims(input_eval, 0)
    
    text_generated = []
    model.reset_states()
    
    # temperature > 1, random
    # temperature < 1, greedy 
    temperature = 2
    
    for _ in range(num_generate):
        # 1. model inference -> predictions
        # 2. sample -> ch -> text_generated.
        # 3. update input_eval
        
        # predictions : [batch_size, input_eval_len, vocab_size]
        predictions = model(input_eval)
        # predictions: logits -> softmax -> prob
        # softmax: e^xi 
        # eg: 4,2 e^4/(e^4 + e^2) = 0.88, e^2 / (e^4 + e^2) = 0.12
        # eg: 2,1 e^2/(e^2 + e) = 0.73, e / (e^2 + e) = 0.27
        predictions = predictions / temperature
        # predictions : [input_eval_len, vocab_size]
        predictions = tf.squeeze(predictions, 0)
        # predicted_ids: [input_eval_len, 1]
        # a b c -> b c d
        predicted_id = tf.random.categorical(
            predictions, num_samples = 1)[-1, 0].numpy()
        text_generated.append(idx2char[predicted_id])
        # s, x -> rnn -> s', y
        input_eval = tf.expand_dims([predicted_id], 0)
    return start_string + ''.join(text_generated)

new_text = generate_text(model2, "All: ")
print(new_text)

课程导语:    人工智能可谓是现阶段最火的行业,在资本和技术协同支持下正在进入高速发展期。当今全球市值前五大公司都指向同一发展目标:人工智能。近几年,人工智能逐渐从理论科学落地到现实中,与生活越来越息息相关,相关的各种职位炙手可热,而深度学习更是人工智能无法绕开的重要一环。 从AlphaGo打败李世石开始,深度学习技术越来越引起社会各界的广泛关注。不只学术界,甚至在工业界也取得了重大突破和广泛应用。其中应用最广的研究领域就是图像处理和自然语言处理。而要入门深度学习,CNN和RNN作为最常用的两种神经网络是必学的。网上关于深度学习的资料很多,但大多知识点分散、内容不系统,或者以理论为主、代码实操少,造成学员学习成本高。本门课程将从最基础的神经元出发,对深度学习的基础知识进行全面讲解,帮助大家迅速成为人工智能领域的入门者,是进阶人工智能深层领域的基石。 讲师简介:赵辛,人工智能算法科学家。2019年福布斯科技榜U30,深圳市海外高层次人才(孔雀人才)。澳大利亚新南威尔士大学全奖博士,SCI收录其发表过的10篇国际期刊学术文章。曾任深圳市微埃智能科技有限公司联合创始人。优快云人工智能机器学习、深度学习方向满分级精英讲师。授课风格逻辑严谨、条理清晰、循序渐进、循循善诱,化枯燥为如沐春风,所教学生人数过万。 课程设计: 本课程分为5大模块,19小节,共计540时长(约9小时): 第一部分,课程介绍、目标与内容概览。主要学习人工智能深度学习应用场景;熟悉深度学习主流技术;掌握使用keras解决深度学习主要问题(神经网络、卷积神经网络、循环神经网络),以及深度学习主要内容:神经网络、卷积神经网络、循环神经网络;案例简介。 第二部分,深度学习之多层感知器(MLP)。主要学习多层感知器(MLP);MLP实现非线性分类;深度学习实战准备;Python调用keras实现MLP。 MLP技术点实战案例:第三部分,深度学习之卷积神经网络(CNN)。主要学习卷积神经网络 ; CNN模型分析;主流CNN模型; Python调用keras实现CNN; CNN技术点实战案例:第四部分,深度学习之循环神经网络(RNN)。主要学习循环神经网络;RNN模型分析;Python调用keras实现RNN。 RNN技术点实战案例: 第五部分,综合提升。主要进行迁移学习;混合模型;实战准备+综合实战,以及最后进行课程内容总结。 混合模型技术点实战案例
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值