这将非常类似于卷积网络滤波器的可视化方式:我们将在输入空间中进行梯度上升优化,以使特定滤波器的响应最大化。在
方法如下:培训结束后,首先我们需要指定输出并定义要最大化的损失函数:from keras import backend as K
output_class = 0 # the index of the output class we want to maximize
output = model.layers[-1].output
loss = K.mean(output[:,output_class]) # get the average activation of our desired class over the batch
接下来,我们需要取上面定义的关于输入层的损耗梯度:
^{pr2}$
接下来,我们需要定义一个后端函数,该函数以初始输入图像为输出,并将损失和渐变的值作为输出,以便在下一步中使用它来实现优化过程:func = K.function([model.input], [loss, grads])
最后,我们实现了梯度上升优化过程:import numpy as np
input_img = np.random.random((1, 28, 28)) # define an initial random image
lr = 1. # learning rate used for gradient updates
max_iter = 50 # number of gradient updates iterations
for i in range(max_iter):
loss_val, grads_val = func([input_img])
input_img += grads_val * lr # update the image based on gradients
请注意,此过程完成后,要显示图像,您可能需要确保图像中的所有值都在范围[0,255](或[0,1])。在