我正在 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))))
现在的问题是,如何进行反向传递并获得不同层的梯度?
典型的向后方法不起作用。
最佳答案
如果你想得到输入图像的.grad
,你必须用chainer.Variable
包装输入。
然而,VGGLayers.extract()
不支持Variable
的输入,所以在这种情况下你应该调用.forward()
或者它的包装函数__调用__()
。
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
关于python - Chainer 中加载的神经网络层的梯度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53106686/