问题描述
我想检查两个ndarray是否是同一基础ndarray的重叠视图.
I would like to check if two ndarrays are overlapping views of the same underlying ndarray.
要检查两个切片是否完全相同,我可以做类似的事情:
To check that two slices are exactly the same, I can do something like:
a.base is b.base and a.shape == b.shape and a.data == b.data
在一个简单的情况下,比较缓冲区似乎是可行的-谁能告诉我它是否在一般情况下起作用?
The comparison of buffers seemed to work in one simple case -- can anyone tell me if it works in general?
不幸的是,这不适用于重叠的切片,而且我还没有弄清楚如何从缓冲区中准确提取其在基础数据中的偏移量,也许有人可以帮助我吗?
Unfortunately, this wont work for overlapping slices, and I haven't figured out how to extract from the buffer exactly what its offset is in the underlying data -- perhaps someone can help me with this?
也可以说a
和b
是x
的切片,而c
是b
的切片.由于基础数据相同,因此我也想检测c
和a
之间的重叠.似乎我应该能够只比较缓冲区和形状...如果有人可以告诉我确切的方法,我将不胜感激.
Also, say a
and b
are slices of x
, and c
is a slice of b
. As the underlying data is the same, I would also like to detect overlaps between c
and a
. It would seem that I should be able to get away with comparing just buffer and shape... if anyone could tell me exactly how, I would be grateful.
推荐答案
numpy.may_share_memory()
是我们目前拥有的最佳启发式方法.保守地讲,它是启发式的.它可能会给您带来误报,但不会给您带来误报.我认为可能有办法将启发式方法改进为100%正确.如果将其展开,则将它们折叠到该功能中,因此这是前进的最佳方法.
numpy.may_share_memory()
is the best heuristic that we have at the moment. It is conservatively heuristic; it may give you false positives, but it will not give you false negatives. I think there might be ways to improve the heuristic to be 100% correct. If they pan out, they will be folded into that function, so that's the best way forward.
这篇关于如何检查numpy数组的两个切片相同(或重叠)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!