c ++从模板返回

时间:2016-02-29 15:49:57

标签: c++ templates mlpack

我对使用C ++中的模板进行泛型编程有点新,并且对如何从模板化函数返回对象有疑问。这是mlpack库的神经网络模块的一部分。这来自feedforward_network_test.cpp,可以找到here。如果我理解这一点,模板化函数BuildVanillaNetwork的设置方式,可以传递不同类型的网络参数来构建神经网络。我想要的是这个函数返回它构建的FFN对象,以便我可以从我调用的地方访问它。我对那里的代码做了一些小改动:

template <typename PerformanceFunction,
         typename OutputLayerType,
         typename PerformanceFunctionType,
         typename MatType = arma::mat
         >
mlpack::ann::FFN<> BuildVanillaNetwork(MatType& trainData,
        MatType& trainLabels,
        MatType& testData,
        MatType& testLabels,
        const size_t hiddenLayerSize,
        const size_t maxEpochs,
        const double classificationErrorThreshold)
{
    // input layer
    mlpack::ann::LinearLayer<> inputLayer(trainData.n_rows, hiddenLayerSize);
    mlpack::ann::BiasLayer<> inputBiasLayer(hiddenLayerSize);
    mlpack::ann::BaseLayer<PerformanceFunction> inputBaseLayer;

    // hidden layer
    mlpack::ann::LinearLayer<> hiddenLayer1(hiddenLayerSize, trainLabels.n_rows);
    mlpack::ann::BiasLayer<> hiddenBiasLayer1(trainLabels.n_rows);
    mlpack::ann::BaseLayer<PerformanceFunction> outputLayer;

    // output layer
    OutputLayerType classOutputLayer;

    auto modules = std::tie(inputLayer, inputBiasLayer, inputBaseLayer, hiddenLayer1, hiddenBiasLayer1, outputLayer);
    mlpack::ann::FFN<decltype(modules), decltype(classOutputLayer), mlpack::ann::RandomInitialization, PerformanceFunctionType> net(modules, classOutputLayer);
    net.Train(trainData, trainLabels);
    MatType prediction;
    net.Predict(testData, prediction);

    double classificationError;
    for (size_t i = 0; i < testData.n_cols; i++)
    {
        if (arma::sum(arma::sum(arma::abs(prediction.col(i) - testLabels.col(i)))) != 0)
        {
            classificationError++;
        }
    }

     classificationError = double(classificationError) / testData.n_cols;

    std::cout << "Classification Error = " << classificationError * 100 << "%" << std::endl;

    return net;
}

这是主要功能:

int main(int argc, char** argv)
{
    arma::mat dataset;
    mlpack::data::Load("../data/thyroid_train.csv", dataset, true);
    arma::mat trainData = dataset.submat(0, 0, dataset.n_rows - 4, dataset.n_cols - 1);
    arma::mat trainLabels = dataset.submat(dataset.n_rows - 3, 0, dataset.n_rows - 1, dataset.n_cols - 1);

    mlpack::data::Load("../data/thyroid_test.csv", dataset, true);
    arma::mat testData = dataset.submat(0, 0, dataset.n_rows - 4, dataset.n_cols - 1);
    arma::mat testLabels = dataset.submat(dataset.n_rows - 3, 0, dataset.n_rows - 1, dataset.n_cols - 1);

    const size_t hiddenLayerSize = 8;
    const size_t maxEpochs = 200;
    const double classificationErrorThreshold = 0.1;

    auto myFFN = BuildVanillaNetwork<mlpack::ann::LogisticFunction, mlpack::ann::BinaryClassificationLayer, mlpack::ann::MeanSquaredErrorFunction>
        (trainData, trainLabels, testData, testLabels, hiddenLayerSize, maxEpochs, classificationErrorThreshold);

    return 0;
}

编译时,我收到以下错误:

[100%] Building CXX object CMakeFiles/ff_nn.dir/src/ff_nn.cpp.o /home/username/project-yanack/mlpack_nn/src/ff_nn.cpp:24:18: error: wrong number of template arguments (0, should be 4)  mlpack::ann::FFN<> BuildVanillaNetwork(MatType& trainData,
                  ^ In file included from /home/username/project-yanack/mlpack_nn/src/ff_nn.cpp:16:0: /usr/local/include/mlpack/methods/ann/ffn.hpp:35:7: error: provided for ‘template<class LayerTypes, class OutputLayerType, class InitializationRuleType, class PerformanceFunction> class mlpack::ann::FFN’  class FFN
       ^ /home/username/project-yanack/mlpack_nn/src/ff_nn.cpp: In instantiation of ‘int BuildVanillaNetwork(MatType&, MatType&, MatType&, MatType&, size_t, size_t, double) [with PerformanceFunction
= mlpack::ann::LogisticFunction; OutputLayerType = mlpack::ann::BinaryClassificationLayer; PerformanceFunctionType = mlpack::ann::MeanSquaredErrorFunction; MatType = arma::Mat<double>; size_t = long unsigned int]’: /home/username/project-yanack/mlpack_nn/src/ff_nn.cpp:83:112:   required from here /home/username/project-yanack/mlpack_nn/src/ff_nn.cpp:64:12: error: cannot convert ‘mlpack::ann::FFN<std::tuple<mlpack::ann::LinearLayer<arma::Mat<double>, arma::Mat<double> >&, mlpack::ann::BiasLayer<arma::Mat<double>, arma::Mat<double> >&, mlpack::ann::BaseLayer<mlpack::ann::LogisticFunction, arma::Mat<double>, arma::Mat<double> >&, mlpack::ann::LinearLayer<arma::Mat<double>, arma::Mat<double> >&, mlpack::ann::BiasLayer<arma::Mat<double>, arma::Mat<double> >&, mlpack::ann::BaseLayer<mlpack::ann::LogisticFunction, arma::Mat<double>, arma::Mat<double> >&>, mlpack::ann::BinaryClassificationLayer, mlpack::ann::RandomInitialization, mlpack::ann::MeanSquaredErrorFunction>’ to ‘int’ in return
     return net;
            ^ make[2]: *** [CMakeFiles/ff_nn.dir/src/ff_nn.cpp.o] Error 1 make[1]: *** [CMakeFiles/ff_nn.dir/all] Error 2 make: *** [all] Error 2

任何帮助解决此问题表示赞赏。此外,如果我能获得解释此代码中使用的各种概念的教程的链接,那将会很棒。

修改-1

我将函数标题更改为:

template <typename PerformanceFunction,
         typename OutputLayerType,
         typename PerformanceFunctionType,
         typename MatType = arma::mat
         >
mlpack::ann::FFN<PerformanceFunction, OutputLayerType, PerformanceFunctionType, MatType> BuildVanillaNetwork(MatType& trainData,
        MatType& trainLabels,
        MatType& testData,
        MatType& testLabels,
        const size_t hiddenLayerSize,
        const size_t maxEpochs,
        const double classificationErrorThreshold)

但编译时我仍然遇到错误:

[100%] Building CXX object CMakeFiles/ff_nn.dir/src/ff_nn.cpp.o
In file included from /home/username/project-yanack/mlpack_nn/src/ff_nn.cpp:16:0:
/usr/local/include/mlpack/methods/ann/ffn.hpp: In instantiation of ‘class mlpack::ann::FFN<mlpack::ann::LogisticFunction, mlpack::ann::BinaryClassificationLayer, mlpack::ann::MeanSquaredErrorFunction, arma::Mat<double> >’:
/home/username/project-yanack/mlpack_nn/src/ff_nn.cpp:83:112:   required from here
/usr/local/include/mlpack/methods/ann/ffn.hpp:361:55: error: incomplete type ‘std::tuple_size<mlpack::ann::LogisticFunction>’ used in nested name specifier
       size_t Max = std::tuple_size<LayerTypes>::value - 1,
                                                       ^
/usr/local/include/mlpack/methods/ann/ffn.hpp:369:55: error: incomplete type ‘std::tuple_size<mlpack::ann::LogisticFunction>’ used in nested name specifier
       size_t Max = std::tuple_size<LayerTypes>::value - 1,
                                                       ^
/home/username/project-yanack/mlpack_nn/src/ff_nn.cpp: In instantiation of ‘mlpack::ann::FFN<PerformanceFunction, OutputLayerType, PerformanceFunctionType, MatType> BuildVanillaNetwork(MatType&, MatType&, MatType&, MatType&, size_t, size_t, double) [with PerformanceFunction = mlpack::ann::LogisticFunction; OutputLayerType = mlpack::ann::BinaryClassificationLayer; PerformanceFunctionType = mlpack::ann::MeanSquaredErrorFunction; MatType = arma::Mat<double>; size_t = long unsigned int]’:
/home/username/project-yanack/mlpack_nn/src/ff_nn.cpp:83:112:   required from here
/home/username/project-yanack/mlpack_nn/src/ff_nn.cpp:64:12: error: could not convert ‘net’ from ‘mlpack::ann::FFN<std::tuple<mlpack::ann::LinearLayer<arma::Mat<double>, arma::Mat<double> >&, mlpack::ann::BiasLayer<arma::Mat<double>, arma::Mat<double> >&, mlpack::ann::BaseLayer<mlpack::ann::LogisticFunction, arma::Mat<double>, arma::Mat<double> >&, mlpack::ann::LinearLayer<arma::Mat<double>, arma::Mat<double> >&, mlpack::ann::BiasLayer<arma::Mat<double>, arma::Mat<double> >&, mlpack::ann::BaseLayer<mlpack::ann::LogisticFunction, arma::Mat<double>, arma::Mat<double> >&>, mlpack::ann::BinaryClassificationLayer, mlpack::ann::RandomInitialization, mlpack::ann::MeanSquaredErrorFunction>’ to ‘mlpack::ann::FFN<mlpack::ann::LogisticFunction, mlpack::ann::BinaryClassificationLayer, mlpack::ann::MeanSquaredErrorFunction, arma::Mat<double> >’
     return net;
            ^
make[2]: *** [CMakeFiles/ff_nn.dir/src/ff_nn.cpp.o] Error 1
make[1]: *** [CMakeFiles/ff_nn.dir/all] Error 2
make: *** [all] Error 2

此外,FFN类(here)的签名似乎与我在此函数中的签名不同。这可能是个问题吗?如果是,我该如何修复它,因为据我所知,这些类型名称并不是真正的“类型”。

感谢。

3 个答案:

答案 0 :(得分:0)

mlpack::ann::FFN<> BuildVanillaNetwork(MatType& trainData,

将其更改为包含模板中参数的内容,例如:

mlpack::ann::FFN<
    PerformanceFunction,
    OutputLayerType,
    PerformanceFunctionType,
    MatType
> BuildVanillaNetwork(MatType& trainData,...

如果编译器支持,请尝试decltype(auto)

auto BuildVanillaNetwork(MatType& trainData,`...) -> decltype(auto) {...

答案 1 :(得分:0)

问题是您将BuildVanillaNetwork函数定义为:

mlpack::ann::FFN<> BuildVanillaNetwork(...)

当人们涉及模板时,错误消息通常很难被人阅读,但通过这些行读取会给出类似这样的信息:

  

错误:模板参数数量错误(0,应为4)...为'模板类mlpack :: ann :: FFN'提供

其余错误是由这个引起的(基本上,因为它不了解该函数的返回类型,编译器认为它是int,然后它会抱怨它可以&#39 ; t将net转换为int)。

因此,您必须实际指定返回类型的模板参数。您在函数体中使用decltype来推导它们(这发生在编译时,而不是运行时),但在原型中它不会那么容易。有一种方法可以使用decltype来声明函数的返回类型,但在这种情况下它不会帮助你。所以你不妨继续明确地写下来。

答案 2 :(得分:0)

您可以使用以下模式稍微简化返回类型推断:

template<typename PerformanceFunction, typename OutputLayerType,
    typename PerformanceFunctionType, typename MatType>
struct BuildVanillaNetworkHelper
{
    using LinearLayer = mlpack::ann::LinearLayer<>;
    using BiasLayer = mlpack::ann::BiasLayer<>;
    using BaseLayer = mlpack::ann::BaseLayer<PerformanceFunction>;
    using ModulesType = std::tuple<LinearLayer, BiasLayer, BaseLayer,
        LinearLayer, BiasLayer, BaseLayer>;
    using FFNType = mlpack::ann::FFN<ModulesType, OutputLayerType,
        mlpack::ann::RandomInitialization, PerformanceFunctionType>;
};

template <typename PerformanceFunction,
         typename OutputLayerType,
         typename PerformanceFunctionType,
         typename MatType = arma::mat,
         typename Helper = BuildVanillaNetworkHelper<
             PerformanceFunction, OutputLayerType,
             PerformanceFunctionType, MatType>
         >
typename Helper::FFNType BuildVanillaNetwork(...);