仅在 python 3 中给定 numpy 整数类型时出现 Pytorch 错误(不在 python 2 中)
Pytorch errors when given numpy integer types only in python 3 (not in python 2)
例如,torch.randn 函数等在给定 numpy.int64 类型时变得疯狂:
Python 3.5.5 |Anaconda custom (64-bit)| (default, Mar 12 2018, 23:12:44)
[GCC 7.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import torch
>>> import numpy
>>> torch.randn(numpy.int64(4))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: torch.randn received an invalid combination of arguments - got (numpy.int64), but expected one of:
* (int ... size)
didn't match because some of the arguments have invalid types: (numpy.int64)
* (torch.Size size)
didn't match because some of the arguments have invalid types: (numpy.int64)
* (torch.Generator generator, int ... size)
* (torch.Generator generator, torch.Size size)
但是在 python 2 中,这工作得很好:
Python 2.7.14 |Anaconda, Inc.| (default, Dec 7 2017, 17:05:42)
[GCC 7.2.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import torch
>>> import numpy
>>> torch.randn(numpy.int64(3))
-2.0513
0.5409
-0.0814
[torch.FloatTensor of size 3]
我找不到其他人 运行 讨论这个问题。这是众所周知的吗?这与我的设置有关吗?有没有办法在不完全放弃 numpy 的情况下解决这个问题?
我使用的是 0.3.1 版的 pytorch 和 1.14.2 版的 numpy。
在 Python 2 上,在 C long 是 64 位的 OS 上,numpy.int64
是 int
的子类,所以大多数需要 int 的东西将接受 numpy.int64
,即使它们不是为处理 int-like 类型而编写的。
在 Python 3 上,不再发生这种情况。如果您需要使用需要真正整数的库,请调用 int
:
torch.randn(int(some_numpy_integer))
例如,torch.randn 函数等在给定 numpy.int64 类型时变得疯狂:
Python 3.5.5 |Anaconda custom (64-bit)| (default, Mar 12 2018, 23:12:44)
[GCC 7.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import torch
>>> import numpy
>>> torch.randn(numpy.int64(4))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: torch.randn received an invalid combination of arguments - got (numpy.int64), but expected one of:
* (int ... size)
didn't match because some of the arguments have invalid types: (numpy.int64)
* (torch.Size size)
didn't match because some of the arguments have invalid types: (numpy.int64)
* (torch.Generator generator, int ... size)
* (torch.Generator generator, torch.Size size)
但是在 python 2 中,这工作得很好:
Python 2.7.14 |Anaconda, Inc.| (default, Dec 7 2017, 17:05:42)
[GCC 7.2.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import torch
>>> import numpy
>>> torch.randn(numpy.int64(3))
-2.0513
0.5409
-0.0814
[torch.FloatTensor of size 3]
我找不到其他人 运行 讨论这个问题。这是众所周知的吗?这与我的设置有关吗?有没有办法在不完全放弃 numpy 的情况下解决这个问题?
我使用的是 0.3.1 版的 pytorch 和 1.14.2 版的 numpy。
在 Python 2 上,在 C long 是 64 位的 OS 上,numpy.int64
是 int
的子类,所以大多数需要 int 的东西将接受 numpy.int64
,即使它们不是为处理 int-like 类型而编写的。
在 Python 3 上,不再发生这种情况。如果您需要使用需要真正整数的库,请调用 int
:
torch.randn(int(some_numpy_integer))