隐藏input但可输入_Keras集成梯度用于模型可解释性

集成梯度是一种模型可解释技术,用于理解神经网络预测中的输入特征重要性。通过选择基线输入(如黑色图像),进行多次插值计算,然后用梯形法则近似梯度积分,可以揭示输入特征与模型预测的关系。Keras提供了一个示例,展示了如何在图像分类任务中应用集成梯度进行可视化解释。
摘要由CSDN通过智能技术生成

【导读】集成梯度是一种用于将分类模型的预测归因于其输入特征的技术。这是一种模型可解释性技术:它来可视化输入要素和模型预测之间的关系。

原文链接:

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))

显示图片

7e2b0cf74536845251886f3cb63c79ef.png

集成梯度算法

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值