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
如果要获得输入图像的}。在
.grad
,必须用chainer.Variable
来包装输入。但是,
VGGLayers.extract()
不支持Variable
的输入,因此在这种情况下,您应该调用.forward()
或其包装函数{第1点。
不要调用
VGGLayers.predict()
,这不是用于backprop计算的。请改用
VGGLayers.extract()
。在第2点。}代替
不要将
np.square()
和np.sum()
直接应用于chainer.Variable
。使用
F.square()
和{chainer.Variable
。在第三点。
使用
loss.backward()
获得可学习参数的.grad
。使用
loss.backward(retain_grad=True)
获得所有变量的.grad
。(模式2)使用
chainer.grad()
获得特定变量的.grad
。(图案3)代码:
相关问题 更多 >
编程相关推荐