如何将特征张量的值作为'if'条件表达式

how to make the eigen tensor's value as the 'if' condition expression

本文关键字:if 表达式 条件 特征 张量      更新时间:2023-10-16

if中的条件应该是布尔类型,但我只能得到compare的特征张量表达式。所以它在编译时会出现错误。我的问题是如何修改以下代码以使if条件合法。

Eigen::Tensor<float, 1> linear(2);
linear.setValues({3,4});
auto linear_square = (linear * linear).sum().sqrt();  // linear_square: 5
auto compare = (linear_square>linear_square.constant(4));
if(compare)  // bug: compare cannot be converted to bool
std::cout<<"hahaha"<<std::endl;

主要问题是您使用了关键字auto,它以令人惊讶的方式适用于 Eigen。

基本上,张量运算的输出不是张量,而是一个运算,即如何组合张量的方法。当您将此值(操作(分配给张量时,将触发计算。因此,您需要使用张量作为运算输出的类型,以便触发计算。

文档比我精确一点:https://eigen.tuxfamily.org/dox-devel/unsupported/eigen_tensors.html,我引用(强调我的(:

由于张量操作创建了张量运算符,因此C++auto关键字没有其直观的含义。考虑这 2 行 法典:

Tensor<float, 3> t3 = t1 + t2;
auto t4 = t1 + t2;

在第一行中,我们分配张量t3,它将包含 添加t1t2的结果。在第二行中,t4是 实际上是将计算加法的张量算子树 的t1t2.事实上,t4不是张量,你无法得到 其元素的值:

Tensor<float, 3> t3 = t1 + t2;
cout << t3(0, 0, 0);  // OK prints the value of t1(0, 0, 0) + t2(0, 0, 0)
auto t4 = t1 + t2;
cout << t4(0, 0, 0);  // Compilation error!

所以我避免使用auto,而是使用秩 0 的张量(文档告诉我sum()返回秩 0 张量(。这触发了计算,使compare成为真正的张量。此代码编译并按预期运行:

#include <iostream>
#include <unsupported/Eigen/CXX11/Tensor>
int main()
{
Eigen::Tensor<float, 1> linear{2};
linear.setValues({ 3,4 });
//Here you can use auto because you do not try to get data out of this element, I am making explicit the dimensionality
Eigen::Tensor<float, 0> linear_square = (linear * linear).sum().sqrt();  // linear_square: 5
//Here you need conversion to Tensor
Eigen::Tensor<bool, 0> compare = linear_square > linear_square.constant(4);
if (compare(0)) 
std::cout << "hahaha" << std::endl;
else
std::cout << "no" << std::endl;
}

我使用 MSVC 2019 进行了编译,并使用了 Eigen 3.3.3(NuGet 中可用的那个(。