Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/meteor/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Pytorch:如何计算用于语义分割的IoU(Jaccard索引)_Pytorch - Fatal编程技术网

Pytorch:如何计算用于语义分割的IoU(Jaccard索引)

Pytorch:如何计算用于语义分割的IoU(Jaccard索引),pytorch,Pytorch,有人能提供一个玩具例子来说明如何在pytorch中为语义分段计算IoU(联合交集)吗?我在某处找到了这个,并对它进行了修改。如果我能再次找到它,我会发布链接。很抱歉,这是一个错误。 这里的关键函数是名为iou的函数。包装函数evaluate\u performance不是通用的,但它表明在计算IoU之前需要迭代所有结果 import torch import pandas as pd # For filelist reading import myPytorchDatasetClass #

有人能提供一个玩具例子来说明如何在pytorch中为语义分段计算IoU(联合交集)吗?

我在某处找到了这个,并对它进行了修改。如果我能再次找到它,我会发布链接。很抱歉,这是一个错误。
这里的关键函数是名为
iou
的函数。包装函数
evaluate\u performance
不是通用的,但它表明在计算
IoU
之前需要迭代所有结果

import torch 
import pandas as pd  # For filelist reading
import myPytorchDatasetClass  # Custom dataset class, inherited from torch.utils.data.dataset


def iou(pred, target, n_classes = 12):
  ious = []
  pred = pred.view(-1)
  target = target.view(-1)

  # Ignore IoU for background class ("0")
  for cls in xrange(1, n_classes):  # This goes from 1:n_classes-1 -> class "0" is ignored
    pred_inds = pred == cls
    target_inds = target == cls
    intersection = (pred_inds[target_inds]).long().sum().data.cpu()[0]  # Cast to long to prevent overflows
    union = pred_inds.long().sum().data.cpu()[0] + target_inds.long().sum().data.cpu()[0] - intersection
    if union == 0:
      ious.append(float('nan'))  # If there is no ground truth, do not include in evaluation
    else:
      ious.append(float(intersection) / float(max(union, 1)))
  return np.array(ious)


def evaluate_performance(net):
    # Dataloader for test data
    batch_size = 1  
    filelist_name_test = '/path/to/my/test/filelist.txt'
    data_root_test = '/path/to/my/data/'
    dset_test = myPytorchDatasetClass.CustomDataset(filelist_name_test, data_root_test)
    test_loader = torch.utils.data.DataLoader(dataset=dset_test,  
                                              batch_size=batch_size,
                                              shuffle=False,
                                              pin_memory=True)
    data_info = pd.read_csv(filelist_name_test, header=None)
    num_test_files = data_info.shape[0]  
    sample_size = num_test_files

    # Containers for results
    preds = Variable(torch.zeros((sample_size, 60, 36, 60)))
    gts = Variable(torch.zeros((sample_size, 60, 36, 60)))

    dataiter = iter(test_loader) 
    for i in xrange(sample_size):
        images, labels, filename = dataiter.next()
        images = Variable(images).cuda()
        labels = Variable(labels)
        gts[i:i+batch_size, :, :, :] = labels
        outputs = net(images)
        outputs = outputs.permute(0, 2, 3, 4, 1).contiguous()
        val, pred = torch.max(outputs, 4)
        preds[i:i+batch_size, :, :, :] = pred.cpu()
    acc = iou(preds, gts)
    return acc

假设您的输出是形状
[32,256,256]
#32是小批量大小,256x256是图像的高度和宽度,标签也是相同的形状

然后你可以使用sklearn的
jaccard\u相似度\u分数
,在一些重塑之后

如果两者都是火炬张量,则:

lbl = labels.cpu().numpy().reshape(-1)
target = output.cpu().numpy().reshape(-1)
现在:


演示如何在tensorflow中实现它。将其移植到PyTorch应该是很容易的。在最新的Sklearn中,如0.24.1,函数名已更改为jaccard_score。
from sklearn.metrics import jaccard_similarity_score as jsc
print(jsc(target,lbl))