PyTorch torch.row_stack Function


Pytorch torch 参考手册Pytorch torch Reference Manual

torch.row_stackIt is a function in PyTorch used to stack tensors by rows, equivalent to vertical stacking.

Function Definition

torch.row_stack(tensors, *, out=None)

Usage Example

Example

import torch

# Row stacking of 1D tensors
x1 = torch.tensor([1, 2, 3])
x2 = torch.tensor([4, 5, 6])
result = torch.row_stack([x1, x2])
print("1D tensor row stacking:")
print(f"  x1: {x1}")
print(f"  x2: {x2}")
print(f"  row_stack:n{result}")

# Row stacking of 2D tensors
y1 = torch.tensor([[1, 2, 3]])
y2 = torch.tensor([[4, 5, 6]])
result = torch.row_stack([y1, y2])
print("\n2D tensor row stacking:")
print(f"  y1:n{y1}")
print(f"  y2:n{y2}")
print(f"  row_stack:n{result}")

# Equivalent to vstack
z1 = torch.tensor([1, 2, 3])
z2 = torch.tensor([4, 5, 6])
result_vstack = torch.vstack([z1, z2])
result_row_stack = torch.row_stack([z1, z2])
print("\nrow_stack is equivalent to vstack:")
print(f"  vstack: {result_vstack.tolist()}")
print(f"  row_stack: {result_row_stack.tolist()}")

The output result is:

一维张量行堆叠:
  x1: tensor([1, 2, 3])
  x2: tensor([4, 5, 6])
  row_stack:
tensor([[1, 2, 3],
        [4, 5, 6]])

二维张量行堆叠:
  y1:
tensor([[1, 2, 3]])
  y2:
tensor([[4, 5, 6]])
  row_stack:
tensor([[1, 2, 3],
        [4, 5, 6]])

row_stack 等价于 vstack:
  vstack: [[1, 2, 3], [4, 5, 6]]
  row_stack: [[1, 2, 3], [4, 5, 6]]

Pytorch torch 参考手册Pytorch torch Reference Manual

Other Extensions