c++ - Eigen::Tensor 双收缩到标量值

标签 c++ eigen tensor

我认为这应该是一件非常简单的事情,但我没有解决它。我正在尝试对两个 senond 阶 Eigen 张量进行双收缩。一切正常,但双重收缩的结果是 Eigen 类型:

Eigen::TensorContractionOp<const std::array<Eigen::IndexPair<int>, 2ul>, const Eigen::TensorFixedSize<double, Eigen::Sizes<3l, 3l> >, const Eigen::TensorFixedSize<double, Eigen::Sizes<3l, 3l> > >

但我需要一个double。我可以打印它,但我无法使用它。

代码如下

#include <iostream>
#include <unsupported/Eigen/CXX11/Tensor>

int main()
{

    auto tensor1 = Eigen::TensorFixedSize<double, Eigen::Sizes<3,3>>();
    tensor1.setValues({ {1, 0, 0},
                        {0, 1, 0},
                        {0, 0, 1} });
    std::cout << "tensor1:\n" << tensor1 << "\n";

    auto tensor2 = Eigen::TensorFixedSize<double, Eigen::Sizes<3,3>>();
    tensor2.setValues({ {2, 0, 0},
                        {0, 2, 0},
                        {0, 0, 2} });
    std::cout << "tensor2:\n" << tensor2 << "\n";

    Eigen::array<Eigen::IndexPair<int>, 2> contraction_pair0011
        = { Eigen::IndexPair<int>(0, 0), Eigen::IndexPair<int>(1, 1)};

    auto tensor1_tensor2 = tensor1.contract(tensor2, contraction_pair0011);
    std::cout << "tensor1 : tensor2:\n" << tensor1_tensor2 << "\n";

    // double value = tensor1_tensor2; // won't compile

}

我需要一个函数或调用来获取结果的值,希望有人能帮助我。

干杯乔纳斯

最佳答案

我解决了这个问题,但认为如果您正在使用 Eigen::Tensor 模块,它也会对您有所帮助。

如所写hereTensor Operations 和 C++“auto” 部分:

因为张量运算创建张量运算符,C++ auto 关键字没有其直观的含义。当您使用 auto 您没有得到张量,而是一个未计算的表达式...

所以张量收缩的结果是

Eigen::TensorContractionOp<...>

而不是我们可以从中获取其元素的张量。所以我们需要知道结果张量的大小。问题是结果必须是用空 Eigen::Sizes<> 完成的标量张量。

Eigen::TensorFixedSize<double, Eigen::Sizes<>>

这里是运行代码。我希望它能帮助别人...

#include <iostream>
#include <unsupported/Eigen/CXX11/Tensor>

int main()
{
    auto tensor1 = Eigen::TensorFixedSize<double, Eigen::Sizes<3,3>>();
    tensor1.setValues({ {1, 0, 0},
                        {0, 1, 0},
                        {0, 0, 1} });
    std::cout << "tensor1:\n" << tensor1 << "\n";

    auto tensor2 = Eigen::TensorFixedSize<double, Eigen::Sizes<3,3>>();
    tensor2.setValues({ {2, 0, 0},
                        {0, 2, 0},
                        {0, 0, 2} });
    std::cout << "tensor2:\n" << tensor2 << "\n";


    Eigen::array<Eigen::IndexPair<int>, 2> contraction_pair0011
        = { Eigen::IndexPair<int>(0, 0), Eigen::IndexPair<int>(1, 1)};

    Eigen::TensorFixedSize<double, Eigen::Sizes<>> tensor1_tensor2 = tensor1.contract(tensor2, contraction_pair0011);
    std::cout << "tensor1 : tensor1:\n" << tensor1_tensor2 << "\n";

    double t1_t2 = tensor1_tensor2(0);
    std::cout << "result in double:\n" << t1_t2 << "\n";
}

关于c++ - Eigen::Tensor 双收缩到标量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45940313/

相关文章:

c++ - 可以在编译时隐式引用类名吗?

c++ - Eigen 中的稀疏矩阵

c++ - 使用特征库再现张量矩阵

c++ - 三角和对称矩阵的特征填充存储和优化操作

python - 在 PyTorch 中索引多维张量中的最大元素

python - 有没有一种聪明的方法可以使用 numpy 消除这些循环?

c++ - 按升序和降序打印链表

c++ - C++中的初始化列表

c++ - 绑定(bind)成员函数的指针/引用的禁止语法

tensorflow - 如何在 tensorflow.js 模型中添加图像并为给定的图像标签训练模型