c++ - 如何在 C++ 中将 torch 模型定义为函数的输入

标签 c++ libtorch

我正在用 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/

相关文章:

c++ - Qt 中的全局菜单与 QtMenuBar

python - 在从 PyTorch 训练和导出的 LibTorch 中运行模型时获得的结果不正确

c++ - 带有 Cuda 的 LibTorch(C++) 引发异常

c++ - 运行时错误 (SIGSEGV)

android - 如何绘制/渲染 Bullet Physics 碰撞体/形状?

visual-studio - 在 Windows 上的 C++ 应用程序中使用 PyTorch 模型

pytorch - 为什么在 iOS 上使用 Caffe2 或 Core-ML 而不是 LibTorch(.pt 文件)?

c++ - libtorch : How to create a gpu tensor base on data_ptr?

C++ 格式化程序取消拆分行

c++ - QTextBrowser 问题与 css