我已经使用Keras创建LSTM网络,用于基于句子中前一个单词的上下文来预测下一个单词。我已经用Python编写了代码,但是必须将其与C ++的现有代码一起部署。因此,如何将这块代码转换为C ++,因为我是新手,因此我一直在python中使用内置函数。
我一直在尝试将每一行python代码都转换为C ++,但这很耗时,而且我什至无法读取C ++中的hdf5和pkl文件。 Python代码:
from pickle import load
from keras.models import load_model
from keras.preprocessing.sequence import pad_sequences
def generate_seq(model, tokenizer, seq_length, seed_text, no_next_words):
result = []
in_text = seed_text
for _ in range(no_next_words):
# encode the text as integer
encoded = tokenizer.texts_to_sequences([in_text])[0]
# convert sequences to a fixed length
encoded = pad_sequences([encoded], maxlen=seq_length, truncating='pre')
# predict probabilities for each word
yhat = model.predict_classes(encoded, verbose=0)
# map predicted word index to word
out_word = ''
for word, index in tokenizer.word_index.items():
if index == yhat:
out_word = word
break
# append to input
in_text += ' ' + out_word
result.append(out_word)
return ' '.join(result)
# load the model
model = load_model('model_chat2_3.h5')
# load the tokenizer
tokenizer = load(open('tokenizer_chat2_3.pkl', 'rb'))
# generate new text
while(True):
inp = input("Enter:")
generated = generate_seq(model, tokenizer, 2,inp, 1)
print(generated)
C ++代码:
#include <iostream>
#include <fstream>
#include <typeinfo>
#include <string>
using namespace std;
int main(int argc, const char * argv[]) {
ifstream myReadFile,myReadFile2;
myReadFile.open("/Users/Apple/New word_prediction/word_prediction/data/colab models/chat2_2/tokenizer_chat2_2.pkl");
myReadFile2.open("/Users/Apple/New word_prediction/word_prediction/data/colab models/chat2_2/model_chat2_2.h5");
char output[1200];
if (myReadFile.is_open()) {
while (!myReadFile.eof()) {
myReadFile >> output;
cout<<output<<endl;
}
}
myReadFile.close();
myReadFile2.close();
return 0;
}
C ++的输出结果是一些编码后的字符串。
我尝试参考前面的答案,但是所有答案都是针对其用例而专门构建的。 例如: Convert Keras model to C++。 基本上,我使用LSTM网络(隐藏层:LSTM)构建了keras模型,而在上述链接中,它是为CNN网络构建的,具有完全不同的体系结构。如果我点击上面的链接,我将不得不完全更改代码。 同样在其他类似的存储库中,它们也用于CNN进行图像处理,但是在我的用例中,我必须通过LSTM网络基于先前单词的上下文来预测下一个单词。 该模型在控制台上具有很好的准确性,但是必须在移动应用程序的实时键盘上进行测试。
所以我的问题是,是否有一种方法或工具可以将某些代码转换为C ++,或者至少如何读取基于LSTM网络(model_chat2_3.h5)和tokenizer_chat2_3.pkl文件构建的keras模型。进入C ++。 另外,如果有人可以指导我将keras模型直接部署在移动应用程序上,以用作键盘。再次使用现有的所有存储库,在移动应用程序上部署基于CNN的模型以执行与图像相关的事情
Keras LSTM model to android这也将有所帮助,但尚未有人回答。
我是C ++的新手,由于时间有限,因此无法为其编写完整的代码。任何帮助表示赞赏!