Contenido del Curso
Neural Networks with PyTorch
Neural Networks with PyTorch
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:
import torch tensor = torch.tensor([[1, 2, 3], [4, 5, 6]]) print(f"Tensor shape: {tensor.shape}")
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.
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}")
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.
import torch tensor = torch.arange(12) # Reshape a tensor to 6x2 reshaped_tensor = tensor.reshape(6, 2) print(f"Reshaped tensor: {reshaped_tensor}")
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.
import torch # Automatically infer the second dimension inferred_tensor = tensor.view(2, -1) print("Inferred Tensor:", inferred_tensor)
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.
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)
Changing Dimensions
unsqueeze(dim)
adds a new dimension at the specified position;squeeze(dim)
removes dimensions of size 1.
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}")
¡Gracias por tus comentarios!