繁体   English   中英

Pytorch 数学计算(只能将一个元素张量转换为 Python 标量)

[英]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.sinmath.cos调用替换为torch.sintorch.cos torch.sintorch.cos计算所有元素的正弦或余弦值。

问题是因为使用math.cosmath.sin math.cos 不是矢量化的,但 np.cos 是。 使用np.sinnp.costorch.sintorch.cos

暂无
暂无

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

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