我正在用 c++ 加载一个模型,该模型是用 python 训练的。现在我想编写一个函数,用随机输入测试模型,但我无法将模型定义为函数的参数。我已经尝试过结构,但它不起作用。
void test(vector<struct comp*>& model){
//pseudo input
vector<torch::jit::IValue> inputs;
inputs.push_back(torch::ones({1,3,224, 224}));
at::Tensor output = model[0]->forward(inputs).toTensor();
cout << output << endl;
}
int main(int argc, char *argv[]) {
if (argc == 2){
cout << argv[1] << endl;
//model = load_model(argv[1]);
torch::jit::script::Module module = torch::jit::load(argv[1]);
}
else {
cerr << "no path of model is given" << endl;
}
// test
vector<struct comp*> modul;
modul.push_back(module);
test(modul);
}
最佳答案
编辑:您需要将 module
变量放入范围内!
您的基本类型是torch::jit::script::Module
,因此为其定义一个名称:
using module_type = torch::jit::script::Module;
然后在代码中使用它,同时使用 const
引用作为只读参数:
void test(const vector<module_type>& model){
//pseudo input
vector<torch::jit::IValue> inputs;
inputs.push_back(torch::ones({1,3,224, 224}));
at::Tensor output = model[0]->forward(inputs).toTensor();
cout << output << endl;
}
int main(int argc, char *argv[]) {
if (argc == 2){
cout << argv[1] << endl;
}
else {
cerr << "no path of model is given" << endl;
return -1;
}
// test
module_type module = torch::jit::load(argv[1]);;
vector<module_type> modul;
modul.push_back(module);
test(modul);
}
关于c++ - 如何在 C++ 中将 torch 模型定义为函数的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57218201/