Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprende Tensor Creation Functions | 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
Tensor Creation Functions

Similarly to NumPy, PyTorch also offers several built-in functions to create tensors directly. These functions help in initializing data placeholders and generating structured or custom tensors.

Tensor of Zeros and Ones

To create a tensor filled with zeros, use torch.zeros(). The arguments represent the size of each dimension, with the number of arguments corresponding to the number of dimensions:

123
import torch tensor = torch.zeros(4, 2) print(tensor)
copy

This is useful for initializing biases or placeholders where the initial values are set to zero.

Similarly, use torch.ones() to create a tensor filled with ones:

123
import torch tensor = torch.ones(3, 3) print(tensor)
copy

This can be particularly useful for initializing weights, bias terms, or performing operations where a tensor of ones serves as a neutral element or a specific multiplier in mathematical computations.

Arange and Linspace

Similarly to numpy.arange(), torch.arange() generates a sequence of values with a specified step size:

123
import torch tensor = torch.arange(0, 10, step=2) print(tensor)
copy

We have successfully created a tensor with values from 0 to 10 exclusive with the step size equal to 2.

To create evenly spaced values between a start and end point, use torch.linspace():

123
import torch tensor = torch.linspace(0, 1, steps=5) print(tensor)
copy

This generates a tensor with 5 equally spaced values between 0 and 1 inclusive.

Tensor from Shape

You can create tensors with a specific shape by using the "like" variants of creation functions. These create tensors with the same shape as an existing tensor:

123456
import torch x = torch.tensor([[1, 2, 3], [4, 5, 6]]) zeros_tensor = torch.zeros_like(x) ones_tensor = torch.ones_like(x) print(f"Tensor of zeros: {zeros_tensor}") print(f"Tensor of ones: {ones_tensor}")
copy

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

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