Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprende Working with Shapes | PyTorch Basics
Neural Networks with PyTorch
course content

Contenido del Curso

Neural Networks with PyTorch

Neural Networks with PyTorch

1. PyTorch Basics
2. Preparing for Neural Networks
3. Neural Networks

book
Working with Shapes

Similarly to NumPy arrays, a tensor's shape determines its dimensions. You can inspect a tensor's shape using the .shape attribute:

123
import torch tensor = torch.tensor([[1, 2, 3], [4, 5, 6]]) print(f"Tensor shape: {tensor.shape}")
copy

Reshaping Tensors with view

The .view() method creates a new view of the tensor with the specified shape without modifying the original tensor. The total number of elements must remain the same.

1234567
import torch tensor = torch.arange(12) # Reshape a tensor to 4x3 reshaped_tensor = tensor.view(4, 3) print(f"Reshaped tensor: {reshaped_tensor}") # Original tensor remains unchanged print(f"Original tensor: {tensor}")
copy

Reshaping Tensors with reshape

The .reshape() method is similar to .view() but can handle cases where the tensor is not stored contiguously in memory. It also doesn't modify the original tensor.

12345
import torch tensor = torch.arange(12) # Reshape a tensor to 6x2 reshaped_tensor = tensor.reshape(6, 2) print(f"Reshaped tensor: {reshaped_tensor}")
copy

Using Negative Dimensions

You can use -1 in the shape to let PyTorch infer the size of one dimension based on the total number of elements.

1234
import torch # Automatically infer the second dimension inferred_tensor = tensor.view(2, -1) print("Inferred Tensor:", inferred_tensor)
copy

Understanding Tensor Views

A view of a tensor shares the same data with the original tensor. Changes to the view affect the original tensor and vice versa.

1234567
import torch tensor = torch.arange(12) view_tensor = tensor.view(2, 6) view_tensor[0, 0] = 999 # Changes in the view are reflected in the original tensor print("View Tensor:", view_tensor) print("Original Tensor:", tensor)
copy

Changing Dimensions

  • unsqueeze(dim) adds a new dimension at the specified position;
  • squeeze(dim) removes dimensions of size 1.
12345678
import torch tensor = torch.arange(12) # Add a new dimension unsqueezed_tensor = tensor.unsqueeze(0) # Add a batch dimension print(f"Unsqueezed tensor: {unsqueezed_tensor.shape}") # Remove a dimension of size 1 squeezed_tensor = unsqueezed_tensor.squeeze(0) print(f"Squeezed Tensor: {squeezed_tensor.shape}")
copy

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 1. Capítulo 9
We're sorry to hear that something went wrong. What happened?
some-alt