这是我的第二篇文章。如果我听起来很尴尬,我真的很抱歉。我是机器学习的新手。报告问题或提出负面意见将对我有帮助。再次抱歉,我无法清除我的问题。
现在问我一个问题,我正在研究下一个单词Prediction的作业。我正在尝试创建一个模型,该模型可用于基于像快速键盘这样的输入来生成下一个单词。我创建了一个能够生成下一个单词的模型。但是我想为一个输入单词生成多个单词。例如,我吃热___。对于空白处,我希望预测像狗,比萨饼,巧克力。但是,我当前的模型能够生成具有最大概率的下一个单词。但是我想要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
我正在关注medium中提到的文章 预先谢谢你。