gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 01:44:04 28 4
gpt4 key购买 nike

我认为这应该是一件非常简单的事情,但我没有解决它。我正在尝试对两个 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com