如何将特征张量的值作为'if'条件表达式
how to make the eigen tensor's value as the 'if' condition expression
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
,它将包含 添加t1
和t2
的结果。在第二行中,t4
是 实际上是将计算加法的张量算子树 的t1
和t2
.事实上,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 中可用的那个(。
相关文章:
- 优化/减少 if 语句中的条件表达式
- 代码样式:在 switch/if 语句的分支中重用控件表达式或控制变量
- if 语句中的复合表达式
- 如何将特征张量的值作为'if'条件表达式
- 重构模板函数中的常量表达式 if 语句
- 在 if 语句中返回布尔值的 lambda 表达式
- 布尔表达式是否像使用 if 或 switch 进行分支一样繁琐?
- 为什么我不能在我的三元表达式中使用 return,但我可以在常规的 if-else 语句中使用?
- IF-ELSE语句的Lambda表达式的返回类型扣除
- 'if'之前的主要表达式出现错误
- 为什么 if constexpr 不会使这个核心常量表达式错误消失?
- 带有 or 表达式的 If 语句中的语法错误
- "if"表达式的评估
- C++Bare布尔表达式(不包含if、while或其他语句)
- 求和1~N,不使用乘法、除法、if、while、for、switch和三元表达式
- 在令牌和'else'之前'%'预期的主表达式,没有以前的'if'
- 表达式跟进中的变量声明'if'
- if语句中的函数:期望的错误表达式
- 如何优化If/then条件表达式的长序列- SIMD
- if 表达式中的操作顺序是否更改