- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
arr = np.arange(16).reshape((2, 2, 4))
arr.strides
(32, 16, 4)
因此,据我所知,我相信在内存中它会类似于下图。步幅沿轴标记(在箭头上)。
这就是我在使用命令转置其中一个轴后的想法:
arr.transpose((1, 0, 2))
我知道内存块中没有变化,但我无法理解步幅究竟如何帮助遍历内存块中的数组以生成预期的数组。 (是否将不同轴上的元素倒序遍历?)
[[[ 0 1 2 3]
[ 4 5 6 7]]
[[ 8 9 10 11]
[12 13 14 15]]]
我尝试通过 C 中的官方 numpy 代码来理解,但我无法理解。
如果有人能以更简单的方式提供解释,那就太好了。
最佳答案
除非明确要求(例如使用 axis
参数),否则 Numpy 总是从最大的轴到最小的轴迭代轴(即降序)。因此,在您的示例中,它首先读取内存中偏移量 0 处的 View 项目,然后添加轴 2 的步幅(此处为 4)并读取下一个项目,依此类推,直到到达轴的末端。然后它添加一次轴 1 的步幅并再次重复之前的循环,以此类推其他轴。
内部 Numpy C 代码的行为如下:
// Numpy array are not strongly typed internally.
// The raw memory buffer is always contiguous.
char* data = view.rawData;
const size_t iStride = view.stride[0];
const size_t jStride = view.stride[1];
const size_t kStride = view.stride[2];
for(int i=0 ; i<view.shape[0] ; ++i) {
for(int j=0 ; j<view.shape[1] ; ++j) {
for(int k=0 ; k<view.shape[2] ; ++k) {
// Compute the offset from the view strides
const size_t offset = iStride * i + jStride * j + kStride * k;
// Extract an item at the memory offset
Type item = (Type*)(data + offset);
// Do something with item here (eg. print it)
}
}
}
当您应用转置时,Numpy 会更改步幅,以便交换 iStride
和 jStride
。它还会更新形状(view.shape[0]
和 view.shape[1]
也被交换)。代码将执行就像交换两个循环一样,除了内存访问效率较低,因为它们不连续。这是一个例子:
arr = np.arange(16).reshape((2, 2, 4))
arr.strides # (32, 16, 4)
view = arr.transpose((1, 0, 2))
view.strides # (16, 32, 4) <-- note that 16 and 32 have been swapped
请注意,步幅以字节为单位(而不是项目数)。
关于numpy - 步幅如何帮助遍历 numpy 中的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70366891/
我不确定哪种结构布局最适合我的应用程序:共享、打包、std140、std430。我并不是要求对每个信息进行解释,这些信息很容易找到,只是很难弄清楚每个信息对供应商兼容性/性能的影响。如果 shared
如何在 Swift 中获取特定数字类型的最小值(跨度)?我的意思是,最短的非零步幅。例如 1 代表 Int,0.00...001 代表 Double 等... 最佳答案 这已经在单独的评论中得到了部分
有没有办法告诉 numpy 在写入 python pickle 文件时保留非标准步幅? >>> # Create an array with non-standard striding >>> x =
我将图像存储为 2d numpy 数组(可能是多维)。 我可以在那个反射(reflect)二维滑动窗口的数组上创建一个 View ,但是当我 reshape 它以使每一行都是一个扁平化的窗口(行是窗口
我是一名优秀的程序员,十分优秀!