测试概念激活向量(TCAV)

发布于 2025-01-22 15:22:17 字数 1377 浏览 0 评论 0原文

我正在尝试计算测试概念激活向量( tcav,如下所述我的分类模型。到目前为止,我还没有成功地在线找到Pytorch模型的代码,因此我决定自己重写它。我要复制的代码是:

def compute_tcav(input_tensor, model, AA, layer_name, filter_indices, optimizer, seed_input=None, wrt_tensor=None, backprop_modifier=None, grad_modifier='absolute'):
   
    layer_AA = AA[layer_name]
    
    losses = [
        (ActivationMaximization(layer_AA, filter_indices), -1)
    ]
    
    opt = optimizer(input_tensor, losses, wrt_tensor=wrt_tensor, norm_grads=False)
    #grads = opt.minimize(seed_input=seed_input, max_iter=1, grad_modifier=grad_modifier, verbose=False)[1]
    
    return losses #utils.normalize(grads)[0]

源:

def ActivationMaximizationLoss(input_AA):
    loss = torch.mean(input_AA)
    return loss
def compute_tcav_pytorch(model, layer_predictions):
    optimizer = torch.optim.SGD(model.parameters(), 1e-4)
    optimizer.zero_grad()
    
    input_AA = torch.from_numpy(layer_predictions['_blocks.6._project_conv']) # middle    
    input_AA.requires_grad=True
    
    loss = ActivationMaximizationLoss2(input_AA)
    loss.backward()
    optimizer.step()
    
    img = input_AA.grad
    
    return img[0][0]

I am trying to compute the Testing Concept Activation Vectors (TCAV, as described here) vectors for different concepts for my classification model. So far, I haven't successfully found code online for Pytorch models so I have decided to rewrite it myself. The code I am trying to copy is:

def compute_tcav(input_tensor, model, AA, layer_name, filter_indices, optimizer, seed_input=None, wrt_tensor=None, backprop_modifier=None, grad_modifier='absolute'):
   
    layer_AA = AA[layer_name]
    
    losses = [
        (ActivationMaximization(layer_AA, filter_indices), -1)
    ]
    
    opt = optimizer(input_tensor, losses, wrt_tensor=wrt_tensor, norm_grads=False)
    #grads = opt.minimize(seed_input=seed_input, max_iter=1, grad_modifier=grad_modifier, verbose=False)[1]
    
    return losses #utils.normalize(grads)[0]

source: https://github.com/maragraziani/iMIMIC-RCVs/blob/master/rcv_utils.py

This is what I have so far:

def ActivationMaximizationLoss(input_AA):
    loss = torch.mean(input_AA)
    return loss
def compute_tcav_pytorch(model, layer_predictions):
    optimizer = torch.optim.SGD(model.parameters(), 1e-4)
    optimizer.zero_grad()
    
    input_AA = torch.from_numpy(layer_predictions['_blocks.6._project_conv']) # middle    
    input_AA.requires_grad=True
    
    loss = ActivationMaximizationLoss2(input_AA)
    loss.backward()
    optimizer.step()
    
    img = input_AA.grad
    
    return img[0][0]

I am trying to maximise a layer activation from the model and from that get the TCAV vector.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文