Home > Blockchain >  How to pass an n-dim Eigen tensor to a function?
How to pass an n-dim Eigen tensor to a function?

Time:10-29

I'm looking to make a loss function that can take 2 tensors of any dimensions as parameters, but the dimensions of tensor 1 (t1) and tensor (t2) must match. Below are the templates that I tried to use to can pass the tensors into the function. I was thinking that T would be a type and N would model the number of indexes possible without explicitly writing a type for infinitely possible tensor dimensions.

loss.h

#include <iostream>

namespace Loss {
    template<class T, std::size_t N>
    void loss(Eigen::Tensor<T, N, 0>& predicted, Eigen::Tensor<T, N, 0>& actual) {
        std::cout << "Loss::loss() not implemented" << std::endl;
    };
};

main.cpp

#include "loss.h"
int main() {

    Eigen::Tensor<double, 3> t1(2, 3, 4);
    Eigen::Tensor<double, 3> t2(2, 3, 4);

    t1.setZero();
    t2.setZero();
  
    Loss::loss(t1, t2);

    return 0;
}

The type error that I get before compiling from my editor:

no instance of function template "Loss::loss" matches the argument list -- argument types are: (Eigen::Tensor<double, 3, 0, Eigen::DenseIndex>, Eigen::Tensor<double, 3, 0, Eigen::DenseIndex>

And this is the message I get once I compile (unsuccessfully):

note: candidate template ignored: substitution failure [with T = double]: deduced non-type template argument does not have the same type as the corresponding template parameter ('int' vs 'std::size_t' (aka 'unsigned long')) void loss(Eigen::Tensor<T, N, 0>& predicted, Eigen::Tensor<T, N, 0>& actual) { ^ 1 error generated.

CodePudding user response:

The error message is pointing out the type of the non-type template parameter is size_t, but in the declaration of t1 and t2 the value of that parameter is 3, which has type int. This mismatch makes the template argument deduction fail.

You can fix this by changing the type of the non-type template parameter to int

template<class T, int N>
void loss( // ...

or just let it be deduced

template<class T, auto N>
void loss( // ...

CodePudding user response:

number literals are signed integers, and you’ve specified the number type of your template as size_t Which is unsigned. So the types don’t match. Try Eigen::Tensor<double, 3u> … in your main program to use unsigned literals.

  • Related