Registry / ai-ml / lime
library0.2.0.1pypypi✓ verified 85d ago

LIME (Local Interpretable Model-agnostic Explanations) is a Python library designed to explain individual predictions of machine learning classifiers and regressors. It works for tabular, text, and image data by building local, interpretable surrogate models around the instance to be explained. The current version is 0.2.0.1 and the library is actively maintained.

pip install lime
INSTALL
IMPORT
SIG · LIME
L
lime
ai-mlpythonv0.2.0.1
Install
16.9s avg
Import
3541ms
Disk
427MB
Pass rate
5/ 10
Env Coverage5 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v0.2.0.1 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.920 runs
build_error
glibc
py 3.103.920 runs
installs and imports cleanly · install 16.9s · import 3.541s · 412MB
427MB installed
● package 427MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

LimeTabularExplainer
from lime.lime_tabular import LimeTabularExplainer
from lime import LimeTabularExplainer
Explainer classes are located within sub-modules (e.g., lime_tabular, lime_text, lime_image), not directly under the top-level 'lime' package.
LimeTextExplainer
from lime.lime_text import LimeTextExplainer
Explainer classes are located within sub-modules (e.g., lime_tabular, lime_text, lime_image), not directly under the top-level 'lime' package.
LimeImageExplainer
from lime.lime_image import LimeImageExplainer
Explainer classes are located within sub-modules (e.g., lime_tabular, lime_text, lime_image), not directly under the top-level 'lime' package.

This quickstart demonstrates how to use `LimeTabularExplainer` to explain an individual prediction from a scikit-learn RandomForestClassifier on the Iris dataset. It covers data preparation, model training, explainer initialization, and generating/displaying the explanation.

import numpy as np import sklearn import sklearn.ensemble from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split import lime import lime.lime_tabular # 1. Prepare Data and Model iris = load_iris() X = iris.data y = iris.target feature_names = iris.feature_names class_names = iris.target_names X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) model = sklearn.ensemble.RandomForestClassifier(n_estimators=100, random_state=42) model.fit(X_train, y_train) # 2. Create a LIME Explainer for Tabular Data explainer = lime.lime_tabular.LimeTabularExplainer( training_data=X_train, feature_names=feature_names, class_names=class_names, mode='classification' ) # 3. Choose an instance to explain i = np.random.randint(0, X_test.shape[0]) instance_to_explain = X_test[i] # 4. Generate the explanation explanation = explainer.explain_instance( data_row=instance_to_explain, predict_fn=model.predict_proba, num_features=2 ) # 5. Print the explanation print(f"Explaining instance: {instance_to_explain}") print(f"Predicted class: {iris.target_names[model.predict(instance_to_explain.reshape(1, -1))[0]]}") print("--- Local Explanation ---") print(explanation.as_list()) # For visualization in a Jupyter Notebook: # explanation.show_in_notebook(show_table=True)
Debug
Known issues
breakingPython 2 support was dropped in version 0.2.0.0. LIME now requires Python 3.5 or newer.
fix
Ensure your project uses Python 3.5 or a later version. Upgrade your Python environment if necessary.
affects: >=0.2.0.0
gotchaFor `LimeTabularExplainer`, `training_data` is crucial. It is used to compute statistics (mean, std dev, frequencies) for feature perturbation and discretization. Providing a non-representative or empty `training_data` can lead to inaccurate or misleading explanations.
fix
Always provide `LimeTabularExplainer` with a representative sample of your training data (as a NumPy array) to ensure accurate feature statistics are calculated.
affects: All versions
gotchaThe `predict_fn` passed to `explain_instance` must return probabilities for classification tasks (e.g., `model.predict_proba`) and raw predicted values for regression tasks (e.g., `model.predict`). Mismatching this can cause errors or incorrect explanations.
fix
Verify that your `predict_fn` matches the expected output type for LIME based on your model's task (probabilities for classification, raw values for regression).
affects: All versions
gotchaLIME explanations can be sensitive to hyperparameters like `num_samples` (number of perturbed samples) and the choice of distance metric, potentially leading to varied or unstable explanations across runs or slight changes in settings.
fix
Experiment with different hyperparameters to assess the stability of explanations. Consider the theoretical limitations and potential for local instability, especially in high-dimensional or complex feature spaces.
affects: All versions
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'lime'
The 'lime' library is not installed in your current Python environment or the environment where you are trying to run your code.
fix
Install the 'lime' library using pip: `pip install lime`
ModuleNotFoundError: No module named 'lime.lime_tabular'
This error often occurs when the 'lime' library is either not installed correctly, or there's a conflict in the Python environment, or an attempt to import a submodule directly without the main package being properly recognized. It can also happen when `pip install lime` wasn't run, or if the installed `lime` package structure is unexpected.
fix
First, ensure 'lime' is installed: `pip install lime`. If it's already installed, try upgrading: `pip install --upgrade lime`. If the issue persists, consider creating a new virtual environment and reinstalling `lime` within it. For imports, typically `from lime.lime_tabular import LimeTabularExplainer` is correct, but ensure `lime` itself is accessible.
NotImplementedError: LIME does not currently support classifier models without probability scores.
LIME's `explain_instance` method for classification tasks requires the model's prediction function (`predict_fn`) to return probability scores (e.g., from `model.predict_proba`), not direct class predictions (e.g., from `model.predict`).
fix
Provide a prediction function that outputs probabilities (an array where each row sums to 1). For scikit-learn classifiers, use `model.predict_proba`. Example: `explainer.explain_instance(data_row, model.predict_proba, num_features=5)`
TypeError: unhashable type: 'slice'
This error typically arises when `LimeTabularExplainer` receives a Pandas DataFrame as `training_data` or `data_row` when it expects a NumPy array. LIME expects certain inputs to be in a NumPy array format for internal operations.
fix
Convert your Pandas DataFrame to a NumPy array before passing it to the explainer: `explainer = lime.lime_tabular.LimeTabularExplainer(X_train.values, ...)` and `exp = explainer.explain_instance(X_test_instance.values, ...)`
AttributeError: 'DMatrix' object has no attribute 'shape'
This error occurs when trying to use `LimeTabularExplainer` with an XGBoost model by passing an `xgboost.DMatrix` object directly as `data_row` or `training_data`. LIME's tabular explainer expects a NumPy array, not a `DMatrix`.
fix
Convert your `xgboost.DMatrix` object back to a NumPy array (or the original feature array) before passing it to `LimeTabularExplainer` or `explain_instance`. For example, if you have `xgb_data = xgb.DMatrix(X_numpy_array)`, then use `X_numpy_array` directly with LIME.
Upgrade
Version history
0.2.0.1latest on PyPI · released Jun 26, 2020
Audit
Dependencies
numpyrequiredEssential for data manipulation, especially with tabular data explainers.
scikit-learnrequiredCommonly used for training models that LIME then explains; many examples rely on it.
Agent activity
6 hits · last 30 days
node
6
Resources