【问题标题】:PyTorch [1 if x > 0.5 else 0 for x in outputs ] with tensorsPyTorch [1 if x > 0.5 else 0 for x in outputs ] 带张量
【发布时间】:2020-01-20 00:07:51
【问题描述】:

我有一个 sigmoid 函数的列表输出作为 PyTorch 中的张量

例如

output (type) = torch.Size([4]) tensor([0.4481, 0.4014, 0.5820, 0.2877], device='cuda:0',

在进行二进制分类时,我想将所有低于 0.5 的值变为 0,将高于 0.5 的值变为 1。

传统上,您可以使用 NumPy 数组使用列表迭代器:

output_prediction = [1 if x > 0.5 else 0 for x in outputs ]

这可行,但是我必须稍后将 output_prediction 转换回张量才能使用

torch.sum(ouput_prediction == labels.data)

其中 labels.data 是标签的二进制张量。

有没有办法使用带有张量的列表迭代器?

【问题讨论】:

  • 也许你可以使用output_prediction = torch.tensor([1 if x > 0.5 else 0 for x in outputs ])

标签: python pytorch torchvision


【解决方案1】:
prob = torch.tensor([0.3,0.4,0.6,0.7])

out = (prob>0.5).float()
# tensor([0.,0.,1.,1.])

说明:在pytorch中,可以直接使用prob>0.5得到一个torch.bool类型的张量。然后就可以通过.float()转成float类型了。

【讨论】:

    【解决方案2】:

    为什么不考虑使用 loopless 解决方案?也许像下面这样就足够了:

    In [34]: output = torch.tensor([0.4481, 0.4014, 0.5820, 0.2877]) 
    
    # subtract off the threshold value (0.5), create a boolean mask, 
    # and then cast the resultant tensor to an `int` type
    In [35]: result = torch.as_tensor((output - 0.5) > 0, dtype=torch.int32) 
    
    In [36]: result        
    Out[36]: tensor([0, 0, 1, 0], dtype=torch.int32)
    

    【讨论】:

    • 您对减法如何增加执行成本有任何见解吗?在您看来,它会比公认的解决方案花费更长的时间吗?
    • @dennlinger 根据我的测试,时间差异似乎可以忽略不计,有时我什至没有执行时间差异。
    猜你喜欢
    • 1970-01-01
    • 2012-11-04
    • 1970-01-01
    • 1970-01-01
    • 2015-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多