Eigen:如何将 "greater than"(在 ArrayXf 上)的结果转换为 Eigen 向量

Eigen: how to convert the result of "greater than" (on ArrayXf) to Eigen vector

考虑以下代码:

Eigen::VectorXf classify()
{
   Eigen::VectorXf probability(4);
   probability << 0.9, 0.8, -0.1, 0.2;

   auto y_pred = probability.array() > 0.8; //what is the type of y_pred?
   //y_pred looks like [1 0 0 0]

   // how to return y_pred as a VectorXf? 
   // I'm trying this, but it is not working:
   return static_cast<Eigen::VectorXf>(y_pred); //doesn't work
}

int main() 
{
   classify();
}

2 个问题:

不,progress会运算右边的表达式所以auto a=3>2会return bool:1 or 0.(如果右边的表达式为真则left的值为1) 所以,y_pred 的类型是 bool.

如果你看一下 Eigen documentation,你会注意到 Eigen::VectorXf 实际上是 Eigen::Matrix<float, Eigen::Dynamic, 1>typedef

类型y_pred

Eigen::Matrix class 派生自 Eigen::MatrixBase template class, which is where the array() member function comes from. This method returns a wrapper object, which can basically be considered as an Eigen::Array。将比较运算符应用于 array() 的结果会产生 boolEigen::Array

转换为类向量类型

文档有一个 section dedicated to the use of the Eigen::Array class. One subsection, namely Converting between array and matrix expressions, is of particular interest in the context of your question. There, one can read that an Eigen::Array may be converted to an Eigen::Matrix by using the matrix() 方法。

根据以上观察结果,您应该能够通过 returning y_pred.matrix() 而不是 static_cast<Eigen::VectorXf>(y_pred)y_pred 转换为某种向量。 return 类型可能类似于 Eigen::Matrix<bool, Eigen::Dynamic, 1>.

由于 bool 的矩阵在线性代数运算中不太常见,因此没有 typedef 与之关联。

y_pred 是一个抽象表达式。它的类型类似于(为了便于阅读而简化):

CWiseBinaryOp<greater<float>,ArrayWrapper<VectorXf>,CwiseNullaryOp<Constant<float>,ArrayXf>>

它继承了ArrayBase,它的Scalar类型是bool

如果您想要 VectorXf,则将布尔值转换为浮点数:

VectorXf foo = y_pred.cast<float>();

在这种情况下,从 arraymatrix 的转换是隐式的。