IS指标复现 文本生成图像IS分数定量实验全流程复现 Inception Score定量评价实验踩坑避坑流程

一、IS分数简介

文本生成图像的评估也是一个很有挑战性的工作,IS分数是测量图像质量的一个通用指标。
IS用到了KL散度和熵的数学知识,其主要原理在于计算p(y|x)和p(y)之间的散度,IS分数越大越好。

二、IS分数 CUB定量实验步骤

以DF-GAN为例子:

第一步:B_VALIDATION改为True

根据DF-GAN的官方文档,首先将bird.yml中的B_VALIDATION改为True:
在这里插入图片描述

第二步:配置训练好的生成器

配置训练好的model,并将其放到code/bird中,重命名为netG.pth,DF-GAN官方也给出了训练好的模型:官方链接 ,打不开官方链接的可以点击CSDN链接,下载后放入指定文件夹即可。
在这里插入图片描述

第三步:采样生成图像

运行:python main.py --cfg cfg/bird.yml

可能出现的问题1:RuntimeError: Attempting to deserialize object on CUDA device
1 but torch.cuda.device_count() is 1
问题原因:模型在训练时使用了多块GPU,但是本机只有1块GPU
解决方案:指定用“cuda:0”,找到两个torch.load()
第一处在main.py的第57行:netG.load_state_dict(torch.load('models/%s/netG.pth' % (cfg.CONFIG_NAME))将其更改为:netG.load_state_dict(torch.load('models/%s/netG.pth' % (cfg.CONFIG_NAME), map_location='cuda:0'))
第二处在第254行将其更改为:state_dict = torch.load(cfg.TEXT.DAMSM_NAME, map_location='cuda:0')

可能出现的问题2:
RuntimeError: Error(s) in loading state_dict for NetG:
size mismatch for fc.weight: copying a param with shape torch.Size([4096, 100]) from checkpoint, the shape in current model is torch.Size([1024, 100]).
size mismatch for fc.bias: copying a param with shape torch.Size([4096]) from checkpoint, the shape in current model is torch.Size([1024]).
size mismatch for block0.c1.weight: copying a param with shape torch.Size([256, 256, 3, 3]) from checkpoint, the shape in current model is torch.Size([64, 64, 3, 3])
问题原因:在加载模型时,参数对应不上,尺寸mismatch
解决方案:查看训练出的模型model.py与此时做定量的model.py是否一样,查看yml文件的尺寸大小是否设置一样,特别是NF参数的设置。如果是使用的DF-GAN官方训练好的模型,要将NF设置为32,其他也要保持一致:

成功运行后,会进行自动采样生成若干图片,即成功
在这里插入图片描述

第四步:下载IS代码并配置

官方提供的IS分数(StackGAN用过的)代码:github链接,将其放入文件夹中位置如下:
在这里插入图片描述

第五步:下载预训练好的inception mode并配置

下载预训练好的inception model:官方链接、打不开可以点击:CSDN链接,将其放入文件夹指定位置,位置如下:

在这里插入图片描述

第六步:配置inception_score.py,更改读取的路径

打开inception_score.py的代码,定位到41行到49行:
在这里插入图片描述
可以看到这里有两个文件地址,第一个地址是指明在哪里读取预训练好的inception model checkpoints,将其改为自己放的路径:
在这里插入图片描述

tf.app.flags.DEFINE_string('checkpoint_dir',
                           '../birds_valid299/model.ckpt',
                           """Path where to read model checkpoints.""")

第二个路径是指从哪里读取采样的图片,同样将其改为自己放的路径:
在这里插入图片描述

tf.app.flags.DEFINE_string('image_folder',
                           '../test/valid/single',
                           """Path where to load the images """)

第七步:开始定量评测

在终端输入:python inception_score.py --image_folder ../test/valid/single
显示如下:
在这里插入图片描述
就是大功告成啦,可以看到本次结果为 4.61,误差为±0.13!

最后

💖 个人简介:人工智能领域研究生,目前主攻文本生成图像(text to image)方向

📝 个人主页:中杯可乐多加冰

🔥 限时免费订阅:文本生成图像T2I专栏

🎉 支持我:点赞👍+收藏⭐️+留言📝

如果这篇文章帮助到你很多,希望能不吝打赏我一杯可乐!多加冰哦

  • 12
    点赞
  • 39
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 27
    评论
下面是使用 PyTorch 计算 Inception Score 的示例代码: ```python import torch import torch.nn as nn from torch.utils.data import DataLoader from torchvision import models, transforms, datasets import numpy as np from scipy.stats import entropy def inception_score(imgs, batch_size=32, resize=False): """ Computes the Inception Score of the generated images imgs """ assert (type(imgs) == np.ndarray) assert (imgs.shape[1] == 3) assert (np.min(imgs[0]) >= 0 and np.max(imgs[0]) > 10), 'Image values should be in the range [0, 255]' N = len(imgs) # Set up the Inception model inception_model = models.inception_v3(pretrained=True) inception_model.eval() if resize: # Resize the images to 299x299 transform = transforms.Compose([ transforms.ToPILImage(), transforms.Resize((299, 299)), transforms.ToTensor(), transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) ]) else: # Crop the images to 299x299 transform = transforms.Compose([ transforms.ToPILImage(), transforms.RandomCrop((299, 299)), transforms.ToTensor(), transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) ]) dataset = ImageDataset(imgs, transform) dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=False) # Compute the activations of the Inception model for all batches of images activations = [] for batch in dataloader: pred = inception_model(batch)[0] activations.append(pred.detach().cpu().numpy()) activations = np.concatenate(activations, axis=0) # Compute the mean and covariance of the activations mu = np.mean(activations, axis=0) sigma = np.cov(activations, rowvar=False) # Compute the Inception Score scores = [] for i in range(N // batch_size): batch = torch.from_numpy(imgs[i * batch_size:(i + 1) * batch_size]).float().cuda() pred = inception_model(batch)[0].detach().cpu().numpy() p_yx = np.exp(-0.5 * np.sum((pred - mu) ** 2 * np.linalg.inv(sigma), axis=1)) / np.sqrt( np.linalg.det(sigma) * (2 * np.pi) ** pred.shape[1]) scores.append(p_yx) scores = np.concatenate(scores, axis=0) scores = np.mean(scores.reshape((-1, 1)), axis=0) scores = np.exp(entropy(scores)) return scores class ImageDataset(torch.utils.data.Dataset): def __init__(self, imgs, transform=None): self.imgs = imgs self.transform = transform def __getitem__(self, index): img = self.imgs[index] if self.transform is not None: img = self.transform(img) return img def __len__(self): return len(self.imgs) ``` 这里需要注意的一点是,这个代码中用到了 PyTorch 的 `models.inception_v3` 模型,需要安装 torchvision 库才能使用。另外,在计算 Inception Score 时,建议对生成的图片进行大小调整或裁剪,以便与 Inception v3 的输入要求相匹配。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 27
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

中杯可乐多加冰

请我喝杯可乐吧,我会多加冰!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值