python - 从 `torch` 或 `numpy` 向量创建 pytorch 张量
问题描述
我试图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]])
此外,我们可以从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:只有一个元素张量可以转换为 Python 标量
什么是正确的语法?
更新请求显示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
返回一个torch.Tensor,如下所示 -
X = torch.arange(0,6.28)
x
>> tensor([0., 1., 2., 3., 4., 5., 6.])
同样,torch.cos(x)
并torch.tan(x)
返回 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]])
如果您更喜欢沿轴 = 0 连接,请torch.cat([torch.cos(x), torch.tan(x)])
改用。
推荐阅读
- html - 具有相同名称的多个无线电组的 HTML
- javascript - 将特定函数 CALL 分配给变量
- windows - 使用批处理关闭文件资源管理器中所有打开的文件夹
- python - python如何按索引删除子字符串
- php - Laravel Dusk $browser->attach() 机器升级后不再工作
- sql-server - 如何使用掩码字符或下面字符串中的任何其他技巧过滤出年份?
- r - 如何在 R 中使用 ggplot2 绘制平均值的误差线?
- java - Java 中的递归和 While 循环
- c# - 对 2captcha 使用 POST 方法时出错
- javascript - 子组件不是从一个父级的状态更改重新渲染,而是从另一个父级重新渲染?