Pytorch Torch Vstack
## PyTorch torch.vstack
`torch.vstack` is a PyTorch function used to stack tensors vertically (row-wise). It is equivalent to concatenating tensors along the first dimension (dim=0) after 1D tensors have been reshaped to 2D.
---
### Syntax
```python
torch.vstack(tensors, *, out=None)
```
### Parameters
| Parameter | Type | Description |
| :--- | :--- | :--- |
| `tensors` | Sequence of Tensors | A sequence (list or tuple) of tensors to stack. The tensors must have the same shape except in the first dimension. |
| `out` | Tensor, optional | The output tensor. |
### Return Value
* Returns a new tensor formed by stacking the input tensors vertically.
---
## Code Examples
The following examples demonstrate how to use `torch.vstack` with 1D and 2D tensors.
```python
import torch
# 1. Vertical stacking of 1D tensors
x1 = torch.tensor([1, 2, 3])
x2 = torch.tensor([4, 5, 6])
result_1d = torch.vstack([x1, x2])
print("--- 1D Tensor Vertical Stacking ---")
print(f"x1: {x1}")
print(f"x2: {x2}")
print(f"Result:\n{result_1d}\n")
# 2. Vertical stacking of 2D tensors
y1 = torch.tensor([[1, 2], [3, 4]])
y2 = torch.tensor([[5, 6], [7, 8]])
result_2d = torch.vstack([y1, y2])
print("--- 2D Tensor Vertical Stacking ---")
print(f"y1:\n{y1}")
print(f"y2:\n{y2}")
print(f"Result:\n{result_2d}\n")
# 3. Stacking multiple 1D tensors
z1 = torch.tensor([1, 2, 3])
z2 = torch.tensor([4, 5, 6])
z3 = torch.tensor([7, 8, 9])
result_multi = torch.vstack([z1, z2, z3])
print("--- Stacking Multiple 1D Tensors ---")
print(f"Result:\n{result_multi}")
```
### Output
```text
--- 1D Tensor Vertical Stacking ---
x1: tensor([1, 2, 3])
x2: tensor([4, 5, 6])
Result:
tensor([[1, 2, 3],
[4, 5, 6]])
--- 2D Tensor Vertical Stacking ---
y1:
tensor([[1, 2],
[3, 4]])
y2:
tensor([[5, 6],
[7, 8]])
Result:
tensor([[1, 2],
[3, 4],
[5, 6],
[7, 8]])
--- Stacking Multiple 1D Tensors ---
Result:
tensor([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
```
---
## Key Considerations
1. **Dimensionality Behavior**:
* For **1D tensors** of shape `(N,)`, `torch.vstack` treats them as 2D row vectors of shape `(1, N)` before stacking them along the first dimension. The resulting tensor will be 2D.
* For **2D or higher-dimensional tensors**, `torch.vstack` concatenates them directly along the first axis (`dim=0`).
2. **Shape Compatibility**:
* Except for the first dimension, all other dimensions of the input tensors must match exactly. For example, you cannot vertically stack a tensor of shape `(2, 3)` with a tensor of shape `(2, 4)`.
3. **Alias**:
* `torch.vstack` is fully equivalent to `torch.row_stack`. You can use either depending on your coding style preferences.
YouTip