诗歌是一种有着特殊魅力的文学体裁,是一种人类文明发展的象征。在当前时代下,使用计算机对散文诗进行模拟生成成为自然语言生成领域的一个挑战。本文通过建立英文诗语料库,基于深度学习模型进行散文诗创作,实现散文诗的计算机辅助创作。它可以为广大的英文诗歌文学爱好者提供很大便利,同时也有助汉英文诗的传播与宣扬。本文设计了GRU模型进行训练,然后利用GRU模型权重实现自动生成器系统。
数据集:
诗歌的数据集包含:弗罗斯特(Frost)和约翰·济慈(John Keats)等人的诗歌或者诗词等。
训练模型的代码如下:
def word2index(word):
return word_model.wv.vocab[word].index
def index_to_word(index):
return word_model.wv.index2word[index]
xs = np.zeros([len(words), max_len], dtype=np.int32)
ys = np.zeros([len(words)], dtype=np.int32)
for i, sent in enumerate(words):
if sent:
for t, word in enumerate(sent[:-1]):
xs[i, t] = word2index(word)
ys[i] = word2index(sent[-1])
model = Sequential()
model.add(Embedding(input_dim=vocab_size,
output_dim=embedding_size, weights=[pretrained_weights]))
model.add(GRU(units=embedding_size, return_sequences=True))
model.add(GRU(units=embedding_size))
model.add(Dropout(0.4))
model.add(Dense(units=vocab_size, activation="softmax"))
adam = Adam(lr=0.01)
model.compile(loss="sparse_categorical_crossentropy",
optimizer=adam, metrics=["SparseCategoricalAccuracy"])
history = model.fit(xs, ys, batch_size=128, epochs=100, verbose=1)
if not os.path.exists('../model'):
os.makedirs('../model')
model.save("../model/poet_gru_model.h5")
它使用训练在模型语料库上的Word2Vec词嵌入来推断相似的词。如果没有找到这样的单词,它会从词汇表中选择一个与前一句的最后一个单词押韵的单词。如果在词汇表中找不到押韵的单词,生成器将停止执行。
实现的界面如下:
完整代码:点击添加群:正在跳转