从 `torch` 或 `numpy` 向量创建 pytorch 张量

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

我正在尝试创建一些测试 torch 张量,方法是组装通过基本数学函数计算的向量的维度。作为先驱:从原始 python arrays 组装张量确实有效:

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

此外,我们可以 assemble 来自 numpy 个数组的张量 https://pytorch.org/docs/stable/tensors.html:

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

然而,我无法从计算出的向量中进行组装。以下是一些尝试:

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

以上均有以下错误:

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

正确的语法是什么?

更新 请求的评论显示 x / X。它们实际上设置为相同(我在中途改变主意使用哪个)

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 如下所示 -

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

类似地,torch.cos(x)torch.tan(x) returns 个实例 torch.Tensor

在 torch 中连接张量序列的理想方法是使用 torch.stack

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

输出

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

如果您更喜欢沿 axis=0 连接,请改用 torch.cat([torch.cos(x), torch.tan(x)])