You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++中如何创建initializer_list对象以适配OpenNN的Tensor::setValues方法

C++ OpenNN 动态特征向量传入Tensor问题

我在编写C++代码时遇到了问题,当前使用OpenNN搭建神经网络,需要使用已训练完成的神经网络(变量名neuralnetwork)对特征集合(变量名featureVector)做输出预测。调用的相关函数要求传入initializer_list类型的参数,现有代码如下:

float featureVector[1][5] = {{1, 2, 3, 4, 5}};
Tensor<type, 2> inputs(1, featureLength);
inputs.setValues(featureVector);
neuralnetwork.calculate_outputs(inputs);

运行后收到的报错信息如下:

neuralnetwork.cpp:141:22: error: reference to type 'const typename internal::Initializer<Tensor<float, 2, 0, long long>, NumDimensions>::InitList' (aka 'const initializer_list<initializer_list>') could not bind to an lvalue of type 'float [1][5]'
TensorBase.h:861:81: note: passing argument to parameter 'vals' here

参照OpenNN官方示例修改的代码可以正常运行,但不符合使用需求,原因是需要featureVector为可动态赋值的变量,而非字面量:

Tensor<type, 2> inputs(1, featureLength);
inputs.setValues({{1, 2, 3, 4, 5}});
neuralnetwork.calculate_outputs(inputs);

我还尝试将featureVector改为std::list类型,同样无法运行。我需要将数组或std::list类型的特征向量转换为可用的initializer_list,但没有找到有效的初始化方案。

补充信息

  • neuralnetwork的类型定义:
OpenNN::NeuralNetwork neuralnetwork;
  • calculate_outputs函数定义:
Tensor<type, 2> NeuralNetwork::calculate_outputs(const Tensor<type, 2>& inputs)

可行解决方案

最终我找到符合需求的可行写法如下:

auto featureVector1 = {1.f, 2.f, 3.f, 4.f, 5.f};
auto featureVector = {featureVector1};
Tensor<type, 2> inputs(1, featureLength);
inputs.setValues(featureVector);
neuralnetwork.calculate_outputs(inputs);

该写法虽然不够简洁优雅,但完全满足使用需求。

内容的提问来源于stack exchange,提问作者ano

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 02:45:04