【问题标题】:How to use loaded LSTM attention model to make predictions on input?如何使用加载的 LSTM 注意力模型对输入进行预测?
【发布时间】:2020-02-07 21:19:01
【问题描述】:

我是深度学习和 Keras 的完整初学者。我想建立一个分层的注意力网络,帮助将 cmets 分类为几个类别,即。有毒,剧毒等。我从一个开放的存储库中获取了代码并保存了模型。然后我使用 model_from_json 加载模型。现在我希望使用这个加载的模型对输入文本进行预测(作为 python 输入或单独的文件给出)。

这是我正在使用的代码:https://www.kaggle.com/sermakarevich/hierarchical-attention-network/notebook

然后我做了:

model_json = model.to_json()
with open("model.json", "w") as json_file:
    json_file.write(model_json)
model.save_weights("model.h5")
print("Saved model to disk")

然后在一个单独的文件中:

json_file = open('model.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
loaded_model = model_from_json(loaded_model_json,custom_objects={'AttentionWithContext':AttentionWithContext})
loaded_model.load_weights("model.h5")
print("Loaded model from disk")

我正在完美地“从磁盘加载模型”。我想知道我需要输入的格式以及如何使用代码 sn-p 使用模型对其进行分类。由于我对此知之甚少,如果有人可以帮助我使用 python 特定代码使其工作,那将非常有帮助。

【问题讨论】:

    标签: machine-learning keras deep-learning data-science attention-model


    【解决方案1】:

    在进行预测时,请确保您也选择了分词器,否则输出将不正确。

        new = ["Your_text_that_you_want_to_check"]
        seq = tokenizer.texts_to_sequences(new)
        padded = pad_sequences(seq, maxlen=MAX_SEQUENCE_LENGTH)
        pred = model.predict(padded)
    

    在预测时,将新文本转换为向量以训练模型非常重要。我已经将我的训练数据转换为序列,然后用零填充它,这样长度应该相同,并且我在预测时重复的步骤相同。但请确保您腌制您的 tokenzier。我希望它有帮助!如果您在理解这些步骤时遇到困难,请告诉我。

    【讨论】:

    • 我在保存模型后添加了以下内容:使用 open('tokenizer.pickle','wb') 作为句柄:pickle.dump(tokenizer,handle,protocol=pickle.HIGHEST_PROTOCOL) 并在文件中在加载模型的地方,我添加了以下内容: texts=[ "hey"] with open('tokenizer.pickle','rb') as handle: tk=pickle.load(handle) tk.fit_on_texts(texts) index_list = tk.texts_to_sequences(texts) data = pad_sequences(index_list, maxlen=1) y =loaded_model.predict(data) 我得到错误:ValueError:检查输入时出错:预期 input_2 有 3 个维度,但得到的数组形状为( 1, 1)
    • 嗨@Code231 不再适合文本。您不必编写此行 tk.fit_on_texts(texts) 并确保在训练时和这部分中 maxlen 应该相同。您已将 1 用作 maxlen,因此请确保在训练时使用相同的 maxlen。 with open('tokenizer.pickle','rb') as handle: tk=pickle.load(handle) texts=[ "hey"] index_list = tk.texts_to_sequences(texts) data = pad_sequences(index_list, maxlen=max_len_you_used_while_training) y =loaded_model.predict(data)
    猜你喜欢
    • 2021-12-15
    • 2022-11-22
    • 1970-01-01
    • 1970-01-01
    • 2019-09-01
    • 1970-01-01
    • 2017-11-10
    • 2019-02-08
    • 2018-08-11
    相关资源
    最近更新 更多