简体   繁体   English

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

[英]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.我正在尝试通过组合通过基本数学函数计算的向量的维度来创建一些测试torch张量。 As a precursor: assembling Tensors from primitive python arrays does work:作为先驱:从原始 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]])

In addition we can assemble Tensors from numpy arrays https://pytorch.org/docs/stable/tensors.html :此外,我们可以从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]])

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 ValueError:只有一个元素张量可以转换为 Python 标量

What is the correct syntax?什么是正确的语法?

Update A comment requested showing x / X .更新要求显示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 - torch.arange返回一个 torch.Tensor 如下所示 -

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同样, torch.cos(x)torch.tan(x)返回 torch.Tensor 的实例

The ideal way to concatenate a sequence of tensors in torch is to use torch.stacktorch.stack连接一系列张量的理想方法是使用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.如果您更喜欢沿轴 = 0 连接,请改用torch.cat([torch.cos(x), torch.tan(x)])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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