python - PyTorch 何时自动转换 Tensor dtype?
问题描述
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.])
解决方案
推荐阅读
- qnamaker - 如果有多个答案,QnAMaker 服务是否会按分数对答案进行排序?
- sql - Hive sql 将多列扩展为行
- node.js - Docker nodejs无法打开文件
- node.js - 如何使用 Cloud Build 为部署在 Cloud Run 上的节点应用运行测试
- python - 如何在 shell_exec 运行 Python 脚本之前检查 CPU 使用率?或者替代排队方法来防止服务器过载?
- docker - 尝试从 docker 容器访问共享内存时出现“权限被拒绝”,即使 --ipc 设置为“主机”
- javascript - 将 Vue 属性绑定到异步值
- java - 使用 group by 休息命名约定
- ruby-on-rails - Ruby on Rails 中的多对多关系,无法使用多选字段创建多条记录
- elixir - 有没有办法在 Elixir 中将函数体作为字符串获取?