pytorch 把tensor转换成Python标量int float 且 AttributeError: Variable object has no attribute item

如何将1*1的tensor类型的变量转换为Python的标量?

 

如下面这行代码所示:

def ssim(img1,img2):
    img1 = torch.from_numpy(np.rollaxis(img1, 2)).float().unsqueeze(0)/255.0
    img2 = torch.from_numpy(np.rollaxis(img2, 2)).float().unsqueeze(0)/255.0   
    img1 = Variable( img1,  requires_grad=False)    # torch.Size([256, 256, 3])
    img2 = Variable( img2, requires_grad = False)
    ssim_value = pytorch_ssim.ssim(img1, img2).item()
    return ssim_value

在倒数第2行中,我们想将计算得到的pytorch_ssim.ssim(img1, img2)(FloatTensor类型,1*1)转换为Python的Float类型标量。本来上面代码中使用.item()的方法是可以的,但今天竟然报错了:

*** AttributeError: 'Variable' object has no attribute 'item'

报错原因还不清楚,猜测可能是版本的问题?

经过多次尝试,将倒数第二行改为下面的代码即可:

ssim_value = float(pytorch_ssim.ssim(img1, img2))

 

你可能感兴趣的:(#,计算成像,#,Deep,Learning,#,Code,ssim,pytorch,tensor,python)