Python PyTorch stack() method
Last Updated :
28 Feb, 2022
PyTorch torch.stack() method joins (concatenates) a sequence of tensors (two or more tensors) along a new dimension. It inserts new dimension and concatenates the tensors along that dimension. This method joins the tensors with the same dimensions and shape. We could also use torch.cat() to join tensors But here we discuss the torch.stack() method.
Syntax: torch.stack(tensors, dim=0)
Arguments:
- tensors: It’s a sequence of tensors of same shape and dimensions
- dim: It’s the dimension to insert. It’s an integer between 0 and the number of dimensions of input tensors.
Returns: It returns the concatenated tensor along a new dimension.
Let’s understand the torch.stack() method with the help of some Python 3 examples.
Example 1:
In the Python example below we join two one-dimensional tensors using torch.stack() method.
Python3
import torch
x = torch.tensor([1.,3.,6.,10.])
y = torch.tensor([2.,7.,9.,13.])
print("Tensor x:", x)
print("Tensor y:", y)
print("join tensors:")
t = torch.stack((x,y))
print(t)
print("join tensors dimension 0:")
t = torch.stack((x,y), dim = 0)
print(t)
print("join tensors dimension 1:")
t = torch.stack((x,y), dim = 1)
print(t)
|
Output:
Tensor x: tensor([ 1., 3., 6., 10.])
Tensor y: tensor([ 2., 7., 9., 13.])
join tensors:
tensor([[ 1., 3., 6., 10.],
[ 2., 7., 9., 13.]])
join tensors dimension 0:
tensor([[ 1., 3., 6., 10.],
[ 2., 7., 9., 13.]])
join tensors dimension 1:
tensor([[ 1., 2.],
[ 3., 7.],
[ 6., 9.],
[10., 13.]])
Explanation: In the above code tensors x and y are one-dimensional each having four elements. The final concatenated tensor is a 2D tensor. As the dimension is 1, we can stack the tensors with dimensions 0 and 1. When dim =0 the tensors are stacked increasing the number of rows. When dim =1 the tensors are transposed and stacked along the column.
Example 2:
In the Python example below we join two one-dimensional tensors using torch.stack() method.
Python3
import torch
x = torch.tensor([[1., 3., 6.], [10., 13., 20.]])
y = torch.tensor([[2., 7., 9.], [14., 21., 34.]])
print("Tensor x:\n", x)
print("Tensor y:\n", y)
print("join tensors")
t = torch.stack((x, y))
print(t)
print("join tensors in dimension 0:")
t = torch.stack((x, y), 0)
print(t)
print("join tensors in dimension 1:")
t = torch.stack((x, y), 1)
print(t)
print("join tensors in dimension 2:")
t = torch.stack((x, y), 2)
print(t)
|
Output:
Tensor x:
tensor([[ 1., 3., 6.],
[10., 13., 20.]])
Tensor y:
tensor([[ 2., 7., 9.],
[14., 21., 34.]])
join tensors
tensor([[[ 1., 3., 6.],
[10., 13., 20.]],
[[ 2., 7., 9.],
[14., 21., 34.]]])
join tensors in dimension 0:
tensor([[[ 1., 3., 6.],
[10., 13., 20.]],
[[ 2., 7., 9.],
[14., 21., 34.]]])
join tensors in dimension 1:
tensor([[[ 1., 3., 6.],
[ 2., 7., 9.]],
[[10., 13., 20.],
[14., 21., 34.]]])
join tensors in dimension 2:
tensor([[[ 1., 2.],
[ 3., 7.],
[ 6., 9.]],
[[10., 14.],
[13., 21.],
[20., 34.]]])
Explanation: In the above code, x and y are two-dimensional tensors. Notice that the final tensor is a 3-D tensor. As the dimension of each input tensor is 2, we can stack the tensors with dimensions 0 and 2. See the differences among the final output tensors with dim = 0, 1, and 2.
Example 3:
In this example, we join more than two tensors. We can join any number of tensors.
Python3
import torch
x = torch.tensor([1., 3., 6., 10.])
y = torch.tensor([2., 7., 9., 13.])
z = torch.tensor([4., 5., 8., 11.])
print("Tensor x:", x)
print("Tensor y:", y)
print("Tensor z:", z)
print("join tensors:")
t = torch.stack((x, y, z))
print(t)
print("join tensors dimension 0:")
t = torch.stack((x, y, z), dim=0)
print(t)
print("join tensors dimension 1:")
t = torch.stack((x, y, z), dim=1)
print(t)
|
Output:
Tensor x: tensor([ 1., 3., 6., 10.])
Tensor y: tensor([ 2., 7., 9., 13.])
Tensor z: tensor([ 4., 5., 8., 11.])
join tensors:
tensor([[ 1., 3., 6., 10.],
[ 2., 7., 9., 13.],
[ 4., 5., 8., 11.]])
join tensors dimension 0:
tensor([[ 1., 3., 6., 10.],
[ 2., 7., 9., 13.],
[ 4., 5., 8., 11.]])
join tensors dimension 1:
tensor([[ 1., 2., 4.],
[ 3., 7., 5.],
[ 6., 9., 8.],
[10., 13., 11.]])
Example 4: Demonstrating Errors
In the example below we show errors when the input tensors are not of the same shape.
Python3
import torch
x = torch.tensor([1., 3., 6., 10.])
y = torch.tensor([2., 7., 9.])
print("Tensor x:", x)
print("Tensor y:", y)
print("join tensors:")
t = torch.stack((x, y))
print(t)
print("join tensors dimension 0:")
t = torch.stack((x, y), dim=0)
print(t)
print("join tensors dimension 1:")
t = torch.stack((x, y), dim=1)
print(t)
|
Output:
Shape of x: torch.Size([4])
Shape of y: torch.Size([3])
RuntimeError: stack expects each tensor to be equal size, but got [4] at entry 0 and [3] at entry 1
Notice that the shape of the two tensors is not the same. It throws a runtime error. In the same way, when the dimension of tensors is not the same it throws a runtime error. Try for yourself for tensors with different dimensions and see how the output is.
Similar Reads
Python PyTorch stack() method
PyTorch torch.stack() method joins (concatenates) a sequence of tensors (two or more tensors) along a new dimension. It inserts new dimension and concatenates the tensors along that dimension. This method joins the tensors with the same dimensions and shape. We could also use torch.cat() to join ten
5 min read
Python | PyTorch sin() method
PyTorch is an open-source machine learning library developed by Facebook. It is used for deep neural network and natural language processing purposes. The function torch.sin() provides support for the sine function in PyTorch. It expects the input in radian form and the output is in the range [-1, 1
2 min read
Python | PyTorch sinh() method
PyTorch is an open-source machine learning library developed by Facebook. It is used for deep neural network and natural language processing purposes. The function torch.sinh() provides support for the hyperbolic sine function in PyTorch. It expects the input in radian form. The input type is tensor
2 min read
Python PyTorch zeros() method
PyTorch is an open-source machine learning library developed by Facebook. It is used for deep neural network and natural language processing purposes. The function torch.zeros() returns a tensor filled with the scalar value 0, with the shape defined by the variable argument size. Syntax: torch.zeros
1 min read
Python - PyTorch is_storage() method
PyTorch torch.is_storage() method returns True if obj is a PyTorch storage object. Syntax: torch.is_storage(object) Arguments object: This is input tensor to be tested. Return: It returns either True or False. Let's see this concept with the help of few examples: Example 1: # Importing the PyTorch l
1 min read
Python - PyTorch is_storage() method
PyTorch torch.is_storage() method returns True if obj is a PyTorch storage object. Syntax: torch.is_storage(object) Arguments object: This is input tensor to be tested. Return: It returns either True or False. Let's see this concept with the help of few examples: Example 1: # Importing the PyTorch l
1 min read
Python - PyTorch add() method
PyTorch torch.add() method adds a constant value to each element of the input tensor and returns a new modified tensor. Syntax: torch.add(inp, c, out=None) Arguments inp: This is input tensor. c: The value that is to be added to every element of tensor. out: This is optional parameter and it is the
1 min read
Python - PyTorch exp() method
PyTorch torch.exp() method returns a new tensor after getting the exponent of the elements of the input tensor. Syntax: torch.exp(input, out=None) Arguments input: This is input tensor. out: The output tensor. Return: It returns a Tensor. Let's see this concept with the help of few examples: Example
1 min read
Python - PyTorch log() method
PyTorch torch.log() method gives a new tensor having the natural logarithm of the elements of input tensor. Syntax: torch.log(input, out=None) Arguments input: This is input tensor. out: The output tensor. Return: It returns a Tensor. Let's see this concept with the help of few examples: Example 1:
1 min read
Python - PyTorch div() method
PyTorch torch.div() method divides every element of the input with a constant and returns a new modified tensor. Syntax: torch.div(inp, other, out=None) Arguments inp: This is input tensor. other: This is a number to be divided to each element of input inp. out: The output tensor. Return: It returns
1 min read
Python Pytorch full() method
PyTorch is an open-source machine learning library developed by Facebook. It is used for deep neural network and natural language processing purposes. The function torch.full() returns a tensor of size size filled with fill_value. Syntax: torch.ones(size, fill_value, out=None) Parameters: size: a se
1 min read
Python - PyTorch ceil() method
PyTorch torch.ceil() method returns a new tensor having the ceil value of the elements of input, Which is the smallest integer larger than or equal to each element. Syntax: torch.ceil(inp, out=None) Arguments inp: This is input tensor. out: The output tensor. Return: It returns a Tensor. Let's see t
1 min read
Python PyTorch log2() method
PyTorch log2() method computes the logarithm to the base 2 of the elements of an input tensor. It computes the logarithm values element-wise. It takes a tensor as an input and returns a new tensor with computed logarithm values. The elements of the input tensor must be between zero and the positive
4 min read
Python - PyTorch floor() method
PyTorch torch.floor() method returns a new tensor which is floor of the elements of input, the largest integer less than or equal to each element. Syntax: torch.floor(input, out=None) Arguments input: This is input tensor. out: The output tensor. Return: It returns a Tensor. Let's see this concept w
1 min read
Python Pytorch empty() method
PyTorch is an open-source machine learning library developed by Facebook. It is used for deep neural network and natural language processing purposes. The function torch.empty() returns a tensor filled with uninitialized data. The shape of the tensor is defined by the variable argument size. Syntax:
1 min read
Python - PyTorch numel() method
PyTorch torch.numel() method returns the total number of elements in the input tensor. Syntax: torch.numel(input) Arguments input: This is input tensor. Return: It returns the length of the input tensor. Let's see this concept with the help of few examples: Example 1: # Importing the PyTorch library
1 min read
Python - PyTorch clamp() method
PyTorch torch.clamp() method clamps all the input elements into the range [ min, max ] and return a resulting tensor. Syntax: torch.clamp(inp, min, max, out=None) Arguments inp: This is input tensor. min: This is a number and specifies the lower-bound of the range to which input to be clamped. max:
2 min read
How Does the "View" Method Work in Python PyTorch?
PyTorch, a popular open-source machine learning library, is known for its dynamic computational graphs and intuitive interface, particularly when it comes to tensor operations. One of the most commonly used tensor operations in PyTorch is the .view() function. If you're working with PyTorch, underst
5 min read
turtle.up() method in Python
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support. turtle.up() The turtle.up() method is used to pull the pen up from the screen. It g
1 min read
Stack in Python
A stack is a linear data structure that stores items in a Last-In/First-Out (LIFO) or First-In/Last-Out (FILO) manner. In stack, a new element is added at one end and an element is removed from that end only. The insert and delete operations are often called push and pop. The functions associated wi
8 min read