我有以下多維陣列:
windows = array([[[[[[0., 0.],
[1., 0.]],
[[0., 0.],
[1., 0.]],
[[0., 0.],
[1., 0.]]],
[[[0., 1.],
[0., 0.]],
[[0., 1.],
[0., 0.]],
[[1., 0.],
[0., 0.]]],
[[[1., 0.],
[0., 0.]],
[[0., 1.],
[0., 0.]],
[[0., 1.],
[0., 0.]]]]]])
print(windows.shape)
(1, 1, 3, 3, 2, 2) # (n, d, a, b, c, c) w = a * (c*c), h = b * (c*c)
我想得到下一個結果陣列:
mask = array([[
[[0., 0., 0., 0., 0., 0.],
[1., 0., 1., 0., 1., 0.],
[0., 1., 0., 1., 1., 0.],
[0., 0., 0., 0., 0., 0.],
[1., 0., 0., 1., 0., 1.],
[0., 0., 0., 0., 0., 0.]]
]], dtype=np.float32)
print(mask.shape)
(1, 1, 6, 6) # (n, d, w, h)
基本上,我想將最后 4 個維度壓縮到二維矩陣中,以便最終形狀變為 (n, d, w, h),在這種情況下為 (1, 1, 6, 6)。
我試過了np.concatenate(windows, axis = 2),但它沒有沿著第二維連接,并且由于某種原因首先減少了(雖然我設定了軸 = 2)'n'維。
附加資訊:
windows 是以下代碼片段的結果
windows = np.lib.stride_tricks.sliding_window_view(arr, (c, c), axis (-2,-1), writeable = True) # arr.shape == mask.shape
windows = windows[:, :, ::c, ::c] # these are non-overlapping windows of arr with size (c,c)
windows = ... # some modifications of windows
現在我想從這些形狀為 的 windows 陣列構建arr.shape,這個陣列mask在上面的例子中被呼叫。簡單的 reshape 不起作用,因為它以錯誤的順序回傳元素。
uj5u.com熱心網友回復:
IIUC,您想要合并維度 2 4 和 3 5,一個簡單的方法是合并到swapaxes4 和 5(或 -3 和 -2)以及reshape到 (1,1,6,6):
windows.swapaxes(-2,-3).reshape(1,1,6,6)
輸出:
array([[[[0., 0., 0., 0., 0., 0.],
[1., 0., 1., 0., 1., 0.],
[0., 1., 0., 1., 1., 0.],
[0., 0., 0., 0., 0., 0.],
[1., 0., 0., 1., 0., 1.],
[0., 0., 0., 0., 0., 0.]]]])
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/352607.html
上一篇:如何定期確定python陣列元素
