c++实现argmax

该博客介绍了如何使用C++实现argmax函数,处理语义分割模型(如TensorRT)的输出结果。该模型通常以nchw格式返回数据,argmax函数用于找到每个像素的最大通道值并返回其索引,从而帮助解析模型的预测结果。
摘要由CSDN通过智能技术生成

c++实现argmax处理语义分割trt模型输出结果

一般分割模型输出的是nchw格式数据

void argmax(float* x, int* y, int rows, int cols, int chan)
{
    for(int i = 0,wh = rows * cols; i < rows; i++)
    {
        for(int j = 0; j < cols; j++)
        {
            int max = -10000000;
            int max_ind = -1;
            for(int k = 0; k < chan; k++)
            {
                if(x[k * wh + i * cols + j] > max)
                {
                    max = x[k * wh + i * cols + j];
                    max_ind = k;
                }
                
            }
            y[i * cols + j] = max_ind;
        }
    }
}
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
以下是一个简单的 C++ 实现,使用了第三方库 Hugging Face Transformers 和 Torch: ```cpp #include <iostream> #include <string> #include <vector> #include <torch/torch.h> #include <torch/script.h> #include <transformers/transformers.h> int main() { // 加载模型和 tokenizer std::string model_path = "path/to/model"; std::string vocab_path = "path/to/vocab"; transformers::BertTokenizer tokenizer(vocab_path); torch::jit::script::Module model = torch::jit::load(model_path); // 设置模型为 eval 模式 model.eval(); // 对话循环 std::string input_text; std::vector<std::string> history; while (true) { // 获取用户输入 std::getline(std::cin, input_text); // 把历史记录和用户输入拼接成一个字符串 std::string context = ""; for (const auto& h : history) { context += h + tokenizer.get_ending_of_wordpiece(); } context += input_text; // 把字符串编码成 token std::vector<std::string> tokens = tokenizer.encode(context); // 把 token 转换成 tensor std::vector<int64_t> input_ids(tokens.size()); std::transform(tokens.begin(), tokens.end(), input_ids.begin(), [&](const std::string& token) { return std::stoi(token); }); torch::Tensor input_tensor = torch::tensor(input_ids).unsqueeze(0); // 用模型生成回复 std::vector<torch::jit::IValue> inputs; inputs.push_back(input_tensor); at::Tensor output_tensor = model.forward(inputs).toTensor(); // 把回复从 tensor 转换成字符串 std::vector<int64_t> output_ids = output_tensor.argmax(/*dim=*/2).squeeze().tolist(); std::vector<std::string> output_tokens(output_ids.size()); std::transform(output_ids.begin(), output_ids.end(), output_tokens.begin(), [&](const int64_t id) { return std::to_string(id); }); std::string output_text = tokenizer.decode(output_tokens); // 输出回复并更新历史记录 std::cout << output_text << std::endl; history.push_back(input_text); history.push_back(output_text); } return 0; } ``` 需要注意的是,这个实现可能不够完整和稳定,还需要根据实际情况进行进一步的调整和优化。
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值