當前位置: 首頁>>代碼示例>>Python>>正文


Python inception.inception_v3方法代碼示例

本文整理匯總了Python中torchvision.models.inception.inception_v3方法的典型用法代碼示例。如果您正苦於以下問題:Python inception.inception_v3方法的具體用法?Python inception.inception_v3怎麽用?Python inception.inception_v3使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在torchvision.models.inception的用法示例。


在下文中一共展示了inception.inception_v3方法的10個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: __init__

# 需要導入模塊: from torchvision.models import inception [as 別名]
# 或者: from torchvision.models.inception import inception_v3 [as 別名]
def __init__(self):
        super().__init__()
        self.inception_model = inception_v3(pretrained=True)
        self.inception_model.Mixed_7c.register_forward_hook(self.output_hook)
        self.mixed_7c_output = None 
開發者ID:paperswithcode,項目名稱:torchbench,代碼行數:7,代碼來源:utils.py

示例2: load_inception_net

# 需要導入模塊: from torchvision.models import inception [as 別名]
# 或者: from torchvision.models.inception import inception_v3 [as 別名]
def load_inception_net(parallel=False):
  inception_model = inception_v3(pretrained=True, transform_input=False).cuda()
  inception_model = WrapInception(inception_model.eval()).cuda()
  if parallel:
    print('Parallelizing Inception module...')
    inception_model = nn.DataParallel(inception_model)
  return inception_model


# This produces a function which takes in an iterator which returns a set number of samples
# and iterates until it accumulates config['num_inception_images'] images.
# The iterator can return samples with a different batch size than used in
# training, using the setting confg['inception_batchsize'] 
開發者ID:WANG-Chaoyue,項目名稱:EvolutionaryGAN-pytorch,代碼行數:15,代碼來源:inception_utils.py

示例3: load_inception_net

# 需要導入模塊: from torchvision.models import inception [as 別名]
# 或者: from torchvision.models.inception import inception_v3 [as 別名]
def load_inception_net(parallel=False):
  inception_model = inception_v3(pretrained=True, transform_input=False)
  inception_model = WrapInception(inception_model.eval()).cuda()
  if parallel:
    print('Parallelizing Inception module...')
    inception_model = nn.DataParallel(inception_model)
  return inception_model


# This produces a function which takes in an iterator which returns a set number of samples
# and iterates until it accumulates config['num_inception_images'] images.
# The iterator can return samples with a different batch size than used in
# training, using the setting confg['inception_batchsize'] 
開發者ID:ajbrock,項目名稱:BigGAN-PyTorch,代碼行數:15,代碼來源:inception_utils.py

示例4: inception_score_precomp

# 需要導入模塊: from torchvision.models import inception [as 別名]
# 或者: from torchvision.models.inception import inception_v3 [as 別名]
def inception_score_precomp(imgs, cuda=True, batch_size=32, resize=False):
    N = len(imgs)
    batch_size = min(batch_size, N)

    assert batch_size > 0

    # Set up dtype
    if cuda:
        dtype = torch.cuda.FloatTensor
    else:
        if torch.cuda.is_available():
            print("WARNING: You have a CUDA device, so you should probably set cuda=True")
        dtype = torch.FloatTensor

    # Set up dataloader
    dataloader = torch.utils.data.DataLoader(imgs, batch_size=batch_size)

    # Load inception model
    inception_model = inception_v3(pretrained=True, transform_input=False).type(dtype)
    inception_model.eval()
    up = nn.Upsample(size=(299, 299), mode='bilinear').type(dtype)

    def get_pred(x):
        if resize:
            x = up(x)
        x = inception_model(x)
        return F.softmax(x).data.cpu().numpy()

    # Get predictions
    preds = np.full((N, INCEPTION_NUM_F), np.nan)

    for i, batch in enumerate(dataloader, 0):
        batch = batch.type(dtype)
        batchv = Variable(batch)
        batch_size_i = batch.size()[0]

        preds[i*batch_size:i*batch_size + batch_size_i] = get_pred(batchv)
    assert np.all(np.isfinite(preds))

    return preds 
開發者ID:uber-research,項目名稱:metropolis-hastings-gans,代碼行數:42,代碼來源:inception_score.py

示例5: inception_score

# 需要導入模塊: from torchvision.models import inception [as 別名]
# 或者: from torchvision.models.inception import inception_v3 [as 別名]
def inception_score(imgs, cuda=True, batch_size=32, resize=False, splits=1):
    """Computes the inception score of the generated images imgs

    imgs -- Torch dataset of (3xHxW) numpy images normalized in the range [-1, 1]
    cuda -- whether or not to run on GPU
    batch_size -- batch size for feeding into Inception v3
    splits -- number of splits
    """
    N = len(imgs)

    assert batch_size > 0
    assert N > batch_size

    # Set up dtype
    if cuda:
        dtype = torch.cuda.FloatTensor
    else:
        if torch.cuda.is_available():
            print("WARNING: You have a CUDA device, so you should probably set cuda=True")
        dtype = torch.FloatTensor

    # Set up dataloader
    dataloader = torch.utils.data.DataLoader(imgs, batch_size=batch_size)

    # Load inception model
    inception_model = inception_v3(pretrained=True, transform_input=False).type(dtype)
    inception_model.eval();
    up = nn.Upsample(size=(299, 299), mode='bilinear').type(dtype)
    def get_pred(x):
        if resize:
            x = up(x)
        x = inception_model(x)
        return F.softmax(x).data.cpu().numpy()

    # Get predictions
    preds = np.zeros((N, 1000))

    for i, batch in enumerate(dataloader, 0):
        batch = batch.type(dtype)
        batchv = Variable(batch)
        batch_size_i = batch.size()[0]

        preds[i*batch_size:i*batch_size + batch_size_i] = get_pred(batchv)

    # Now compute the mean kl-div
    split_scores = []

    for k in range(splits):
        part = preds[k * (N // splits): (k+1) * (N // splits), :]
        py = np.mean(part, axis=0)
        scores = []
        for i in range(part.shape[0]):
            pyx = part[i, :]
            scores.append(entropy(pyx, py))
        split_scores.append(np.exp(np.mean(scores)))

    return np.mean(split_scores), np.std(split_scores) 
開發者ID:sbarratt,項目名稱:inception-score-pytorch,代碼行數:59,代碼來源:inception_score.py

示例6: inception_score

# 需要導入模塊: from torchvision.models import inception [as 別名]
# 或者: from torchvision.models.inception import inception_v3 [as 別名]
def inception_score(img_ds, cuda=True, batch_size=32, resize=False, splits=1):
    """Computes the inception score of the generated images imgs

    Ref:
        https://github.com/sbarratt/inception-score-pytorch/blob/master/inception_score.py
    Args:
        img_ds: Torch dataset of (3xHxW) numpy images normalized in the range [-1, 1]
        cuda: whether or not to run on GPU
        batch_size: batch size for feeding into Inception v3
        splits: number of splits
    """
    N = len(img_ds)
    assert batch_size > 0
    assert N > batch_size
    # Set up dtype
    if cuda:
        dtype = torch.cuda.FloatTensor
    else:
        if torch.cuda.is_available():
            print("WARNING: You have a CUDA device, so you should probably set cuda=True")
        dtype = torch.FloatTensor
    # Set up dataloader
    dataloader = torch.utils.data.DataLoader(img_ds, batch_size=batch_size)
    # Load inception model
    inception_model = inception_v3(pretrained=True, transform_input=False).type(dtype)
    inception_model.eval()
    up = nn.Upsample(size=(299, 299), mode='bilinear').type(dtype)

    def get_pred(x):
        if resize:
            x = up(x)
        x = inception_model(x)
        return F.softmax(x).data.cpu().numpy()
    # Get predictions
    preds = np.zeros((N, 1000))
    for i, batch in enumerate(dataloader, 0):
        batch = batch.type(dtype)
        batchv = Variable(batch)
        batch_size_i = batch.size()[0]

        preds[i * batch_size:i * batch_size + batch_size_i] = get_pred(batchv)

    # Now compute the mean kl-div
    split_scores = []

    for k in range(splits):
        part = preds[k * (N // splits): (k + 1) * (N // splits), :]
        py = np.mean(part, axis=0)
        scores = []
        for i in range(part.shape[0]):
            pyx = part[i, :]
            scores.append(entropy(pyx, py))
        split_scores.append(np.exp(np.mean(scores)))

    return np.mean(split_scores), np.std(split_scores) 
開發者ID:doublechenching,項目名稱:brats_segmentation-pytorch,代碼行數:57,代碼來源:inception_score.py

示例7: create_model

# 需要導入模塊: from torchvision.models import inception [as 別名]
# 或者: from torchvision.models.inception import inception_v3 [as 別名]
def create_model(model_name, num_classes=1000, pretrained=False, **kwargs):
    if 'test_time_pool' in kwargs:
        test_time_pool = kwargs.pop('test_time_pool')
    else:
        test_time_pool = True
    if model_name == 'dpn68':
        model = dpn68(
            pretrained=pretrained, test_time_pool=test_time_pool, num_classes=num_classes)
    elif model_name == 'dpn68b':
        model = dpn68b(
            pretrained=pretrained, test_time_pool=test_time_pool, num_classes=num_classes)
    elif model_name == 'dpn92':
        model = dpn92(
            pretrained=pretrained, test_time_pool=test_time_pool, num_classes=num_classes)
    elif model_name == 'dpn98':
        model = dpn98(
            pretrained=pretrained, test_time_pool=test_time_pool, num_classes=num_classes)
    elif model_name == 'dpn131':
        model = dpn131(
            pretrained=pretrained, test_time_pool=test_time_pool, num_classes=num_classes)
    elif model_name == 'dpn107':
        model = dpn107(
            pretrained=pretrained, test_time_pool=test_time_pool, num_classes=num_classes)
    elif model_name == 'resnet18':
        model = resnet18(pretrained=pretrained, num_classes=num_classes, **kwargs)
    elif model_name == 'resnet34':
        model = resnet34(pretrained=pretrained, num_classes=num_classes, **kwargs)
    elif model_name == 'resnet50':
        model = resnet50(pretrained=pretrained, num_classes=num_classes, **kwargs)
    elif model_name == 'resnet101':
        model = resnet101(pretrained=pretrained, num_classes=num_classes, **kwargs)
    elif model_name == 'resnet152':
        model = resnet152(pretrained=pretrained, num_classes=num_classes, **kwargs)
    elif model_name == 'densenet121':
        model = densenet121(pretrained=pretrained, num_classes=num_classes, **kwargs)
    elif model_name == 'densenet161':
        model = densenet161(pretrained=pretrained, num_classes=num_classes, **kwargs)
    elif model_name == 'densenet169':
        model = densenet169(pretrained=pretrained, num_classes=num_classes, **kwargs)
    elif model_name == 'densenet201':
        model = densenet201(pretrained=pretrained, num_classes=num_classes, **kwargs)
    elif model_name == 'inception_v3':
        model = inception_v3(
            pretrained=pretrained, num_classes=num_classes, transform_input=False, **kwargs)
    else:
        assert False, "Unknown model architecture (%s)" % model_name
    return model 
開發者ID:rwightman,項目名稱:pytorch-dpn-pretrained,代碼行數:49,代碼來源:model_factory.py

示例8: __init__

# 需要導入模塊: from torchvision.models import inception [as 別名]
# 或者: from torchvision.models.inception import inception_v3 [as 別名]
def __init__(self, mode, cuda=True,
                 stats_file='', mu1=0, sigma1=0):
        """
        Computes the inception score of the generated images
            cuda -- whether or not to run on GPU
            mode -- image passed in inceptionV3 is normalized by mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]
                and in range of [-1, 1]
                1: image passed in is normalized by mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]
                2: image passed in is normalized by mean=[0.500, 0.500, 0.500], std=[0.500, 0.500, 0.500]
        """
        # load mu, sigma for calc FID
        self.calc_fid = False
        if stats_file:
            self.calc_fid = True
            self.mu1, self.sigma1 = read_stats_file(stats_file)
        elif type(mu1) == type(sigma1) == np.ndarray:
            self.calc_fid = True
            self.mu1, self.sigma1 = mu1, sigma1

        # Set up dtype
        if cuda:
            self.dtype = torch.cuda.FloatTensor
        else:
            if torch.cuda.is_available():
                print("WARNING: You have a CUDA device, so you should probably set cuda=True")
            self.dtype = torch.FloatTensor

        # setup image normalization mode
        self.mode = mode
        if self.mode == 1:
            transform_input = True
        elif self.mode == 2:
            transform_input = False
        else:
            raise Exception("ERR: unknown input img type, pls specify norm method!")
        self.inception_model = inception_v3(pretrained=True, transform_input=transform_input).type(self.dtype)
        self.inception_model.eval()
        # self.up = nn.Upsample(size=(299, 299), mode='bilinear', align_corners=False).type(self.dtype)

        # remove inception_model.fc to get pool3 output 2048 dim vector
        self.fc = self.inception_model.fc
        self.inception_model.fc = nn.Sequential()

        # wrap with nn.DataParallel
        self.inception_model = nn.DataParallel(self.inception_model)
        self.fc = nn.DataParallel(self.fc) 
開發者ID:lzhbrian,項目名稱:metrics,代碼行數:48,代碼來源:is_fid_pytorch.py

示例9: inception_score

# 需要導入模塊: from torchvision.models import inception [as 別名]
# 或者: from torchvision.models.inception import inception_v3 [as 別名]
def inception_score(imgs, device=None, batch_size=32, resize=False, splits=1):
    """Computes the inception score of the generated images imgs

    Args:
        imgs: Torch dataset of (3xHxW) numpy images normalized in the
              range [-1, 1]
        cuda: whether or not to run on GPU
        batch_size: batch size for feeding into Inception v3
        splits: number of splits
    """
    N = len(imgs)

    assert batch_size > 0
    assert N > batch_size

    # Set up dataloader
    dataloader = torch.utils.data.DataLoader(imgs, batch_size=batch_size)

    # Load inception model
    inception_model = inception_v3(pretrained=True, transform_input=False)
    inception_model = inception_model.to(device)
    inception_model.eval()
    up = nn.Upsample(size=(299, 299), mode='bilinear').to(device)

    def get_pred(x):
        with torch.no_grad():
            if resize:
                x = up(x)
            x = inception_model(x)
            out = F.softmax(x, dim=-1)
        out = out.cpu().numpy()
        return out

    # Get predictions
    preds = np.zeros((N, 1000))

    for i, batch in enumerate(dataloader, 0):
        batchv = batch.to(device)
        batch_size_i = batch.size()[0]

        preds[i*batch_size:i*batch_size + batch_size_i] = get_pred(batchv)

    # Now compute the mean kl-div
    split_scores = []

    for k in range(splits):
        part = preds[k * (N // splits): (k+1) * (N // splits), :]
        py = np.mean(part, axis=0)
        scores = []
        for i in range(part.shape[0]):
            pyx = part[i, :]
            scores.append(entropy(pyx, py))
        split_scores.append(np.exp(np.mean(scores)))

    return np.mean(split_scores), np.std(split_scores) 
開發者ID:akanazawa,項目名稱:vgan,代碼行數:57,代碼來源:inception_score.py

示例10: inception_score

# 需要導入模塊: from torchvision.models import inception [as 別名]
# 或者: from torchvision.models.inception import inception_v3 [as 別名]
def inception_score(imgs, cuda=True, batch_size=32, resize=False, splits=1):
    """Computes the inception score of the generated images imgs

    imgs -- Torch dataset of (3xHxW) numpy images normalized in the range [-1, 1]
    cuda -- whether or not to run on GPU
    batch_size -- batch size for feeding into Inception v3
    splits -- number of splits
    """
    N = len(imgs)

    assert batch_size > 0
    assert N > batch_size

    # Set up dtype
    if cuda:
        dtype = torch.cuda.FloatTensor
    else:
        if torch.cuda.is_available():
            print("WARNING: You have a CUDA device, so you should probably set cuda=True")
        dtype = torch.FloatTensor

    # Set up dataloader
    dataloader = torch.utils.data.DataLoader(imgs, batch_size=batch_size)

    # Load inception model
    inception_model = inception_v3(pretrained=True, transform_input=False).type(dtype)
    inception_model.eval();
    up = nn.Upsample(size=(299, 299), mode='bilinear').type(dtype)
    def get_pred(x):
        if resize:
            x = up(x)
        x = inception_model(x)
        return F.softmax(x).data.cpu().numpy()

    # Get predictions
    preds = np.zeros((N, 1000))

    for i, batch in enumerate(dataloader, 0):
        batch = batch.type(dtype)
        batchv = Variable(batch)
        batch_size_i = batch.size()[0]

        preds[i*batch_size:i*batch_size + batch_size_i] = get_pred(batchv)

    # Now compute the mean kl-div
    split_scores = []

    for k in range(splits):
        part = preds[k * (N // splits): (k+1) * (N // splits), :]
        py = np.mean(part, axis=0)
        scores = []
        for i in range(part.shape[0]):
            pyx = part[i, :]
            scores.append(entropy(pyx, py))
        split_scores.append(np.exp(np.mean(scores)))

    return split_scores 
開發者ID:uber-research,項目名稱:metropolis-hastings-gans,代碼行數:59,代碼來源:inception_score.py


注:本文中的torchvision.models.inception.inception_v3方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。