人工智能的可解释性(XAI) | 使用LIME

人工智能(AI)的广阔领域近年来经历了巨大的增长。随着每年更新、更复杂的模型问世,人工智能模型已经开始以无人能预测的速度超越人类智力。但是,随着我们得到更准确和精确的结果,解释这些模型所采取的复杂数学决策背后的推理变得越来越困难。这种数学抽象也不能帮助用户保持对特定模型决策的信任。

例如,在一个实例中,假设一个深度学习模型接收一张图像,并以70%的准确率预测患者患有肺癌。虽然模型可能给出了正确的诊断,但医生不能真正自信地建议患者,因为他/她不知道所述模型诊断背后的推理。

这就是可解释性AI(XAI)的用武之地。

可解释性AI

可解释的AI是指帮助解释给定AI模型的决策过程的技术或方法。这个新发现的人工智能分支已经显示出巨大的潜力,每年都有更新和更复杂的技术出现。一些最著名的XAI技术包括SHAP(Shapley Additive exPlanations)、DeepSHAP、DeepLIFT、CXplain和LIME。

LIME(Local Interpretable Model-agnostic Explanations)

LIME的美在于它的易用性和简单性。LIME背后的核心思想虽然详尽,但确实直观而简单!让我们来看看这个名字本身代表着什么:

  • Model agnosticism是指LIME的属性,它可以通过将任何给定的监督学习模型单独视为“黑盒”给予解释它。这意味着LIME可以处理几乎任何存在的模型!
  • Local explanations意味着LIME给出在被解释的观察/样本的周围或附近局部忠实的解释。

虽然LIME目前仅限于监督机器学习和深度学习模型,但它是最受欢迎和最常用的XAI方法之一。LIME拥有丰富的开源API,可在R和Python中使用。github地址:[https://github.com/marcotcr/lime]

LIME是如何工作的

一般来说,当给定预测模型和测试样本时,LIME执行以下步骤:

  • 采样并获得替代数据集:LIME在被解释的实例附近提供局部忠实的解释。默认情况下,它会生成5000个遵循正态分布的特征向量样本。然后,它使用预测模型获得这5000个样本的目标变量,并试图解释其决策。
  • 替代数据集中的特征选择:在获得替代数据集之后,它根据每行与原始样本/观察的接近程度来加权每行。然后使用Lasso等特征选择技术来获得最重要的特征。

LIME还使用所获得的特征对样本采用岭回归模型。理论上,输出预测应与原始预测模型的输出大小相似。这样做是为了强调这些获得的特征的相关性和重要性。

安装

pip install lime

在继续之前,这里有一些要点,有助于更好地理解围绕LIME的整个工作流程。

数据集描述

LIME在其当前状态下只能对以下类型的数据集给予解释:

  • 表格数据集(lime.lime_tabular.LimeTabularExplainer):例如:回归、分类数据集
  • 图像相关数据集(lime.lime_image.LimeImageExplainer)
  • 文本相关数据集(lime.lime_text.LimeTextExplainer)

由于这是一篇介绍性文章,我们将保持简单,并继续使用表格数据集。更具体地说,我们将使用波士顿房价数据集进行分析。我们将使用Scikit-Learn来加载波士顿数据集。

使用的预测模型
由于LIME本质上是模型不可知的,它可以处理几乎任何抛出的模型。为了强调这一事实,我们将通过Scitkit-learn使用Extra-trees回归器作为我们的预测模型,我们试图调查其决策。

LimeTabularExplainer简介
如上所述,我们将使用表格数据集进行分析。为了处理这样的数据集,LIME的API提供了LimeTabularExplainer。

语法:lime.lime_tablet.LimeTabularExplainer(training_data,mode,feature_names,verbose)
主要参数:
training_data - 由训练数据集组成的2d数组
mode- 取决于问题;“分类”或“回归”
feature_names - 与训练数据集中的列对应的特征列表。如果没有提到,它使用列索引。
verbose - 如果为true,则打印仅使用获得的特征在样本上训练的回归模型的局部预测值

一旦实例化,我们将使用来自定义的解释器对象的方法来解释给定的测试样本。

语法:explain_instance(data_row,predict_fn,num_features=10,num_samples=5000)
主要参数:
data_row -包含与正在解释的测试样本对应的值的1d数组
predict_fn -预测模型使用的预测函数
num_features -解释中存在的最大特征数
num_samples -学习线性模型的邻域大小

为了简洁和简明起见,在上述两种语法中只提到了一些论点。其余的参数,其中大部分默认为一些巧妙优化的值,可以由感兴趣的读者在官方LIME文档中查看[https://lime-ml.readthedocs.io/en/latest/]

工作流程

  1. 数据预处理
  2. 在数据集上训练Extra-trees回归器
  3. 获得给定测试样本的解释

1. 使用Scikit-learn提取数据

# Importing the necessary libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# Loading the dataset using sklearn
from sklearn.datasets import load_boston
data = load_boston()

# Displaying relevant information about the data
print(data['DESCR'][200:1420])

输出

Boston house prices dataset
---------------------------

**Data Set Characteristics:**  

    :Number of Instances: 506 

    :Number of Attributes: 13 numeric/categorical predictive. Median Value (attribute 14) is usually the target.

    :Attribute Information (in order):
        - CRIM     per capita crime rate by town
        - ZN       proportion of residential land zoned for lots over 25,000 sq.ft.
        - INDUS    proportion of non-retail business acres per town
        - CHAS     Charles River dummy variable (= 1 if tract bounds river; 0 otherwise)
        - NOX      nitric oxides concentration (parts per 10 million)
        - RM       average number of rooms per dwelling
        - AGE      proportion of owner-occupied units built prior to 1940
        - DIS      weighted distances to five Boston employment centres
        - RAD      index of accessibility to radial highways
        - TAX      full-value property-tax rate per $10,000
        - PTRATIO  pupil-teacher ratio by town
        - B        1000(Bk - 0.63)^2 where Bk is the proportion of black people by town
        - LSTAT    % lower status of the population
        - MEDV     Median value of owner-occupied homes in $1000's

    :Missing Attribute Values: None

    :Creator: Harrison, D. and Rubinfeld, D.L.

This is a copy of UCI ML housing dataset.
https://archive.ics.uci.edu/ml/machine-learning-databases/housing/

2. 提取特征矩阵X和目标变量y,并进行训练-测试划分

# Separating data into feature variable X and target variable y respectively
from sklearn.model_selection import train_test_split
X = data['data']
y = data['target']

# Extracting the names of the features from data
features = data['feature_names']

# Splitting X & y into training and testing set
X_train, X_test, y_train, y_test = train_test_split(
	X, y, train_size=0.90, random_state=50)

# Creating a dataframe of the data, for a visual check
df = pd.concat([pd.DataFrame(X), pd.DataFrame(y)], axis=1)
df.columns = np.concatenate((features, np.array(['label'])))
print("Shape of data =", df.shape)

# Printing the top 5 rows of the dataframe
df.head()

输出

Shape of data = (506, 14)

在这里插入图片描述

3. 实例化预测模型并在(X_train,y_train)上对其进行训练

# Instantiating the prediction model - an extra-trees regressor
from sklearn.ensemble import ExtraTreesRegressor
reg = ExtraTreesRegressor(random_state=50)

# Fitting the predictino model onto the training set
reg.fit(X_train, y_train)

# Checking the model's performance on the test set
print('R2 score for the model on test set =', reg.score(X_test, y_test))

输出

R2 score for the model on test set = 0.9183847734063736

4. 实例化解释器对象

# Importing the module for LimeTabularExplainer
from lime import lime_tabular

# Instantiating the explainer object by passing in the training set,
# and the extracted features
explainer_lime = lime_tabular.LimeTabularExplainer(X_train,
												feature_names=features,
												verbose=True,
												mode='regression')

5. 通过调用explain_instance()方法获取解释

  • 假设我们想要探索预测模型对第i个测试向量给出的预测背后的推理。
  • 此外,假设我们想要可视化导致这种推理的前k个特征。

在本文中,我们给出了两种i & k组合的解释:

5.1 解释i=10,k=5的决策

我们基本上要求LIME通过显示对所述模型的预测做出贡献的前5个特征来解释第10个测试向量的预测背后的决定。

# Index corresponding to the test vector
i = 10

# Number denoting the top features
k = 5

# Calling the explain_instance method by passing in the:
# 1) ith test vector
# 2) prediction function used by our prediction model('reg' in this case)
# 3) the top features which we want to see, denoted by k

exp_lime = explainer_lime.explain_instance(
	X_test[i], reg.predict, num_features=k)

# Finally visualizing the explanations
exp_lime.show_in_notebook()

输出

Intercept 20.03385472541795
Prediction_local [33.9748055]
Right: 34.323999999999984

在这里插入图片描述
解释输出:

LIME输出了大量信息,让我们一步一步来解读它想要传达的东西

  1. 首先,我们在可视化上方看到三个值:
    Right:这表示我们的预测模型(在本例中是一个额外树回归器)对给定测试向量给出的预测。
    Prediction_local:这表示由在扰动样本上训练的线性模型输出的值(通过在遵循正态分布的测试向量周围采样而获得)并且仅使用由LIME输出的前k个特征。
    Intercept:截距是由上述线性模型对给定测试向量的预测给出的预测的恒定部分。
    在这里插入图片描述
  2. 在可视化方面,我们可以看到蓝色和橙色,分别描绘了消极和积极的关联。
  • 为了解释上述结果,我们可以得出这样的结论:给定向量所描绘的房屋相对较低的价格价值(如左侧的条形图所示)可以归因于以下社会经济原因:
  • LSTAT高值表明在教育和人口方面的地位水平低
  • PTRATIO的高值表示城镇中的教师学生比例高
  • INDUS的高值表明每个城镇的非零售商业英亩比例很高
  • RAD值越低,辐射型公路可达性指标越低
  • RM值越低,说明每栋住宅的房间量越少

我们可以看到,以一种可解释和有意义的方式将一个相对复杂的预测模型(一个额外的树回归器)所做的决定关联起来是多么容易。

5.2 解释i=47,k=5的决策

这里,我们再次要求LIME通过显示有助于所述模型预测的前5个特征来解释第47个测试向量的预测背后的决策。

# Index corresponding to the test vector
i = 47

# Number denoting the top features
k = 5

# Calling the explain_instance method by passing in the:
# 1) ith test vector
# 2) prediction function used by our prediction model('reg' in this case)
# 3) the top features which we want to see, denoted by k
exp_lime = explainer_lime.explain_instance(
	X_test[i], reg.predict, num_features=k)

# Finally visualizing the explanations
exp_lime.show_in_notebook()

输出

Intercept 20.03666971464815
Prediction_local [33.88485397]
Right: 34.323999999999984

在这里插入图片描述
解释输出:

从可视化中,我们可以得出结论,给定矢量所描绘的房屋的相对较高的价格价值(由左侧的条所描绘)可以归因于以下社会经济原因:

  • LSTAT的低值表明在人口、教育和就业能力方面的地位水平高
  • RM的高值表示每个住宅的房间数高
  • TAX值低说明房产税率低
  • PTRATIO值较低表示城镇中的教师学生比例较低
  • AGE值较低,说明建筑物较新
  • INDUS的平均值表明,社会附近的非零售数量较少,在很小程度上降低了房屋的价值。

总结

本文简要介绍了在Python中使用LIME的可解释AI(XAI)。很明显,LIME可以给予我们提供给定黑盒模型决策过程背后更深刻的解释,同时提供对固有数据集的坚实见解。这使得LIME对AI研究人员和数据科学家很有实用价值。

  • 22
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值