Pytorch C++ 矩阵变形和维度调整

pytorch c++ 环境搭建,点击

#include <torch/script.h>
#include <ATen/ATen.h>

#include <iostream>
#include <memory>

using namespace std;
using namespace at;

int main(int argc, const char* argv[])
{

    torch::Tensor a = torch::randn({2,3});
    std::cout<< a << std::endl;
    std::cout<< a.sizes() << std::endl;
    auto b = at::transpose(a,1,0);
    std::cout<< b << std::endl;
    std::cout<< b.sizes() << std::endl;
    std::cout<< "--------------------" << std::endl;

    torch::Tensor x = torch::randn({4,6});
    std::cout<< x.sizes() << std::endl;
    auto y = at::_th_view(x,{2,12});
    std::cout<< y.sizes() << std::endl;
    std::cout<< "--------------------" << std::endl;
    
    torch::Tensor m = torch::randn({4,6});
    std::cout<< m.sizes() << std::endl;
    auto n = at::_th_view(m,{2,3,4});
    std::cout<< n.sizes() << std::endl;
    std::cout<< "--------------------" << std::endl;

    std::cout<< "ok\n";
    return 1;
}

编译并执行

make clean
make
./bin/demo

输出结果

rose@rose-machine:~/pytorch_c++/test$ ./bin/demo 
 0.0786 -0.8607  0.3106
-0.5987 -0.3663  0.4673
[ Variable[CPUFloatType]{2,3} ]
[2, 3]
 0.0786 -0.5987
-0.8607 -0.3663
 0.3106  0.4673
[ Variable[CPUFloatType]{3,2} ]
[3, 2]
--------------------
[4, 6]
[2, 12]
--------------------
[4, 6]
[2, 3, 4]
--------------------
ok

猜你喜欢

转载自blog.csdn.net/luolinll1212/article/details/85339585