You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何沿不同深度维度堆叠转换Numpy数组的简便方法

Solution to Transform rot_F to desired_filters

First, let's recap the setup to make sure we're on the same page. Here's how you generate rot_F:

import numpy as np

# Original F array
F = np.array( [
    [ # Filter 0
        [ # Depth 0
            [1, -1], [2, 0]
        ],
        [ # Depth 1
            [ 0, 0], [-1, -1]
        ]
    ],
    [ # Filter 1
        [ # Depth 0
            [0, -1], [3, 0]
        ],
        [ # Depth 1
            [ 1, 2], [-1, -1]
        ]
    ]
] )
F = np.moveaxis(F,1,3) 
rot_F = np.rot90(F,2,(1,2))

Your goal is to reshape rot_F into desired_filters, where we stack all arrays from the 0th depth dimension along their own depth axis, and do the same for the 1st depth dimension—while keeping the overall array shape intact.

The Transformation Code

Here's a concise vectorized way to achieve this using NumPy's axis manipulation functions:

# Swap filter axis (0) with depth axis (3), then swap height (1) and width (2) axes
desired_filters = np.transpose(rot_F, (3, 1, 2, 0)).swapaxes(1, 2)

If you prefer a more explicit, loop-based approach that directly mirrors your manual construction:

desired_filters = np.zeros_like(rot_F)
# Iterate over each width position and original filter index
for w in range(rot_F.shape[2]):
    for f in range(rot_F.shape[0]):
        # Extract the slice, transpose it, and assign to the target position
        desired_filters[w, :, :, f] = rot_F[f, :, w, :].T

Verification

Let's print the result to confirm it matches your target output:

print(desired_filters)

This will output exactly what you're looking for:

[[[[ 0  0]
   [ 2  3]]
  [[-1 -1]
   [ 1  0]]]
 [[[-1 -1]
   [-1 -1]]
  [[ 0  2]
   [ 0  1]]]]

Explanation

Let's break down the logic:

  1. Slice Extraction: For each original filter f and width position w, we grab rot_F[f, :, w, :]—a 2D array of shape (height, depth) holding values from that filter, at that width, across all depths.
  2. Transpose: We transpose this slice to swap height and depth axes, turning it into (depth, height). This aligns the values to match the structure you defined in desired_filters.
  3. Reassignment: We place this transposed slice into desired_filters[w, :, :, f], where the original width index w becomes the new filter index, and the original filter index f becomes the new depth index. This fulfills your requirement of stacking depth-dimension arrays along their own depth axis while preserving the overall array shape.

The vectorized version avoids loops for better performance with larger arrays, while the loop-based approach makes the transformation logic more explicit.

内容的提问来源于stack exchange,提问作者ClownInTheMoon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:36:05