CS231n Assignment3 Q3心得笔记


一学期网课就这么混完了…CS231n的作业说停就停了3个月,果然人是一种懒惰性很强的动物。细数一下从开始写Assignment1的Q1开始,到今天也快一年了,我真是拖延症晚期患者…好吧,及时弥补,写完这篇关于Network Visualization的博客,暑期燥起来!

Saliency Maps

这次的作业可以分为三个部分,第一个部分是关于显著图的绘制。显著图可以告诉我们究竟是图像中的哪些像素影响了网络的分类结果,即到底是什么部分让网络知道这是帅帅的我,而不是一只傻狗!

为了计算显著图,我们首先需要计算出网络对于当前图片在正确类别上的得分,并且计算出损失在图像每个像素点上的梯度,然后对于每个像素点,取个通道中最大的梯度绝对值作为该像素点处的值。

这一部分需要补充的代码比较简单,正好熟悉一下Pytorch的用法:

def compute_saliency_maps(X, y, model):
    """
    Compute a class saliency map using the model for images X and labels y.

    Input:
    - X: Input images; Tensor of shape (N, 3, H, W)
    - y: Labels for X; LongTensor of shape (N,)
    - model: A pretrained CNN that will be used to compute the saliency map.

    Returns:
    - saliency: A Tensor of shape (N, H, W) giving the saliency maps for the input
    images.
    """
    # Make sure the model is in "test" mode
    model.eval()
    
    # Make input tensor require gradient
    X.requires_grad_()
    
    saliency = None
    ##############################################################################
    # TODO: Implement this function. Perform a forward and backward pass through #
    # the model to compute the gradient of the correct class score with respect  #
    # to each input image. You first want to compute the loss over the correct   #
    # scores (we'll combine losses across a batch by summing), and then compute  #
    # the gradients with a backward pass.                                        #
    ##############################################################################
    # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****

    scores = model(X)
    loss = scores.gather(1, y.view(-1, 1)).squeeze().sum()
    loss.backward()
    saliency = torch.max(torch.abs(X.grad), 1)[0]

    # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
    ##############################################################################
    #                             END OF YOUR CODE                               #
    ##############################################################################
    return saliency

值得一提的是这里的gather函数,这是Pytorch提供的一个函数,用来实现的功能和我们之前assignment中使用的 s[np.arange(N), y] 一样,用来从指定的数组中提取以y为下标的数值。

之后我们就看到了我们显著图的效果,当当当当!

在这里插入图片描述
然后我们看一个小问题

A friend of yours suggests that in order to find an image that maximizes the correct score, we can perform gradient ascent on the input image, but instead of the gradient we can actually use the saliency map in each step to update the image. Is this assertion true? Why or why not?

答案当然是不可以的,因为我们根据梯度更新图像的时候当然是

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值