【发布时间】:2023-04-06 06:46:01
【问题描述】:
PyTorch 何时自动转换 Tensor dtype?为什么有时会自动执行,有时会抛出错误?
例如,这会自动将c 转换为浮点数:
a = torch.tensor(5)
b = torch.tensor(5.)
c = a*b
a.dtype
>>> torch.int64
b.dtype
>>> torch.float32
c.dtype
>>> torch.float32
但这会引发错误:
a = torch.ones(2, dtype=torch.float)
b = torch.ones(2, dtype=torch.long)
c = torch.matmul(a,b)
Traceback (most recent call last):
File "<ipython-input-128-fbff7a713ff0>", line 1, in <module>
torch.matmul(a,b)
RuntimeError: Expected object of scalar type Float but got scalar type Long for argument #2 'tensor'
我很困惑,因为 Numpy 似乎会根据需要自动转换所有数组,例如
a = np.ones(2, dtype=np.long)
b = np.ones(2, dtype=np.float)
np.matmul(a,b)
>>> 2.0
a*b
>>> array([1., 1.])
【问题讨论】:
-
它在第一种情况下(也)为我抛出错误。我正在使用 PyTorch 0.4.1