What is the difference between torch.tensor and torch.Tensor?
According to discussion on pytorch discussion
torch.Tensor
constructor is overloaded to do the same thing as both torch.tensor
and torch.empty
. It is thought this overload would make code confusing, so split torch.Tensor
into torch.tensor
and torch.empty
.
So yes, to some extent, torch.tensor
works similarly to torch.Tensor (when you pass in data). no, neither should be more efficient than the other. It's just that the torch.empty
and torch.tensor
have a nicer API than torch.Tensor
constructor.
In PyTorch torch.Tensor
is the main tensor class. So all tensors are just instances of torch.Tensor
.
When you call torch.Tensor()
you will get an empty tensor without any data
.
In contrast torch.tensor
is a function which returns a tensor. In the documentation it says:
torch.tensor(data, dtype=None, device=None, requires_grad=False) → Tensor
Constructs a tensor with
data
.
This also explains why it is no problem creating an empty tensor instance of `torch.Tensor` without `data` by calling:
tensor_without_data = torch.Tensor()
But on the other side:
tensor_without_data = torch.tensor()
Will lead to an error:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-12-ebc3ceaa76d2> in <module>()
----> 1 torch.tensor()
TypeError: tensor() missing 1 required positional arguments: "data"
But in general there is no reason to choose `torch.Tensor` over `torch.tensor`. Also `torch.Tensor` lacks a docstring.
Similar behaviour for creating a tensor without data
like with: torch.Tensor()
can be achieved using:
torch.tensor(())
Output:
tensor([])
In addition to the above answers, I noticed:
torch.Tensor()
creates a tensor with the default data type, as defined bytorch.get_default_dtype()
.torch.tensor()
will infer data type from the data.
For example:
>>> torch.Tensor([1, 2, 3]).dtype
torch.float32
>>> torch.tensor([1, 2, 3]).dtype
torch.int64
https://discuss.pytorch.org/t/difference-between-torch-tensor-and-torch-tensor/30786/2
torch.tensor infers the dtype automatically, while torch.Tensor returns a torch.FloatTensor. I would recommend to stick to torch.tensor, which also has arguments like dtype, if you would like to change the type.