CNN可视化

本文介绍了CNN(卷积神经网络)的可视化方法,包括查看网络层反应、绘制阴影图以理解分类决策过程,以及fool the net、生成特定类型图片、feature inversion和deep dream等技术,帮助我们洞察神经网络的内部工作原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

CNN可视化

1、查看感兴趣的任意层的方法
a、将图片放入网络
b、选择感兴趣的层,将该层中的感兴趣的神经元的上游梯度值设为1,其他神经元的值为0
c、反向传播至输入数据,求出dx

2、阴影图
a、将图片传入训练过的网络
b、前向传播至softmax层之前的那一层scores输出,确定该图片所属的类型,将该类值设置为1,其他的值设为0,作为上游梯度反向传播
c、由于是灰度图,而前向传播得到的dx可能有3channel,只需取3个channel中绝对值最大的那个
d、绘出灰度图

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, of shape (N, 3, H, W)
  - y: Labels for X, of shape (N,)
  - model: A PretrainedCNN that will be used to compute the saliency map.

  Returns:
  - saliency: An array of shape (N, H, W) giving the saliency maps for the input
    images.
  """
  N, _, H, W = X.shape
  saliency = np.zeros((N, H, W))
  ##############################################################################
  # TODO: Implement this function. You should use the forward and backward     #
  # methods of the PretrainedCNN class, and compute gradients with respect to  #
  # the unnormalized class score of the ground-truth classes in y.             #
  ##############################################################################
  out, cache = model.forward(X, start=None, end=None, mode = 'test')
  dscores = np.zeros_like(out)
  dscores[np.arange(N), y] = 1
  dx, grads = model.backward(dscores, cache)
  for n in range(N):
    for h in range(H):
        for w in range(W):
            saliency[n, h, w] = np.max(np.abs((dx[n, :, h, w])))
    #saliency[n,:,:] -= np.mean(saliency[n, :, :], axis=0, keepdims=True)
  #saliency = np.abs(np.max(dx.reshape(-1,3), axis = 1)).reshape((N, H, W))
  ##############################################################################
  #                             END OF YOUR CODE                               #
  ##############################################################################
  return saliency

3、fool the net
给定任意的图片,我们可以通过一些设置让 网络误以为图片属于我们设定的那一类。和阴影图的绘制相似,我们只需最大化相应类的得分即可
a、将图片传入训练过的网络
b、前向传播至softmax层之前的那一层scores输出,将该我们希望图片的类值设置为1,其他的值设为0,作为上游梯度反向传播
c、梯度提升更新图片(设置正确的参数后应该可以在100次迭代内fool the net)

def make_fooling_image(X, target_y, model):
  """
  Generate a fooling image that is close to X, but that the model classifies
  as target_y.

  Inputs:
  - X: Input image, of shape (1, 3, 64, 64)
  - target_y: An integer in the range [0, 100)
  - model: A PretrainedCNN

  Returns:
  - X_fooling: An image that is close to X, but that is classifed as target_y
    by the model.
  """
  X_fooling = X.copy()
  ##############################################################################
  # TODO: Generate a fooling image X_fooling that the model wil
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值