Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lernen Tensor Creation Functions | Section
Neural Networks and Deep Learning Foundations with PyTorch

bookTensor Creation Functions

Swipe um das Menü anzuzeigen

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
question mark

What will be the output of the following PyTorch code snippet?

Wählen Sie die richtige Antwort aus

War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 1. Kapitel 3

Fragen Sie AI

expand

Fragen Sie AI

ChatGPT

Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen

Abschnitt 1. Kapitel 3
some-alt