Advertisement

对于已交付(客户流失预警)模型的模型可解释LIME

阅读量:

目录

介绍:

数据:

数据处理:

随机森林建模:

LIME

例一:

例二:

介绍:

LIME(Local Interpretable Model-agnostic Explanations)是一种用于解析机器学习模型的方法。它通过创建一个可解释性模型来揭示黑箱模型的预测机制。LIME的核心理念在于在局部区域生成一组代表性的样本数据集,并利用可解释性模型对这些样本进行近似拟合以逼近黑箱模型的行为特征。通过对局部样本预测结果的深入剖析与解读,LIME不仅能够揭示黑箱模型决策的本质规律,并且能够系统地提供各单个特征对最终预测结果的影响度分析。基于此方法,LIME在图像分类、自然语言处理以及各种机器学习应用场景中都被成功应用于提升模型透明度与可 interpretability。

复制代码
 LIME的核心函数是`lime.lime_tabular.LimeTabularExplainer`,它用于解释基于表格数据的模型。这个函数有以下参数:

    
  
    
 - `training_data`: 用于训练解释模型的样本数据。
    
 - `feature_names`: 具有特征名称的特征的列表。
    
 - `class_names`: 目标变量的名称。
    
 - `mode`: 解释模型的模式,默认为 "classification",也可以设置为 "regression"。
    
 - `discretize_continuous`: 是否对连续特征进行离散化,默认为 True。
    
 - `discretizer`: 离散化连续特征的方法,默认为 "quartile"。
    
 - `feature_selection`: 用于选择最重要特征的方法,默认为 "auto"。
    
 - `kernel_width`: 连续特征离散化后的宽度,默认为 None。
    
 - `verbose`: 控制详细程度的标志,默认为 False。
    
  
    
 另外,使用`explain_instance`函数可以为给定的实例解释模型的预测结果。这个函数有以下参数:
    
  
    
 - `data_row`: 要解释的实例数据。
    
 - `predict_fn`: 用于预测的函数。
    
 - `num_features`: 返回解释结果中重要特征的数量,默认为 10。
    
 - `top_labels`: 返回解释结果中预测结果的数量,默认为 1。
    
 - `labels`: 预测结果的标签。
    
 - `categorical_features`: 类别型特征的索引。
    
 - `categorical_names`: 类别型特征的名称。
    
  
    
 这些函数是LIME的核心组成部分,帮助我们解释机器学习模型的预测结果。
    
    
    
    
    python
    
    
![](https://ad.itadn.com/c/weblog/blog-img/images/2025-08-18/Lq9sHa3PtMrmGBIE6eODQNvdlchX.png)

数据:

复制代码
 # Importing the libraries

    
 import numpy as np
    
 import matplotlib.pyplot as plt
    
 import pandas as pd
    
  
    
 # Importing the dataset
    
 data = pd.read_csv('Churn_Modelling.csv')
    
 X = data.iloc[:, 3:13]
    
 y = data.iloc[:, 13]
    
  
    
 data.isnull().sum()
    
 '''
    
 RowNumber          0
    
 CustomerId         0
    
 Surname            0
    
 CreditScore        0
    
 Geography          0
    
 Gender             0
    
 Age                0
    
 Tenure             0
    
 Balance            0
    
 NumOfProducts      0
    
 HasCrCard          0
    
 IsActiveMember     0
    
 EstimatedSalary    0
    
 Exited             0
    
 dtype: int64
    
 '''
    
 data
    
    
    
    
    python
    
    
![](https://ad.itadn.com/c/weblog/blog-img/images/2025-08-18/JO6HYxIEsTu0jFno5cbLqRSXNZfU.png)

数据处理:

复制代码
 #Create dummy variables 机器不能识别字符,转为数字

    
 geography=pd.get_dummies(X["Geography"],drop_first=True)
    
 gender=pd.get_dummies(X['Gender'],drop_first=True)
    
  
    
 ## Concatenate the Data Frames
    
  
    
 X=pd.concat([X,geography,gender],axis=1)
    
  
    
 ## Drop Unnecessary columns
    
 X=X.drop(['Geography','Gender'],axis=1)
    
    
    
    
    python
    
    
![](https://ad.itadn.com/c/weblog/blog-img/images/2025-08-18/TuNKHcdzDIm9hBiV5ArXasZkWq7U.png)

随机森林建模:

复制代码
 # Splitting the dataset into the Training set and Test set

    
 from sklearn.model_selection import train_test_split
    
 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 0)
    
  
    
 from sklearn.ensemble import RandomForestClassifier
    
 classifier=RandomForestClassifier()
    
 classifier.fit(X_train,y_train)
    
  
    
 y_pred=classifier.predict(X_test)
    
 #Import scikit-learn metrics module for accuracy calculation
    
 from sklearn import metrics
    
  
    
 # Model Accuracy, how often is the classifier correct?
    
 print("Accuracy:",metrics.accuracy_score(y_test, y_pred))
    
 #结果:Accuracy: 0.8646666666666667
    
    
    
    
    python
    
    
![](https://ad.itadn.com/c/weblog/blog-img/images/2025-08-18/7wl1YgyqkREUsuxWALoK9fmvr5cD.png)

LIME

复制代码
 import pickle

    
 pickle.dump(classifier, open("classifier.pkl", 'wb'))
    
  
    
 classifier1=pd.read_pickle('classifier.pkl')
    
  
    
 import lime
    
 from lime import lime_tabular
    
  
    
 interpretor = lime_tabular.LimeTabularExplainer(
    
     training_data=np.array(X_train),#用于训练解释模型的样本数据。
    
     feature_names=X_train.columns,#具有特征名称的特征的列表。
    
     mode='classification'#解释模型的模式,默认为 "classification",也可以设置为 "regression"。
    
 )
    
  
    
 # feature importance of the random forest model
    
 feature_importance = pd.DataFrame()
    
 feature_importance['variable'] = X_train.columns
    
 feature_importance['importance'] = classifier1.feature_importances_
    
  
    
 # feature_importance values in descending order
    
 feature_importance.sort_values(by='importance', ascending=False).head(10)#该模型权重
    
    
    
    
    python
    
    
![](https://ad.itadn.com/c/weblog/blog-img/images/2025-08-18/fueOvQTalCb9nkzhgwBARZMy4KDY.png)

例一:

复制代码
 X_test.iloc[88]

    
 '''结果:
    
 CreditScore           756.00
    
 Age                    39.00
    
 Tenure                  3.00
    
 Balance            100717.85
    
 NumOfProducts           3.00
    
 HasCrCard               1.00
    
 IsActiveMember          1.00
    
 EstimatedSalary     73406.04
    
 Germany                 1.00
    
 Spain                   0.00
    
 Male                    0.00
    
 Name: 1096, dtype: float64
    
 '''
    
  
    
 print('prediction: {}'.format(classifier1.predict(X_test.iloc[[88],:])))
    
 #结果:prediction: [1]
    
  
    
 exp = interpretor.explain_instance(
    
     data_row=X_test.iloc[88], ##new data要解释的实例数据
    
     predict_fn=classifier1.predict_proba#: 用于预测的函数。
    
 )
    
  
    
 exp.show_in_notebook(show_table=True)#该人可能属于流失或不流失的概率及各特征占比可能性
    
    
    
    
    python
    
    
![](https://ad.itadn.com/c/weblog/blog-img/images/2025-08-18/jiI5hS2QZu8wGoWcrvbKfOLx9sda.png)
复制代码
    exp.as_pyplot_figure()
    
    python

例二:

复制代码
 exp = interpretor.explain_instance(

    
     data_row=X_test.iloc[2], ##new data
    
     predict_fn=classifier1.predict_proba,
    
     num_features=10
    
 )
    
  
    
 X_test.iloc[2]
    
 '''结果:
    
 CreditScore          706.00
    
 Age                   42.00
    
 Tenure                 8.00
    
 Balance            95386.82
    
 NumOfProducts          1.00
    
 HasCrCard              1.00
    
 IsActiveMember         1.00
    
 EstimatedSalary    75732.25
    
 Germany                0.00
    
 Spain                  1.00
    
 Male                   0.00
    
 Name: 2398, dtype: float64
    
 '''
    
  
    
 exp.show_in_notebook(show_table=True,show_all=False)
    
    
    
    
    python
    
    
![](https://ad.itadn.com/c/weblog/blog-img/images/2025-08-18/rV8Z5aj6EICywdDBxuOKJSzG1kYl.png)
复制代码
    exp.as_pyplot_figure()
    
    python
复制代码
 exp.as_list()

    
 '''结果:
    
 [('0.00 < IsActiveMember <= 1.00', -0.11661097094408614),
    
  ('NumOfProducts <= 1.00', 0.08686460877739129),
    
  ('Male <= 0.00', 0.043159886277428304),
    
  ('Germany <= 0.00', -0.029197882161009953),
    
  ('652.00 < CreditScore <= 719.00', -0.022598898299313823),
    
  ('50910.68 < EstimatedSalary <= 99954.45', -0.01532003910694092),
    
  ('Spain > 0.00', 0.013041709019348565),
    
  ('37.00 < Age <= 44.00', -0.009812578647407045),
    
  ('0.00 < HasCrCard <= 1.00', -0.008498455231089774),
    
  ('Tenure > 7.00', -0.0038766005937966638)]
    
   14. ​
    
 '''
    
    
    
    
    python
    
    
![](https://ad.itadn.com/c/weblog/blog-img/images/2025-08-18/9y1MI2TcPz5fNvLYORhuapGbVxDK.png)

全部评论 (0)

还没有任何评论哟~