Use torch.unsqueeze(input, dim, out=None):

>>> import torch
>>> a = torch.Tensor([1, 2, 3, 4, 5])
>>> a

 1
 2
 3
 4
 5
[torch.FloatTensor of size 5]

>>> a = a.unsqueeze(0)
>>> a

 1  2  3  4  5
[torch.FloatTensor of size 1x5]
Answer from Haha TTpro on Stack Overflow
🌐
CodingNomads
codingnomads.com › torch-reshape-methods
Torch Reshape Methods
Reshape tensors using the reshape method, which is particularly useful when you need to transform your data into a specific format, such as converting a flat tensor into an "image-like" tensor with height, width, and channel dimensions.
🌐
Codecademy
codecademy.com › docs › pytorch › tensors › .reshape()
PyTorch | tensors | .reshape() | Codecademy
September 23, 2024 - The torch.reshape() method reshapes a specified input tensor to a given shape while keeping the same data and number of elements.
🌐
DEV Community
dev.to › hyperkai › reshape-and-view-in-pytorch-40n5
reshape and view in PyTorch - DEV Community
November 5, 2024 - reshape() can be used with torch or a tensor while view() can be used with a tensor but not with torch.
🌐
PyTorch
docs.pytorch.org › reference api › torch.reshape
torch.reshape — PyTorch 2.12 documentation
January 1, 2023 - >>> a = torch.arange(4.) >>> torch.reshape(a, (2, 2)) tensor([[ 0., 1.], [ 2., 3.]]) >>> b = torch.tensor([[0, 1], [2, 3]]) >>> torch.reshape(b, (-1,)) tensor([ 0, 1, 2, 3])
🌐
MyScale
myscale.com › blog › torch-reshape-vs-torch-view-pytorch
Mastering PyTorch Reshape: A Comprehensive Guide
April 24, 2024 - When we delve into pytorch reshape, we encounter a fundamental concept: the ability to alter the dimensions of tensors without changing their underlying data. This operation proves invaluable when adapting tensor shapes to fit different neural network architectures or input requirements. One critical aspect to consider is that torch.reshape exhibits a unique behavior compared to other tensor manipulation functions.
🌐
GeeksforGeeks
geeksforgeeks.org › python › reshaping-a-tensor-in-pytorch
Reshaping a Tensor in Pytorch - GeeksforGeeks
September 1, 2021 - Example 1: Python program to reshape a 1 D tensor to a two-dimensional tensor. ... # import torch module import torch # create an 1 D etnsor with 8 elements a = torch.tensor([1, 2, 3, 4, 5, 6, 7, 8]) # display tensor shape print(a.shape) # display actual tensor print(a) # reshape tensor into 4 rows and 2 columns print(a.reshape([4, 2])) # display shape of reshaped tensor print(a.shape)
Find elsewhere
🌐
Sprintchase
sprintchase.com › home › torch.reshape(): complete guide
torch.reshape(): Complete Guide
May 12, 2025 - The above code shows that using reshape((-1,)), we flatten a 2D tensor into a 1D tensor, which can be verified by checking its sizes. You can pass a list or torch.Size as a shape to the reshape() function, and it will return a tensor with that specific shape.
🌐
APXML
apxml.com › courses › getting-started-with-pytorch › chapter-2-advanced-tensor-manipulations › reshaping-rearranging-tensors
Reshape PyTorch Tensors | View, Permute
torch.Tensor.reshape, PyTorch Developers, 2024 (PyTorch Foundation) - Official documentation for the reshape() method, explaining its flexibility in reshaping both contiguous and non-contiguous tensors, and its behavior regarding data copying.
🌐
Medium
medium.com › @amit25173 › expert-guide-to-resizing-pytorch-tensors-b88d3f34a76b
Expert Guide to Resizing PyTorch Tensors | by Amit Yadav | Medium
February 9, 2025 - You'll learn about efficient reshaping strategies that go beyond the basics, including torch.unsqueeze and torch.squeeze for modifying dimensions, and using torch.clone to retain original values without unintended side effects.
Top answer
1 of 5
284

torch.view has existed for a long time. It will return a tensor with the new shape. The returned tensor will share the underling data with the original tensor. See the documentation here.

On the other hand, it seems that torch.reshape has been introduced recently in version 0.4. According to the document, this method will

Returns a tensor with the same data and number of elements as input, but with the specified shape. When possible, the returned tensor will be a view of input. Otherwise, it will be a copy. Contiguous inputs and inputs with compatible strides can be reshaped without copying, but you should not depend on the copying vs. viewing behavior.

It means that torch.reshape may return a copy or a view of the original tensor. You can not count on that to return a view or a copy. According to the developer:

if you need a copy use clone() if you need the same storage use view(). The semantics of reshape() are that it may or may not share the storage and you don't know beforehand.

Another difference is that reshape() can operate on both contiguous and non-contiguous tensor while view() can only operate on contiguous tensor. Also see here about the meaning of contiguous.

2 of 5
111

Although both torch.view and torch.reshape are used to reshape tensors, here are the differences between them.

  1. As the name suggests, torch.view merely creates a view of the original tensor. The new tensor will always share its data with the original tensor. This means that if you change the original tensor, the reshaped tensor will change and vice versa.
>>> z = torch.zeros(3, 2)
>>> x = z.view(2, 3)
>>> z.fill_(1)
>>> x
tensor([[1., 1., 1.],
        [1., 1., 1.]])
  1. To ensure that the new tensor always shares its data with the original, torch.view imposes some contiguity constraints on the shapes of the two tensors [docs]. More often than not this is not a concern, but sometimes torch.view throws an error even if the shapes of the two tensors are compatible. Here's a famous counter-example.
>>> z = torch.zeros(3, 2)
>>> y = z.t()
>>> y.size()
torch.Size([2, 3])
>>> y.view(6)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: invalid argument 2: view size is not compatible with input tensor's
size and stride (at least one dimension spans across two contiguous subspaces).
Call .contiguous() before .view().
  1. torch.reshape doesn't impose any contiguity constraints, but also doesn't guarantee data sharing. The new tensor may be a view of the original tensor, or it may be a new tensor altogether.
>>> z = torch.zeros(3, 2)
>>> y = z.reshape(6)
>>> x = z.t().reshape(6)
>>> z.fill_(1)
tensor([[1., 1.],
        [1., 1.],
        [1., 1.]])
>>> y
tensor([1., 1., 1., 1., 1., 1.])
>>> x
tensor([0., 0., 0., 0., 0., 0.])

TL;DR:
If you just want to reshape tensors, use torch.reshape. If you're also concerned about memory usage and want to ensure that the two tensors share the same data, use torch.view.

🌐
Medium
medium.com › @sharma.rajeev186 › reshaping-tensors-made-easy-exploring-pytorchs-reshape-command-8f9070fc0c2c
Reshaping Tensors Made Easy: Exploring PyTorch’s reshape() Command | by Rajeev Sharma | Medium
May 10, 2024 - As the name suggests, the “reshape” command allows us to change the shape of a tensor. Look at the PyTorch codes snippet shown below to check the syntax of the command. # Import torch module import torch # define a tensor of random integers ...
🌐
Python Guides
pythonguides.com › pytorch-reshape-tensor
How To Reshape A Tensor In PyTorch? - Python Guides
June 18, 2025 - # Simulating a batch of 8 images (each 3x64x64) batch = torch.rand(8, 3, 64, 64) print("Original batch shape:", batch.shape) # Reshaping to combine batch and channels reshaped_batch = batch.reshape(8, 3 * 64 * 64) print("Reshaped for FC layer:", reshaped_batch.shape) # Adding a time dimension for an RNN time_aware_batch = batch.unsqueeze(1) print("Time-aware batch:", time_aware_batch.shape) # Flattening completely flat_batch = batch.view(-1) print("Flattened batch:", flat_batch.shape) # Reshaping back to original back_to_original = flat_batch.reshape(8, 3, 64, 64) print("Back to original:", back_to_original.shape)
🌐
Rdrr.io
rdrr.io › cran › torch › man › torch_reshape.html
torch_reshape: Reshape in torch: Tensors and Neural Networks with 'GPU' Acceleration
November 5, 2025 - if (torch_is_installed()) { a <- torch_arange(0, 3) torch_reshape(a, list(2, 2)) b <- torch_tensor(matrix(c(0, 1, 2, 3), ncol = 2, byrow=TRUE)) torch_reshape(b, list(-1)) }
🌐
Medium
mr-amit.medium.com › pytorch-view-vs-reshape-a-practical-guide-74bf31eec210
PyTorch view() vs reshape(): A Practical Guide | by It's Amit | Medium
March 6, 2025 - This means you can use reshape() in situations where view() would throw an error. Here’s the trade-off: that flexibility comes at a potential performance cost because making a copy of data takes extra time and memory. But sometimes, it’s worth the trade for convenience and reliability. ... import torch # Create a tensor and transpose it (non-contiguous) tensor = torch.arange(6).reshape(2, 3) non_contig = tensor.T # Transposing makes it non-contiguous print("Is the transposed tensor contiguous?", non_contig.is_contiguous()) # Use reshape on the non-contiguous tensor reshaped = non_contig.reshape(-1) # Reshape automatically handles it print("\nUsing reshape on a non-contiguous tensor:") print(reshaped)
🌐
ProjectPro
projectpro.io › recipes › reshape-torch-tensor
How to reshape a torch tensor -
September 13, 2022 - reshape = torch.reshape(data, (4,2)) print("This is the reshaped tensor:", "\n",reshape, reshape.shape)
🌐
DZone
dzone.com › articles › reshaping-pytorch-tensors
Reshaping PyTorch Tensors - DZone
April 18, 2022 - The same holds for reshaping. It’s possible to convert the existing container to a different spatial size while it preserves the total number of elements. ... import torch data = [1,2,3,4,5,6,7,8] # Original tensor of shape 2x4 tens_A = torch.tensor(data).reshape(shape=(2,4)) # Reshaped from 2x4 to 2x2x2 (preserving number of elements) tens_B = tens_A.reshape(shape=(2,2,2))