如何在TensorFlow中按列切割2D张量并转换为3D张量?
Reshaping 2D Tensor to 3D as Required
Hey there! Let's break down how to transform your [10,12] 2D tensor into the [3,10,4] 3D tensor you need, and even get the flattened version matching your example.
Step 1: Understand the Split Logic
Your original tensor has 12 columns, and you want to split it vertically (by columns) into 3 chunks of 4 columns each:
- First chunk: Columns 0-3 (before the 3rd column, 0-indexed)
- Second chunk: Columns 4-7 (after 3rd column, before 7th)
- Third chunk: Columns 8-11 (after 7th column)
Each chunk will be a [10,4] sub-matrix, which we'll then stack into a 3D tensor with batch_size=3 as the first dimension.
Step 2: Implementation with NumPy
Since you provided a NumPy array example, here's how to do it with NumPy:
import numpy as np # Define your original 2D tensor K K = np.array([[1, 9, 5, 9, 9, 2, 0, 9, 1, 9, 0, 6], [0, 4, 8, 4, 3, 3, 8, 8, 7, 0, 3, 8], [7, 7, 1, 8, 4, 7, 0, 4, 9, 0, 6, 4], [2, 4, 6, 3, 3, 7, 8, 5, 0, 8, 5, 4], [7, 4, 1, 3, 3, 9, 2, 5, 2, 3, 5, 7], [2, 7, 1, 6, 5, 0, 0, 3, 1, 9, 9, 6], [6, 7, 8, 8, 7, 0, 8, 6, 8, 9, 8, 3], [6, 1, 7, 4, 9, 2, 0, 8, 2, 7, 8, 4], [4, 1, 7, 6, 9, 4, 1, 5, 9, 7, 1, 3], [5, 7, 3, 6, 6, 7, 9, 1, 9, 6, 0, 3]]) # Split into three [10,4] sub-matrices chunk1 = K[:, :4] # Columns 0-3 chunk2 = K[:, 4:8] # Columns 4-7 chunk3 = K[:, 8:] # Columns 8-11 # Stack the chunks along axis=0 to get [3,10,4] 3D tensor K_new = np.stack([chunk1, chunk2, chunk3], axis=0) # Optional: Flatten to get the 1D array matching your example K_new_flat = K_new.flatten() print(K_new_flat)
Step 3: Verify the Results
K_new.shapewill return(3, 10, 4), which matches your requirement ofbatch_size=3andsequence_length=4.- The flattened
K_new_flatwill exactly match the 1D array you provided, since NumPy'sflatten()uses row-major (C-style) order by default.
Alternative: PyTorch Implementation
If you're working with PyTorch tensors instead, the logic is almost identical:
import torch # Define your tensor as a PyTorch tensor K = torch.tensor([[1, 9, 5, 9, 9, 2, 0, 9, 1, 9, 0, 6], [0, 4, 8, 4, 3, 3, 8, 8, 7, 0, 3, 8], [7, 7, 1, 8, 4, 7, 0, 4, 9, 0, 6, 4], [2, 4, 6, 3, 3, 7, 8, 5, 0, 8, 5, 4], [7, 4, 1, 3, 3, 9, 2, 5, 2, 3, 5, 7], [2, 7, 1, 6, 5, 0, 0, 3, 1, 9, 9, 6], [6, 7, 8, 8, 7, 0, 8, 6, 8, 9, 8, 3], [6, 1, 7, 4, 9, 2, 0, 8, 2, 7, 8, 4], [4, 1, 7, 6, 9, 4, 1, 5, 9, 7, 1, 3], [5, 7, 3, 6, 6, 7, 9, 1, 9, 6, 0, 3]]) # Split into chunks chunk1 = K[:, :4] chunk2 = K[:, 4:8] chunk3 = K[:, 8:] # Stack into 3D tensor K_new = torch.stack([chunk1, chunk2, chunk3], dim=0) # Flatten to 1D K_new_flat = K_new.flatten() print(K_new_flat)
内容的提问来源于stack exchange,提问作者Sarath R Nair
相关产品推荐
相关产品推荐

