简体   繁体   English

如何循环 C++ 中 Pytorch 张量中的每个值?

[英]How to loop over every value in Pytorch tensor in C++?

I am trying to do something like [0 if i < 1 else 1] for PyTorch tensor in C++. I tried to use tensor.accessor(), but it seem like it require you to know the dimension beforehand.我正在尝试对 C++ 中的 PyTorch 张量执行类似 [0 if i < 1 else 1] 的操作。我尝试使用 tensor.accessor(),但它似乎要求您事先知道维度。 While I want to pass it dynamically.虽然我想动态传递它。

Is there anyway I could do this in C++ for Pytorch?无论如何我可以在 C++ 中为 Pytorch 执行此操作吗?

See if this helps:看看这是否有帮助:

Using TensorIterator:使用张量迭代器:

https://labs.quansight.org/blog/2020/04/pytorch-tensoriterator-internals/ https://labs.quansight.org/blog/2020/04/pytorch-tensoriterator-internals/

Or leveraging t.is_contiguous() / t.contiguous() to simplify transversal:或利用 t.is_contiguous() / t.contiguous() 来简化横向:

https://discuss.pytorch.org/t/iterating-over-tensor-in-c/60333/2 https://discuss.pytorch.org/t/iterating-over-tensor-in-c/60333/2

For loop in c++ torch is like this. c++ torch中的for循环是这样的。 Also, you can try torch.where.另外,你可以试试 torch.where。 Be advised that for loop might be slow compared to built-in operations.请注意,与内置操作相比,for 循环可能会很慢。

        auto answer = torch::zeros_like(x);
        auto batchCount = x.sizes()[0];
        auto pointCount = x.sizes()[1];
        
        // auto nextPoint = torch::zeros({batchCount, _pointDim});
        for (int i = 0; i < batchCount; ++i)
        {
            for (int j = 1; j < _pointCount; ++j)
            {
                answer[i][j] = answer[i][j - 1] + x[i][j - 1];
            } 
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM