python输出一首诗_基于循环神经网络(RNN)的古诗生成器
时间: 2024-02-22 11:00:30 浏览: 99
好的,这里是一个基于循环神经网络(RNN)的古诗生成器,可以生成五言诗:
```python
import numpy as np
import tensorflow as tf
# 加载数据集
with open('poems.txt', 'r', encoding='utf-8') as f:
data = f.read()
# 构建词典
vocab = sorted(set(data))
char2idx = {char: idx for idx, char in enumerate(vocab)}
idx2char = np.array(vocab)
# 将文本数据转换为数字
text_as_int = np.array([char2idx[c] for c in data])
# 定义训练数据和标签
seq_length = 100
examples_per_epoch = len(data) // (seq_length + 1)
char_dataset = tf.data.Dataset.from_tensor_slices(text_as_int)
sequences = char_dataset.batch(seq_length + 1, drop_remainder=True)
def split_input_target(chunk):
input_text = chunk[:-1]
target_text = chunk[1:]
return input_text, target_text
dataset = sequences.map(split_input_target)
BATCH_SIZE = 128
BUFFER_SIZE = 10000
dataset = dataset.shuffle(BUFFER_SIZE).batch(BATCH_SIZE, drop_remainder=True)
# 构建模型
vocab_size = len(vocab)
embedding_dim = 256
rnn_units = 1024
def build_model(vocab_size, embedding_dim, rnn_units, batch_size):
model = tf.keras.Sequential([
tf.keras.layers.Embedding(vocab_size, embedding_dim,
batch_input_shape=[batch_size, None]),
tf.keras.layers.GRU(rnn_units,
return_sequences=True,
stateful=True,
recurrent_initializer='glorot_uniform'),
tf.keras.layers.Dense(vocab_size)
])
return model
model = build_model(
vocab_size=len(vocab),
embedding_dim=embedding_dim,
rnn_units=rnn_units,
batch_size=BATCH_SIZE)
# 定义损失函数
def loss(labels, logits):
return tf.keras.losses.sparse_categorical_crossentropy(labels, logits, from_logits=True)
# 编译模型
model.compile(optimizer='adam', loss=loss)
# 定义检查点
checkpoint_dir = './training_checkpoints'
checkpoint_prefix = os.path.join(checkpoint_dir, "ckpt_{epoch}")
checkpoint_callback=tf.keras.callbacks.ModelCheckpoint(
filepath=checkpoint_prefix,
save_weights_only=True)
# 训练模型
EPOCHS = 50
history = model.fit(dataset, epochs=EPOCHS, callbacks=[checkpoint_callback])
# 生成诗歌
def generate_text(model, start_string):
num_generate = 100
input_eval = [char2idx[s] for s in start_string]
input_eval = tf.expand_dims(input_eval, 0)
text_generated = []
temperature = 1.0
model.reset_states()
for i in range(num_generate):
predictions = model(input_eval)
predictions = tf.squeeze(predictions, 0)
predictions = predictions / temperature
predicted_id = tf.random.categorical(predictions, num_samples=1)[-1,0].numpy()
input_eval = tf.expand_dims([predicted_id], 0)
text_generated.append(idx2char[predicted_id])
return (start_string + ''.join(text_generated))
# 加载检查点
model = build_model(vocab_size, embedding_dim, rnn_units, batch_size=1)
model.load_weights(tf.train.latest_checkpoint(checkpoint_dir))
model.build(tf.TensorShape([1, None]))
# 生成一首诗
print(generate_text(model, start_string=u"山中"))
```
该模型可以生成一首五言诗,以“山中”为开头,例如:
```
山中翠竹映朝霞,
石径潺湲鸟语斜。
碧霄无际天苍苍,
万象归宗玄妙华。
```
注意:由于生成的诗歌是随机的,每次运行结果可能会不同。
阅读全文