view() reshapes the tensor without copying memory, similar to numpy's reshape().

Given a tensor a with 16 elements:

import torch
a = torch.range(1, 16)

To reshape this tensor to make it a 4 x 4 tensor, use:

a = a.view(4, 4)

Now a will be a 4 x 4 tensor. Note that after the reshape the total number of elements need to remain the same. Reshaping the tensor a to a 3 x 5 tensor would not be appropriate.

What is the meaning of parameter -1?

If there is any situation that you don't know how many rows you want but are sure of the number of columns, then you can specify this with a -1. (Note that you can extend this to tensors with more dimensions. Only one of the axis value can be -1). This is a way of telling the library: "give me a tensor that has these many columns and you compute the appropriate number of rows that is necessary to make this happen".

This can be seen in this model definition code. After the line x = self.pool(F.relu(self.conv2(x))) in the forward function, you will have a 16 depth feature map. You have to flatten this to give it to the fully connected layer. So you tell PyTorch to reshape the tensor you obtained to have specific number of columns and tell it to decide the number of rows by itself.

Answer from Kashyap on Stack Overflow
Top answer
1 of 9
465

view() reshapes the tensor without copying memory, similar to numpy's reshape().

Given a tensor a with 16 elements:

import torch
a = torch.range(1, 16)

To reshape this tensor to make it a 4 x 4 tensor, use:

a = a.view(4, 4)

Now a will be a 4 x 4 tensor. Note that after the reshape the total number of elements need to remain the same. Reshaping the tensor a to a 3 x 5 tensor would not be appropriate.

What is the meaning of parameter -1?

If there is any situation that you don't know how many rows you want but are sure of the number of columns, then you can specify this with a -1. (Note that you can extend this to tensors with more dimensions. Only one of the axis value can be -1). This is a way of telling the library: "give me a tensor that has these many columns and you compute the appropriate number of rows that is necessary to make this happen".

This can be seen in this model definition code. After the line x = self.pool(F.relu(self.conv2(x))) in the forward function, you will have a 16 depth feature map. You have to flatten this to give it to the fully connected layer. So you tell PyTorch to reshape the tensor you obtained to have specific number of columns and tell it to decide the number of rows by itself.

2 of 9
92

view() reshapes a tensor by 'stretching' or 'squeezing' its elements into the shape you specify:


How does view() work?

First let's look at what a tensor is under the hood:

Tensor and its underlying storage e.g. the right-hand tensor (shape (3,2)) can be computed from the left-hand one with t2 = t1.view(3,2)

Here you see PyTorch makes a tensor by converting an underlying block of contiguous memory into a matrix-like object by adding a shape and stride attribute:

  • shape states how long each dimension is
  • stride states how many steps you need to take in memory til you reach the next element in each dimension

view(dim1,dim2,...) returns a view of the same underlying information, but reshaped to a tensor of shape dim1 x dim2 x ... (by modifying the shape and stride attributes).

Note this implicitly assumes that the new and old dimensions have the same product (i.e. the old and new tensor have the same volume).


PyTorch -1

-1 is a PyTorch alias for "infer this dimension given the others have all been specified" (i.e. the quotient of the original product by the new product). It is a convention taken from numpy.reshape().

Hence t1.view(3,2) in our example would be equivalent to t1.view(3,-1) or t1.view(-1,2).

🌐
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 - If the tensor isn’t contiguous — perhaps due to slicing, transposing, or other operations — view() will throw an error. ... You need to reshape a tensor quickly. The tensor is already contiguous in memory (or you’re confident about its contiguity). ... import torch # Create a contiguous tensor tensor = torch.arange(6) # Reshape the tensor using view() reshaped = tensor.view(2, 3) print("Original tensor:") print(tensor) print("\nReshaped tensor using view():") print(reshaped)
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-does-the-view-method-work-in-python-pytorch
How Does the "View" Method Work in Python PyTorch? - GeeksforGeeks
July 23, 2025 - Original Tensor: tensor([[1, 2, 3], [4, 5, 6]]) torch.Size([2, 3]) Reshaped Tensor: tensor([1, 2, 3, 4, 5, 6]) torch.Size([6]) In this example, .view(6) reshapes the 2x3 tensor into a 1D tensor with 6 elements.
Find elsewhere
Top answer
1 of 6
71

Yes, it does behave like -1 in numpy.reshape(), i.e. the actual value for this dimension will be inferred so that the number of elements in the view matches the original number of elements.

For instance:

import torch

x = torch.arange(6)

print(x.view(3, -1))      # inferred size will be 2 as 6 / 3 = 2
# tensor([[ 0.,  1.],
#         [ 2.,  3.],
#         [ 4.,  5.]])

print(x.view(-1, 6))      # inferred size will be 1 as 6 / 6 = 1
# tensor([[ 0.,  1.,  2.,  3.,  4.,  5.]])

print(x.view(1, -1, 2))   # inferred size will be 3 as 6 / (1 * 2) = 3
# tensor([[[ 0.,  1.],
#          [ 2.,  3.],
#          [ 4.,  5.]]])

# print(x.view(-1, 5))    # throw error as there's no int N so that 5 * N = 6
# RuntimeError: invalid argument 2: size '[-1 x 5]' is invalid for input with 6 elements

print(x.view(-1, -1, 3))  # throw error as only one dimension can be inferred
# RuntimeError: invalid argument 1: only one dimension can be inferred
2 of 6
8

I love the answer that Benjamin gives https://stackoverflow.com/a/50793899/1601580

Yes, it does behave like -1 in numpy.reshape(), i.e. the actual value for this dimension will be inferred so that the number of elements in the view matches the original number of elements.

but I think the weird case edge case that might not be intuitive for you (or at least it wasn't for me) is when calling it with a single -1 i.e. tensor.view(-1). My guess is that it works exactly the same way as always except that since you are giving a single number to view it assumes you want a single dimension. If you had tensor.view(-1, Dnew) it would produce a tensor of two dimensions/indices but would make sure the first dimension to be of the correct size according to the original dimension of the tensor. Say you had (D1, D2) you had Dnew=D1*D2 then the new dimension would be 1.

For real examples with code you can run:

import torch

x = torch.randn(1, 5)
x = x.view(-1)
print(x.size())

x = torch.randn(2, 4)
x = x.view(-1, 8)
print(x.size())

x = torch.randn(2, 4)
x = x.view(-1)
print(x.size())

x = torch.randn(2, 4, 3)
x = x.view(-1)
print(x.size())

output:

torch.Size([5])
torch.Size([1, 8])
torch.Size([8])
torch.Size([24])

History/Context

I feel a good example (common case early on in pytorch before the flatten layer was official added was this common code):

class Flatten(nn.Module):
    def forward(self, input):
        # input.size(0) usually denotes the batch size so we want to keep that
        return input.view(input.size(0), -1)

for sequential. In this view x.view(-1) is a weird flatten layer but missing the squeeze (i.e. adding a dimension of 1). Adding this squeeze or removing it is usually important for the code to actually run.


Example2

if you are wondering what x.view(-1) does it flattens the vector. Why? Because it has to construct a new view with only 1 dimension and infer the dimension -- so it flattens it. In addition it seems this operation avoids the very nasty bugs .resize() brings since the order of the elements seems to be respected. Fyi, pytorch now has this op for flattening: https://pytorch.org/docs/stable/generated/torch.flatten.html

#%%
"""
Summary: view(-1, ...) keeps the remaining dimensions as give and infers the -1 location such that it respects the
original view of the tensor. If it's only .view(-1) then it only has 1 dimension given all the previous ones so it ends
up flattening the tensor.

ref: my answer https://stackoverflow.com/a/66500823/1601580
"""
import torch

x = torch.arange(6)
print(x)

x = x.reshape(3, 2)
print(x)

print(x.view(-1))

output

tensor([0, 1, 2, 3, 4, 5])
tensor([[0, 1],
        [2, 3],
        [4, 5]])
tensor([0, 1, 2, 3, 4, 5])

see the original tensor is returned!

🌐
YouTube
youtube.com › the python oracle
What does .view() do in PyTorch? - YouTube
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn--Music by Eric Matyashttps://www.soundimage.orgTrack title: Forest o
Published: February 16, 2023
Views: 65
🌐
GitHub
github.com › pytorch › pytorch › issues › 2013
Documentation for how pytorch tensor.view() rearranges dimensions? · Issue #2013 · pytorch/pytorch
July 8, 2017 - ... @mhgump torch.view only changes the sizes of the tensor, while the underlying content remains the same, pretty much like numpy reshape, so the order is the same as the order in the underlying tensor.
🌐
MyScale
myscale.com › blog › torch-reshape-vs-torch-view-pytorch
Mastering PyTorch Reshape: A Comprehensive Guide
April 24, 2024 - While torch.view offers unparalleled flexibility in reshaping tensors, it comes with limitations. Notably, torch.view operates solely on contiguous tensors, restricting its applicability in scenarios where non-contiguous memory layouts are prevalent.
🌐
PyTorch Forums
discuss.pytorch.org › uncategorized
What does .view(-1) do? - Uncategorized - PyTorch Forums
January 23, 2021 - I see this line of code lab=lab.view(-1) I am wondering what this code does? I put a breakpoint on it, and as far as I can see the contents of lab are the same both before and after I execute the code. So does this cod…
🌐
Medium
medium.com › @sfarrukhm › demystifying-pytorch-tensors-the-complete-guide-to-views-memory-layout-and-gradient-tracking-865197664ee4
Demystifying PyTorch Tensors: The Complete Guide to Views, Memory Layout, and Gradient Tracking | by Muhammad Farrukh Mehmood | Medium
September 25, 2025 - Every operation either reinterprets the memory (view), rearranges it (permute/transpose), or copies it (clone/contiguous). Once you internalize this mental model, the PyTorch API stops feeling like a collection of arbitrary rules and starts feeling inevitable. You’ll find yourself naturally reaching for the right method because you understand what each one is actually doing at the memory level. Before we wrap up, try predicting what this code will output: x = torch.arange(12).reshape(3,4) y = x.t() print("x stride:", x.stride(), "contiguous?", x.is_contiguous()) print("y stride:", y.stride(), "contiguous?", y.is_contiguous())
🌐
Codecademy
codecademy.com › docs › pytorch › tensors › .view()
PyTorch | tensors | .view() | Codecademy
November 9, 2024 - The .view() method in PyTorch reshapes a tensor without altering its underlying data, provided the total number of elements remains the same.
🌐
CSDN
blog.csdn.net › internetear › article › details › 160307935
2026年4月19日 AI前沿资讯速览_ollama 0.20.8 版本-CSDN博客
April 19, 2026 - import torch import torch.nn.functional ... d_model * 4), torch.nn.GELU(), torch.nn.Linear(d_model * 4, d_model) ) for _ in range(n_experts) ]) def forward(self, x): # x: [batch, seq_len, d_model] batch_size, seq_len, d_model = x.shape x_flat = x.view(-1, d_model) # [batch*seq_len, d_model] ...
🌐
Codefinity
codefinity.com › courses › v2 › 1dd2b0f6-6ec0-40e6-a570-ed0ac2209666 › 8a329f24-2e0c-4e15-bc32-802e817f6856 › 6f054f4c-f699-45fb-a1d4-0d252768f49c
Codefinity: Courses with certificates | Online Learning Platform
123 import torch tensor = torch.tensor([[1, 2, 3], [4, 5, 6]]) print(f"Tensor shape: {tensor.shape}") ... The .view() method creates a new view of the tensor with the specified shape without modifying the original tensor.
🌐
DEV Community
dev.to › hyperkai › reshape-and-view-in-pytorch-40n5
reshape and view in PyTorch - DEV Community
November 5, 2024 - reshape() may create the copy of a tensor, taking more memory while view() doesn't create the copy of a tensor so view() can be ligher and faster than reshape(). import torch my_tensor = torch.tensor([[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]]) torch.reshape(input=my_tensor, shape=(12,)) torch.reshape(input=my_tensor, shape=(-1,)) my_tensor.reshape(shape=(12,)) my_tensor.reshape(shape=(-1,)) my_tensor.reshape(12) my_tensor.reshape(-1) my_tensor.view((12,)) my_tensor.view((-1,)) my_tensor.view(12) my_tensor.view(-1) # tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) torch.reshape(input=my_tens