创建2D掩码数组并应用于784×49数组的技术实现咨询
Implementing the 784×49 Array with 4×4 Region Mapping
Got it, let's walk through how to build this 784×49 array exactly as you described. First, let's recap the key details to make sure we're aligned:
- All row and column numbering starts at 1 (critical for matching your specified non-zero positions)
- The 784 rows correspond to a flattened 28×28 image: row number
rin the array maps to the image position(x, y)wherex = ((r-1)//28) + 1andy = ((r-1)%28) + 1 - The 49 columns each represent a non-overlapping 4×4 region in the 28×28 image (since 28/4 = 7, this forms a 7×7 grid of 4×4 blocks, totaling 49 blocks)
Step 1: Map Columns to 4×4 Image Regions
Each column c (1-49) maps to a specific 4×4 block in the 28×28 image. To find the block's position:
- Calculate the block's row and column in the 7×7 grid:
block_row = ((c-1) // 7) + 1(groups columns into rows of 7)block_col = ((c-1) % 7) + 1(left-to-right position within the grid row)
- Convert that grid position to the image's 1-based row/column ranges:
- Image rows for the block:
(block_row-1)*4 + 1toblock_row*4 - Image columns for the block:
(block_col-1)*4 + 1toblock_col*4
- Image rows for the block:
Step 2: Generate the Array
We'll initialize a zero-filled array, then set the corresponding rows to non-zero for each column. Here's a Python implementation using NumPy (efficient for array operations):
import numpy as np # Initialize 784x49 array with all zeros (use your desired dtype if needed) result_array = np.zeros((784, 49), dtype=int) # Iterate over each column (1-based to match your specs) for col in range(1, 50): # Get the 4x4 block's grid position block_row = ((col - 1) // 7) + 1 block_col = ((col - 1) % 7) + 1 # Define the image's row/column range for this block (1-based) img_row_start = (block_row - 1) * 4 + 1 img_row_end = block_row * 4 img_col_start = (block_col - 1) * 4 + 1 img_col_end = block_col * 4 # Convert each (image row, image column) to the array's row number for img_row in range(img_row_start, img_row_end + 1): for img_col in range(img_col_start, img_col_end + 1): array_row = (img_row - 1) * 28 + img_col # Set the element to non-zero (we'll use 1 here; adjust as needed) result_array[array_row - 1, col - 1] = 1 # NumPy uses 0-based indexing
Verification
Let's check this matches your examples:
- For Column 1:
block_row=1,block_col=1→ image rows 1-4, columns 1-4. The corresponding array rows are 1-4, 29-32, 57-60, 85-88 (exactly your specified non-zero rows). - For Column 2:
block_row=1,block_col=2→ image rows 1-4, columns 5-8. The corresponding array rows are 5-8, 33-36, 61-64, 89-92 (also matches your specs).
Notes
- If you don't want to use NumPy, you can implement this with nested lists, but NumPy is far more efficient for large arrays like this.
- Replace the
1with any non-zero value you need (e.g., weights, binary flags).
内容的提问来源于stack exchange,提问作者user1371666
相关产品推荐
相关产品推荐

