gpt4 book ai didi

python - Numpy 在转置矩阵时如何移动数据?

转载 作者:太空宇宙 更新时间:2023-11-03 21:23:27 25 4
gpt4 key购买 nike

看起来 numpy.transpose 只节省了步幅,并且实际上根据 this 进行了惰性转置

那么,数据移动实际上发生在什么时候以及如何移动?使用很多很多memcpy?或者其他一些技巧?

我遵循以下路径: 奥 git _a, 奥 git _a, 奥 git _a, 奥 git _a,PyArray_NewFromDescrPyArray_NewFromDecrAndBase, 奥 git _a但看不到任何关于轴排列的信息。这真的是什么时候发生的?

<小时/>

更新2021/1/19

感谢您的解答,numpy array copy with transpose 是 array_reshape ,它使用常见的 PyArray_Newshape 来实现,这个算法非常原生,并且没有考虑任何 simd 加速或缓存友好性

最佳答案

您的问题的答案是:Numpy 不会移动数据。

您在上述链接的 688 行上看到 PyArray_Transpose 了吗?该函数中有一个排列,

    n = permute->len;
axes = permute->ptr;
...
for (i = 0; i < n; i++) {
int axis = axes[i];
...
permutation[i] = axis;
}

任何数组形状都是纯粹的元数据,Numpy 使用它来了解如何处理数据,因为内存始终是线性且连续存储的。因此,没有理由从文档 here 中移动或重新排序任何数据,

Other operations, such as transpose, don't move data elements around in the array, but rather change the information about the shape and strides so that the indexing of the array changes, but the data in the doesn't move. Typically these new versions of the array metadata but the same data buffer are new 'views' into the data buffer. There is a different ndarray object, but it uses the same data buffer. This is why it is necessary to force copies through use of the .copy() method if one really wants to make a new and independent copy of the data buffer.

复制的唯一原因可能是最大化 cache efficiency ,尽管 Numpy 已经 considers 了,

As it turns out, numpy is smart enough when dealing with ufuncs to determine which index is the most rapidly varying one in memory and uses that for the innermost loop.

关于python - Numpy 在转置矩阵时如何移动数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54039225/

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