![](/img/trans.png)
[英]ValueError: only one element tensors can be converted to Python scalars
[英]Pytorch math calculation ( only one element tensors can be converted to Python scalars)
在这种情况下,只有一个元素张量可以转换为 Python 标量是什么意思,我该如何调试它?
x1 = (max-min)*torch.rand(1, 21) + min
x2 = (max-min)*torch.rand(1, 21) + min
zipped_list = zip(x1, x2)
y = [math.sin(2*x1+2) * math.cos(0.5*x2)+0.5 for (x1, x2) in zipped_list]
输出
ValueError: only one element tensors can be converted to Python scalars
您会收到该错误,因为您的火炬张量(x1 和 x2)不是单元素张量。
t = torch.tensor([10, 20])
print(t.item()) # This will throw an error since the tensor has more than 1 element
t = torch.tensor([10])
t.item() # This will print 10
要解决您的问题,请将math.sin
和math.cos
调用替换为torch.sin
和torch.cos
。 torch.sin
或torch.cos
计算所有元素的正弦或余弦值。
问题是因为使用math.cos
和math.sin
。 math.cos 不是矢量化的,但 np.cos 是。 使用np.sin
和np.cos
或torch.sin
和torch.cos
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.