本文整理汇总了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
示例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']
示例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']
示例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
示例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)
示例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)
示例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
示例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)
示例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)
示例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