python - 下一个词预测 RNN
问题描述
这是我的第二篇文章。如果我听起来很尴尬,我真的很抱歉。我是机器学习的新手。报告问题或给出否定意见将对我有所帮助。再次抱歉,我无法解决我的问题。
现在来回答我的问题,我正在处理下一个单词预测的任务。我正在尝试创建一个模型,该模型可用于根据输入(如快速键盘)生成下一个单词。我创建了一个能够生成下一个单词的模型。但我想为一个输入单词生成多个单词。例如,我吃了热的___。对于空白区域,我想要狗、披萨、巧克力等预测。但是,我当前的模型能够生成具有最大概率的下一个单词。但我想要 3 个输出。我使用 LSTM 和 Keras 作为框架。我正在使用 Keras 的顺序模型。代码主要分为三个部分:数据集准备、模型训练和生成预测。
def dataset_preparation():
# basic cleanup
corpus = text.split("\n\n")
# tokenization
tokenizer.fit_on_texts(str(corpus).split("##"))
total_words = len(tokenizer.word_index) + 1
# create input sequences using list of tokens
input_sequences = []
for line in str(corpus).split("\n\n"):
#print(line)
token_list = tokenizer.texts_to_sequences([line])[0]
#print("printing token_list",token_list)
for i in range(1, len(token_list)):
n_gram_sequence = token_list[:i+1]
#print("printing n_gram_sequence",n_gram_sequence)
#print("printing n_gram_sequence length",len(n_gram_sequence))
input_sequences.append(n_gram_sequence)
#print("Printing Input Sequence:",input_sequences)
# pad sequences
max_sequence_len = 378
input_sequences = np.array(pad_sequences(input_sequences, maxlen=max_sequence_len, padding='pre'))
# create predictors and label
predictors, label = input_sequences[:,:-1],input_sequences[:,-1]
label = ku.to_categorical(label, num_classes=total_words)
return predictors, label, max_sequence_len, total_words
def create_model(predictors, label, max_sequence_len, total_words):
model = Sequential()
model.add(Embedding(total_words, 10, input_length=max_sequence_len-1))
model.add(LSTM(150, return_sequences = True))
# model.add(Dropout(0.2))
model.add(LSTM(100))
model.add(Dense(total_words, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
earlystop = EarlyStopping(monitor='loss', min_delta=0, patience=5, verbose=0, mode='auto')
model.fit(predictors, label, epochs=1, verbose=1, callbacks=[earlystop])
print (model.summary())
return model
def generate_text(seed_text, next_words, max_sequence_len):
for _ in range(next_words):
token_list = tokenizer.texts_to_sequences([seed_text])[0]
print("Printing token list:",token_list)
token_list = pad_sequences([token_list], maxlen=max_sequence_len-1, padding='pre')
predicted = model.predict_classes(token_list, verbose=0)
output_word = ""
for word, index in tokenizer.word_index.items():
if index == predicted:
output_word = word
break
seed_text += " " + output_word
return seed_text
我正在关注中提到的文章, 提前谢谢你。
解决方案
推荐阅读
- asp.net-core - ViewComponents 与孩子
- javascript - 如何使用 selenium 和 python 将字符序列发送到 contenteditable="true" 元素
- networking - Boost.Asio 简单的客户端服务器模型不返回响应
- node.js - 用 Jest 测试 Keystone 和 Mongoose
- wordpress - 如何提高 m wordpress 电影网站的速度
- r - 如何在不改变 xy 坐标的情况下在绘图中移动单个文本标签?
- selenium - 在 chrome://downloads 中使用 Chromedriver 保存文件
- java - 在 netbeans 中清理和构建 javafx 应用程序时出错,XML 文档结构必须在同一实体内开始和结束
- android - Android 文档中不完整的方法访问修饰符和/或非访问修饰符
- x86 - 我的 /bin/ls -l Shellcode 如何处理空字节?