{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "### LIME for text classification" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This is an example of the LIME explainer on text classification. If using this explainer, please cite the original work: https://github.com/marcotcr/lime." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "import sklearn.ensemble\n", "from sklearn.datasets import fetch_20newsgroups\n", "\n", "from omnixai.data.text import Text\n", "from omnixai.explainers.nlp import LimeText\n", "from omnixai.preprocessing.text import Tfidf" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We use a `Text` object to represent a batch of texts/sentences. The package `omnixai.preprocessing.text` provides some transforms related to text data such as `Tfidf`." ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "# Load the training and text datasets\n", "categories = ['alt.atheism', 'soc.religion.christian']\n", "newsgroups_train = fetch_20newsgroups(subset='train', categories=categories)\n", "newsgroups_test = fetch_20newsgroups(subset='test', categories=categories)\n", "\n", "x_train = Text(newsgroups_train.data)\n", "y_train = newsgroups_train.target\n", "x_test = Text(newsgroups_test.data)\n", "y_test = newsgroups_test.target\n", "class_names = ['atheism', 'christian']\n", "# A TFDIF transform\n", "transform = Tfidf().fit(x_train)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For this classification task, we train a random forest classifier with TF-IDF feature vectors." ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Test accuracy: 0.9230769230769231\n" ] } ], "source": [ "train_vectors = transform.transform(x_train)\n", "test_vectors = transform.transform(x_test)\n", "model = sklearn.ensemble.RandomForestClassifier(n_estimators=500)\n", "model.fit(train_vectors, y_train)\n", "predict_function = lambda x: model.predict_proba(transform.transform(x))\n", "\n", "predictions = model.predict(test_vectors)\n", "print('Test accuracy: {}'.format(\n", " sklearn.metrics.f1_score(y_test, predictions, average='binary')))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To initialize `LimeText`, we need to set the following parameters:\n", "\n", " - `predict_function`: The prediction function corresponding to the machine learning model to explain. For classification tasks, the outputs of the `predict_function` are the class probabilities." ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/html": [ "