如何向Torch7 Tensor添加切片?及无循环高效合并指定维度Tensor
Hey there! Let's break down your Torch7 questions with practical, loop-free solutions:
1. Merging Tensors A and B into C
To combine your two (1, 2048, 1024) tensors into a single (2, 2048, 1024) tensor without any for loops, use Torch's built-in torch.cat() function. This optimized function handles tensor concatenation along a specified dimension, no manual iteration needed.
Here's the straightforward code:
-- Assuming A and B are your input tensors with shape (1, 2048, 1024) local C = torch.cat({A, B}, 1)
The second argument 1 tells torch.cat() to concatenate along the first dimension (Torch uses 1-based indexing for dimensions). This stacks A and B vertically along the first axis, resulting in exactly the shape you need for C.
2. Adding Slices to a Torch7 Tensor
Adding slices (sub-tensors) can be done efficiently with torch.cat() or in-place resizing + assignment—both methods skip for loops. Here are common use cases:
Adding a slice to the end
If you want to append a new slice (e.g., a tensor D with shape (1, 2048, 1024)) to an existing tensor X (shape (2, 2048, 1024)):
local X_updated = torch.cat({X, D}, 1) -- X_updated now has shape (3, 2048, 1024)
Inserting a slice in the middle
To insert a slice between existing slices, split the original tensor into segments, then concatenate all parts together:
-- Split X into two parts: the first slice and the rest local first_part = X:narrow(1, 1, 1) -- Takes 1 element starting at index 1 of dimension 1 local remaining_part = X:narrow(1, 2, X:size(1)-1) -- Insert D between the two parts local X_inserted = torch.cat({first_part, D, remaining_part}, 1)
Resizing and assigning directly (in-place)
You can also modify the original tensor by resizing it to make space, then copying the new slice into the empty slot:
-- Resize X to fit the new slice (e.g., expand from 2 to 3 in the first dimension) X:resize(3, 2048, 1024) -- Copy the new slice D into the 3rd position X[3]:copy(D)
Note: This changes the original tensor in-place, whereas torch.cat() creates a new tensor. Pick the approach based on whether you need to preserve the original data.
内容的提问来源于stack exchange,提问作者anon

