Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Tensor Creation Functions | PyTorch Introduction
PyTorch Essentials

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:

import torch
tensor = torch.zeros(4, 2)
print(tensor)
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:

import torch
tensor = torch.ones(3, 3)
print(tensor)
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:

import torch
tensor = torch.arange(0, 10, step=2)
print(tensor)
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():

import torch
tensor = torch.linspace(0, 1, steps=5)
print(tensor)
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:

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}")
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?

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

Select the correct answer

Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 1. Kapitel 3

Spørg AI

expand
ChatGPT

Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat

We use cookies to make your experience better!
some-alt