Course contentsShow
← Machine Learning and Deep Learning
Lesson 780 of 3,53819. PyTorch FundamentalsFree lesson

Reshaping Tensors: View and Reshape

Change tensor dimensions using .view(), .reshape(), .squeeze(), and .unsqueeze() while understanding memory implications.

Reshaping Tensors: View and Reshape

You'll learn how to change tensor dimensions without copying data, and when memory layout matters.

The Core Idea

Reshaping means changing how tensor elements are organized—like rearranging books on shelves without changing the books themselves. You might have a tensor of shape (12,) that you want to view as (3, 4) or (2, 6). The data stays the same; only its dimensional structure changes.

Four Key Operations

.view() — Returns a new tensor sharing the same underlying data. It's fast but requires the tensor to be contiguous in memory (elements stored in expected order).

.reshape() — More flexible than .view(). Returns a view when possible, but will copy data if necessary to satisfy the new shape. Safer but potentially slower.

.squeeze() — Removes dimensions of size 1. A tensor of shape (1, 3, 1, 4) becomes (3, 4).

.unsqueeze(dim) — Adds a dimension of size 1 at the specified position. Shape (3, 4) becomes (1, 3, 4) with unsqueeze(0).

Memory Implications

Think of memory like reading a book: .view() requires pages in order (contiguous), while .reshape() can handle scattered pages but might need to reorganize them (copy). Views are lightweight references; copies consume extra memory.

Use .view() when you know your tensor is contiguous and want guaranteed speed. Use .reshape() when you need flexibility and aren't sure about memory layout.

Key Takeaway: .view() and .reshape() reorganize tensor dimensions without changing data; .squeeze() and .unsqueeze() remove or add size-1 dimensions. Understanding memory contiguity helps you choose the right tool for efficient tensor manipulation.