How to create a high dimension tensor with fixed shape and dtype?

Question:

I want to return a tensor with fixed shape size, like, torch.Size([1,345])
However, when I input,

import torch
pt1 = torch.tensor(data=(1, 345), dtype=torch.int64)

it only return torch.Size([2])

I followed some tensor tutorial a tried to

pt1 = torch.tensor(1, 345, dtype=torch.int64)
pt1 = torch.tensor((1, 345), dtype=torch.int64)
pt1 = torch.tensor(shape=(1, 345), dtype=torch.int64)

It still shows error like tensor() takes 1 positional argument but 2 were given
I know some methods mean the data is (1,345) not shape, but…I am novice in pytorch and still not finding the solution of it…

Asked By: 4daJKong

||

Answers:

You can use torch.zeros to make a new tensor

import torch

a = torch.zeros((1,345), dtype=torch.int64)
print(a.shape)
torch.Size([1, 345])
Answered By: core_not_dumped

The data argument of torch.tensor is supposed to be "Initial data for the tensor" and not its shape.

All tensors have fixed shapes. You can define a tensor with uninitialized values with torch.empty or have them filled with specific values (torch.zeros, torch.ones, torch.full, …). For instance:

>>> pt1 = torch.empty(1, 345, dtype=torch.int64)
Answered By: Ivan

According to pytorch’s documentation about torch.tensor, your torch.tensor(data=(1, 345), dtype=torch.int64) code is creating a 2-element tensor [1, 345] ( so it has a size of [2]). To create a tensor like you want, use:

import torch

pt1 = torch.zeros((1, 345), dtype=torch.int64)
pt1.size()
# torch.Size([1, 345])
Answered By: Zero-nnkn
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.