Chainer中加载的神经网络的各层的梯度

时间:2018-11-01 17:49:23

标签: python deep-learning pre-trained-model chainer vgg-net

我正在Chainer中加载预先训练的模型:

net=chainer.links.VGG16Layers(pretrained_model='auto')

然后,我对一些数据进行前向传递并添加一个损失层:

acts = net.predict([image]).array loss=chainer.Variable(np.array(np.sum(np.square(acts-one_hot))))

现在的问题是,如何进行向后传递并获得不同图层的渐变?

典型的后退方法不起作用。

2 个答案:

答案 0 :(得分:2)

第1点。
不要调用VGGLayers.predict(),这不是用于backprop计算的。
不要使用VGGLayers.extract()

第2点。
请勿将np.square()np.sum()直接应用于chainer.Variable
请使用F.square()F.sum()代替chainer.Variable

第3点。
使用loss.backward()获取.grad作为可学习的参数。 (模式1)
使用loss.backward(retain_grad=True)获取所有变量的.grad。 (模式2)
使用chainer.grad()获取特定变量的.grad。 (模式3)

代码:

import chainer
from chainer import functions as F, links as L
from cv2 import imread

net = L.VGG16Layers(pretrained_model='auto')
img = imread("/path/to/img")
prob = net.extract([img], layers=['prob'])['prob']  # NOT predict, which overrides chainer.config['enable_backprop'] as False
intermediate = F.square(prob)
loss = F.sum(intermediate)

# pattern 1:
loss.backward()
print(net.fc8.W.grad)  # some ndarray
print(intermediate.grad)  # None
###########################################
net.cleargrads()
intermediate.grad = None
prob.grad = None
###########################################

# pattern 2:
loss.backward(retain_grad=True)
print(net.fc8.W.grad)  # some ndarray
print(intermediate.grad)  # some ndarray

###########################################
net.cleargrads()
intermediate.grad = None
prob.grad = None
###########################################

# pattern 3:
print(chainer.grad([loss], [net.fc8.W]))  # some ndarray
print(intermediate.grad)  # None

答案 1 :(得分:2)

如果要获取.grad的输入图像,则必须用chainer.Variable包装输入。
但是,VGGLayers.extract()不支持Variable的输入,因此在这种情况下,您应该调用.forward()或其包装函数__call__()

import chainer
from chainer import Variable
from chainer import functions as F
from cv2 import imread
from chainer.links.model.vision import vgg

net = vgg.VGG16Layers(pretrained_model='auto')

# convert raw image (np.ndarray, dtype=uint32) to a batch of Variable(dtype=float32)
img = imread("path/to/image")
img = Variable(vgg.prepare(img))
img = img.reshape((1,) + img.shape)  # (channel, width, height) -> (batch, channel, width, height)

# just call VGG16Layers.forward, which is wrapped by __call__()
prob = net(img)['prob']
intermediate = F.square(prob)
loss = F.sum(intermediate)

# calculate grad
img_grad = chainer.grad([loss], [img])  # returns Variable
print(img_grad.array) # some ndarray