【导读】集成梯度是一种用于将分类模型的预测归因于其输入特征的技术。这是一种模型可解释性技术:它来可视化输入要素和模型预测之间的关系。
原文链接:
https://keras.io/examples/vision/integrated_gradients/
介绍
集成梯度是在计算预测输出相对于输入特征的梯度时的变体。要计算集成梯度,我们需要执行以下步骤:
1. 识别输入和输出。在我们的例子中,输入是图像,输出是模型的最后一层(具有softmax激活的Dense层)。
2.在对特定数据点进行预测时,计算哪些特征对神经网络很重要。为了识别这些特征,我们需要选择一个基线输入。基线输入可以是黑色图像(所有像素值均设置为零)或随机噪声。基线输入的形状需要与我们的输入图像相同,例如(299,299,3)。
3. 在给定的步骤数内插基线。步数表示对于给定的输入图像,我们需要进行梯度近似的步骤。步骤数是一个超参数。作者建议使用20到1000步之间的任何步长。
4. 预处理这些插值图像并进行正向传递。
5. 获取这些插值图像的梯度。
6. 使用梯形法则近似梯度积分。
设置
import numpy as npimport matplotlib.pyplot as pltfrom scipy import ndimagefrom IPython.display import Imageimport tensorflow as tffrom tensorflow import kerasfrom tensorflow.keras import layersfrom tensorflow.keras.applications import xception# Size of the input imageimg_size = (299, 299, 3)# Load Xception model with imagenet weightsmodel = xception.Xception(weights="imagenet")# The local path to our target imageimg_path = keras.utils.get_file("elephant.jpg", "https://i.imgur.com/Bvro0YD.png")display(Image(img_path))
显示图片
集成梯度算法
def get_img_array(img_path, size=(299, 299)): # `img` is a PIL image of size 299x299img = keras.preprocessing.image.load_img(img_path, target_size=size) # `array` is a float32 Numpy array of shape (299, 299, 3)array = keras.preprocessing.image.img_to_array(img) # We add a dimension to transform our array into a "batch" # of size (1, 299, 299, 3)array = np.expand_dims(array, axis=0)return arraydef get_gradients(img_input, top_pred_idx):"""Computes the gradients of outputs w.r.t input image.Args:img_input: 4D image tensortop_pred_idx: Predicted label for the input imageReturns:Gradients of the predictions w.r.t img_input"""images = tf.cast(img_input, tf.float32)with tf.GradientTape() as tape:tape.watch(images)preds = model(images)top_class = preds[:, top_pred_idx]grads = tape.gradient(top_class, images)return gradsdef get_integrated_gradients(img_input, top_pred_idx, baseline=None, num_steps=50):"""Computes Integrated Gradients for a predicted label.Args:img_input (ndarray): Original imagetop_pred_idx: Predicted label for the input imagebaseline (ndarray): The baseline image to start with for interpolationnum_steps: Number of interpolation steps between the baselineand the input used in the computation of integrated gradients. Thesesteps along determine the integral approximation error. By default,num_steps is set to 50.Returns:Integrated grad