简体   繁体   English

将多维数组切片操作从 python 转换为 C++

[英]converting multidimensional array slice operation from python to C++

I have following code snippet (which is part of a function) in python:我在 python 中有以下代码片段(它是函数的一部分):

def decode_netout(netout, anchors, obj_thresh, net_h, net_w):
        # print("netout print: ", netout.shape, netout[0])
        grid_h, grid_w = netout.shape[:2]
        nb_box = 3
        netout = netout.reshape((grid_h, grid_w, nb_box, -1))
        nb_class = netout.shape[-1] - 5
        boxes = []
        netout[..., :2]  = _sigmoid(netout[..., :2])
        netout[..., 4:]  = _sigmoid(netout[..., 4:])
        netout[..., 5:]  = netout[..., 4][..., np.newaxis] * netout[..., 5:]
        netout[..., 5:] *= netout[..., 5:] > obj_thresh

Here netout is array with 13, 13, 255 which is converted to 13, 13, 3, 85. Now considering following statement,这里 netout 是 13、13、255 的数组,它被转换为 13、13、3、85。现在考虑以下语句,

netout[..., :2]  = _sigmoid(netout[..., :2])

If I need to covert this function code to C++ equivalent, what is the best way to write this code.如果我需要将此 function 代码转换为 C++ 等效代码,那么编写此代码的最佳方法是什么。 In C++, netout is an array of float.在 C++ 中,netout 是一个浮点数组。 thanks and regards, -sunil puranik谢谢和问候,-sunil puranik

Using a high-performance library is recommended here (for example Eigen , PyTorch , ArrayFire or other libraries).此处推荐使用高性能库(例如EigenPyTorchArrayFire或其他库)。 If you want to do it yourself, it goes like this for netout[..., :2] = _sigmoid(netout[..., :2]) as an example:如果你想自己做,以netout[..., :2] = _sigmoid(netout[..., :2])为例:


struct Array
{
    std::vector<size_t> shape;
    std::vector<float> data;
};

float sigmoid(float input)
{
    // return sigmoid function of input
}

void some_operation(Array &array)
{
    size_t Y = 1, X = array.shape.back();

    for (size_t i = 0; i < array.shape.size() - 1; ++i)
    {
        Y *= array.shape[i];
    }

    for (size_t i = 0; i < Y; ++i)
        for (size_t j = 0; j < 2; ++j)
        {
            array.data[i * X + j] = sigmoid(array.data[i * X + j]);
        }
}

Here the some_operation function takes in an array and since the last dimension is important to us, the rest get flattened out.这里的some_operation function 接受一个数组,由于最后一个维度对我们很重要,所以 rest 变得平坦。 So we have two dimensions Y, X .所以我们有两个维度Y, X Now we can iterate over the data and do the operation we want.现在我们可以遍历数据并执行我们想要的操作。

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

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