Python 关于pytorch张量的一种奇怪的行为。有人能解释清楚吗?

Python 关于pytorch张量的一种奇怪的行为。有人能解释清楚吗?,python,pytorch,Python,Pytorch,当我创建PyTorch张量并尝试探索其类型时,我发现: >>> a = torch.rand(3,5) >>> a tensor([[0.3356, 0.0968, 0.2185, 0.9843, 0.7846], [0.8523, 0.3300, 0.7181, 0.2692, 0.6523], [0.0523, 0.9344, 0.3505, 0.8901, 0.6464]]) >>> type(a) &l

当我创建PyTorch张量并尝试探索其类型时,我发现:

>>> a = torch.rand(3,5)
>>> a
tensor([[0.3356, 0.0968, 0.2185, 0.9843, 0.7846],
        [0.8523, 0.3300, 0.7181, 0.2692, 0.6523],
        [0.0523, 0.9344, 0.3505, 0.8901, 0.6464]])
>>> type(a)
<class 'torch.Tensor'>
>>> a = a.cuda()
>>> a.is_cuda
True
>>> type(a)
<class 'torch.Tensor'>
>>> a.dtype
torch.float32
>>> 
>a=torch.rand(3,5)
>>>a
张量([[0.3356,0.0968,0.2185,0.9843,0.7846],
[0.8523, 0.3300, 0.7181, 0.2692, 0.6523],
[0.0523, 0.9344, 0.3505, 0.8901, 0.6464]])
>>>类型(a)
>>>a=a.cuda()
>>>a.你是库达吗
真的
>>>类型(a)
>>>a.D类型
火炬32
>>> 

为什么
type(a)
仍然是
torch.Tensor
而不是
torch.cuda.Tensor
,即使这个Tensor已经在GPU上了?

你让我在那里挖掘,但是显然
type()
作为
内置的
方法不适用于类型检测,因为
0.4.0
(请参阅和)

为了获得正确的类型,
torch.Tensor
类具有
type()
成员,可以简单地使用:

import torch

a = torch.rand(3, 5)
print(a)
print(a.type())
a = a.to("cuda")
print(a.is_cuda)
print(a.type())
正如预期的那样,这将产生:

tensor([[0.5060, 0.6998, 0.5054, 0.4822, 0.4408],
        [0.7686, 0.4508, 0.4968, 0.4460, 0.7352],
        [0.1810, 0.6953, 0.7499, 0.7105, 0.1776]])
torch.FloatTensor
True
torch.cuda.FloatTensor

但是,我不确定这一决定背后的理由,除此之外,我找不到任何相关信息。

是的!唯一的区别是
a.type()
got
torch.FloatTensor
type(a)
got
;根据这一点,我猜这是因为
type(a)
是python的一个函数,用于输出变量
a
的类型,它是pytorch张量,但python无法判断它是哪种pytorch张量。另一方面,
a.type()
调用pytorch的一个方法,因此它可以判断具体的pytorch张量类型。我想是的,但这些只是我的推测,并没有具体说明它在引擎盖下是如何工作的(即C++和CUDA)。