简体   繁体   中英

Creating pytorch Tensors from `torch` or `numpy` vectors

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.])

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM