【问题标题】:Visualize the output of Vgg16 model by TSNE plot?通过 TSNE 图可视化 Vgg16 模型的输出?
【发布时间】:2020-05-25 01:38:06
【问题描述】:

我需要可视化分类 14 个不同类别的 Vgg16 模型的输出。 我加载了训练好的模型,我确实用 identity() 层替换了分类器层,但它没有对输出进行分类。

这里是sn-p: 这里的样本数量是 1000 张图片。

epoch = 800
PATH = 'vgg16_epoch{}.pth'.format(epoch)
checkpoint = torch.load(PATH)
model.load_state_dict(checkpoint['model_state_dict'])
optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
epoch = checkpoint['epoch']

class Identity(nn.Module):
    def __init__(self):
        super(Identity, self).__init__()

    def forward(self, x):
        return x

model.classifier._modules['6'] = Identity()
model.eval()
logits_list = numpy.empty((0,4096))  
targets = []


with torch.no_grad():
    for step, (t_image, target, classess, image_path) in enumerate(test_loader):

        t_image = t_image.cuda()
        target = target.cuda()
        target = target.data.cpu().numpy()
        targets.append(target)

        logits = model(t_image)
        print(logits.shape)

        logits = logits.data.cpu().numpy()
        print(logits.shape)
        logits_list = numpy.append(logits_list, logits, axis=0)     
        print(logits_list.shape)


tsne = TSNE(n_components=2, verbose=1, perplexity=10, n_iter=1000) 
tsne_results = tsne.fit_transform(logits_list)   

 target_ids = range(len(targets))

plt.scatter(tsne_results[:,0],tsne_results[:,1],c = target_ids ,cmap=plt.cm.get_cmap("jet", 14))
plt.colorbar(ticks=range(14))
plt.legend()
plt.show()

以下是该脚本的生成内容:我不确定为什么每个集群都有所有颜色!

【问题讨论】:

    标签: python-3.x matplotlib pytorch scatter-plot


    【解决方案1】:

    VGG16 向分类器输出超过 25k 的特征。我相信这对 t-SNE 来说太过分了。包含一个新的nn.Linear 层来减少这个数字是个好主意。因此,t-SNE 可能效果更好。此外,我建议您使用两种不同的方式从模型中获取特征:

    1. 无论型号如何,获得它的最佳方法是使用register_forward_hook 方法。你可以找到一个笔记本here 有一个例子。

    2. 如果您不想使用收银机,我建议您使用此收银机。加载模型后,您可以使用以下类来提取特征:

    class FeatNet (nn.Module):
        def __init__(self, vgg):
            super(FeatNet, self).__init__()
            self.features = nn.Sequential(*list(vgg.children())[:-1]))
    
        def forward(self, img):
            return self.features(img)
    

    现在,您只需致电FeatNet(img) 即可获取这些功能。

    如我之前建议的,要包含特征缩减器,您需要重新训练您的模型,执行以下操作:

    class FeatNet (nn.Module):
        def __init__(self, vgg):
            super(FeatNet, self).__init__()
            self.features = nn.Sequential(*list(vgg.children())[:-1]))
    
        self.feat_reducer = nn.Sequential(
            nn.Linear(25088, 1024),
            nn.BatchNorm1d(1024),
            nn.ReLU()
        )
       
        self.classifier = nn.Linear(1024, 14)
    
    
        def forward(self, img):
            x = self.features(img)
            x_r = self.feat_reducer(x)
            return self.classifier(x_r)
    

    然后,您可以运行返回x_r 的模型,即减少的特征。正如我告诉过你的,25k 特征对于 t-SNE 来说太多了。另一种减少此数字的方法是使用 PCA 代替 nn.Linear。在这种情况下,您将 25k 特征发送到 PCA,然后使用 PCA 的输出训练 t-SNE。我更喜欢使用nn.Linear,但你需要测试一下,看看哪个效果更好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-11
      • 1970-01-01
      • 1970-01-01
      • 2020-05-05
      • 1970-01-01
      • 2018-05-23
      • 2013-07-24
      相关资源
      最近更新 更多