Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this the way to create a PyTorch scalar?

Tags:

python

pytorch

I'm new to PyTorch, and just wanted to kindly confirm if the following creates scalars with values, 1, 2, and 3, respectively?

import torch

a = torch.tensor(1)
b = torch.tensor(2)
c = torch.tensor(3)

Thanks.

like image 350
Simplicity Avatar asked Jan 01 '23 11:01

Simplicity


2 Answers

From the example in the documentation for torch.tensor:

>>> torch.tensor(3.14159)  # Create a scalar (zero-dimensional tensor)
tensor(3.1416)

Therefore, it appears they endorse that passing a number creates the corresponding scalar.

like image 109
Dair Avatar answered Jan 03 '23 00:01

Dair


You can further check what is in your tensor.

import torch
t = torch.tensor(1)
print(t.size())
print(t.ndim)
print(t.numel())
print(t.stride())
print(t.element_size())
print(t.type())

And keep track that PyTorch can create tensors by data and by dimension.

import torch
# by data
t = torch.tensor([1., 1.])
# by dimension
t = torch.zeros(2,2)

Your case was to create tensor by data which is a scalar: t = torch.tensor(1). But this also is a scalar: t = torch.tensor([1]) imho because it has a size and no direction. ;)

like image 26
prosti Avatar answered Jan 03 '23 01:01

prosti