0

I am trying to create some testing torch tensors by assembling the dimensions from vectors calculated via basic math functions. As a precursor: assembling Tensors from primitive python arrays does work:

import torch
import numpy as np
torch.Tensor([[1.0, 0.8, 0.6],[0.0, 0.5, 0.75]])
>> tensor([[1.0000, 0.8000, 0.6000],
            [0.0000, 0.5000, 0.7500]])

In addition we can assemble Tensors from numpy arrays https://pytorch.org/docs/stable/tensors.html:

torch.tensor(np.array([[1, 2, 3], [4, 5, 6]]))
tensor([[ 1,  2,  3],
        [ 4,  5,  6]])

However assembling from calculated vectors is eluding me. Here are some of the attempts made:

X  = torch.arange(0,6.28)
x = X

torch.Tensor([[torch.cos(X),torch.tan(x)]])

torch.Tensor([torch.cos(X),torch.tan(x)])

torch.Tensor([np.cos(X),np.tan(x)])

torch.Tensor([[np.cos(X),np.tan(x)]])

torch.Tensor(np.array([np.cos(X),np.tan(x)]))

All of the above have the following error:

ValueError: only one element tensors can be converted to Python scalars

What is the correct syntax?

Update A comment requested showing x / X. They're actually set to the same (I changed mind mid-course which to use)

In [56]: x == X                                                                                                                          
Out[56]: tensor([True, True, True, True, True, True, True])

In [51]:  x                                                                                                                              
Out[51]: tensor([0., 1., 2., 3., 4., 5., 6.])

In [52]: X                                                                                                                               
Out[52]: tensor([0., 1., 2., 3., 4., 5., 6.])
2
  • 1
    Please let us know what values of x and X you use while assembling from calculated vectors. You probably have a typo somewhere. Commented Sep 19, 2020 at 3:17
  • @SVPraveen Added x/X values to the question Commented Sep 19, 2020 at 4:38

1 Answer 1

1

torch.arange returns a torch.Tensor as seen below -

X  = torch.arange(0,6.28)
x
>> tensor([0., 1., 2., 3., 4., 5., 6.])

Similarly, torch.cos(x) and torch.tan(x) returns instances of torch.Tensor

The ideal way to concatenate a sequence of tensors in torch is to use torch.stack

torch.stack([torch.cos(x), torch.tan(x)])

Output

>> tensor([[ 1.0000,  0.5403, -0.4161, -0.9900, -0.6536,  0.2837,  0.9602],
        [ 0.0000,  1.5574, -2.1850, -0.1425,  1.1578, -3.3805, -0.2910]])

If you prefer to concatenate along axis=0, use torch.cat([torch.cos(x), torch.tan(x)]) instead.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.