Exemplo n.º 1
0
def accuracy(output, target, topk=(1,)):
    output, target = to_torch(output), to_torch(target)
    maxk = max(topk)
    batch_size = target.size(0)

    _, pred = output.topk(maxk, 1, True, True)
    pred = pred.t()
    correct = pred.eq(target.view(1, -1).expand_as(pred))

    ret = []
    for k in topk:
        correct_k = correct[:k].view(-1).float().sum(0)
        ret.append(correct_k.mul_(1. / batch_size))
    return ret
Exemplo n.º 2
0
def extract_cnn_embeddings(model, inputs, modules=None):
    model.eval()
    for ind, inp in enumerate(inputs):
        inputs[ind] = to_torch(inp)
    inputs = [Variable(x, volatile=True).cuda() for x in inputs]

    assert modules is None

    outputs = model(*inputs)
    outputs = outputs.data
    return outputs
Exemplo n.º 3
0
def predict_prob(model, data, data_dir, config):
    config.set_training(False)
    model.eval()
    dataloader = dp.get_dataloader(data, data_dir, config)
    probs = []
    for i, (imgs, _, _, _, _) in enumerate(dataloader):
        inputs = to_torch(imgs)
        inputs = Variable(inputs, volatile=True)
        output = model(inputs)
        prob = nn.functional.softmax(output, dim=1)
        probs += [prob.data.cpu().numpy()]
    probs = np.concatenate(probs)
    return probs
Exemplo n.º 4
0
def extract_cnn_feature(model, inputs, modules=None):
    model.eval()
    inputs = to_torch(inputs)
    inputs = Variable(inputs, volatile=True)
    if modules is None:
        outputs = model(inputs)
        outputs = outputs.data.cpu()
        return outputs
    # Register forward hook for each module
    outputs = OrderedDict()
    handles = []
    for m in modules:
        outputs[id(m)] = None

        def func(m, i, o):
            outputs[id(m)] = o.data.cpu()

        handles.append(m.register_forward_hook(func))
    model(inputs)
    for h in handles:
        h.remove()
    return list(outputs.values())