|
from numpy.core.records import record |
|
from sentence_transformers import SentenceTransformer |
|
from sklearn.pipeline import make_union |
|
from sklearn.feature_extraction.text import CountVectorizer |
|
from sklearn.base import TransformerMixin |
|
import eli5 |
|
from eli5.lime import TextExplainer |
|
from sklearn.pipeline import Pipeline, make_pipeline |
|
import numpy as np |
|
from sklearn.preprocessing import FunctionTransformer |
|
from sklearn.pipeline import Pipeline |
|
from sklearn.naive_bayes import MultinomialNB |
|
from sklearn.ensemble import RandomForestClassifier |
|
from eli5.formatters import format_as_text, format_as_html |
|
import streamlit as st |
|
import streamlit.components.v1 as components |
|
from sklearn.tree import DecisionTreeClassifier |
|
from datasets import load_dataset |
|
import pandas as pd |
|
from sklearn.cluster import KMeans |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
st.set_page_config(page_title="Interpretable Classification/Clustering") |
|
|
|
st.title("Interpretable Clustering/Classification - by Allen Roush") |
|
|
|
st.caption("Under active development! Please contact me or drop a star/issue on https://github.com/Hellisotherpeople/Active-Explainable-Classification") |
|
|
|
form = st.sidebar.form("choose_settings") |
|
|
|
form.header("Main Settings") |
|
task = form.radio("Which task are we solving?", ('Classification', 'Clustering')) |
|
|
|
dataset_name = form.text_area("Enter the name of the huggingface Dataset to do analysis of:", value = "Hellisotherpeople/DebateSum") |
|
dataset_name_2 = form.text_area("Enter the name of the config for the dataset if it has one", value = "") |
|
split_name = form.text_area("Enter the name of the split of the dataset that you want to use", value = "train") |
|
number_of_records = form.number_input("Enter the number of documents that you want to analyze from the dataset", value = 200) |
|
column_name = form.text_area("Enter the name of the column that we are doing analysis on (the X value)", value = "Full-Document") |
|
|
|
if task == "Classification": |
|
labels_column_name = form.text_area("Enter the name of the column that we are using for labels doing analysis on (the Y value)", value = "OriginalDebateFileName") |
|
|
|
form.form_submit_button("Submit") |
|
|
|
@st.cache |
|
def load_and_process_data(path, name, streaming, split_name, number_of_records): |
|
dataset = load_dataset(path = path, name = name, streaming=streaming) |
|
dataset_head = dataset[split_name].take(number_of_records) |
|
df = pd.DataFrame.from_dict(dataset_head) |
|
return df |
|
|
|
df = load_and_process_data(dataset_name, dataset_name_2, True, split_name, number_of_records) |
|
|
|
display_full_df = form.checkbox("Display the full dataset dataframe?") |
|
display_X_df = form.checkbox("Display the training data?", value = True) |
|
if task == "Classification": |
|
display_y_df = form.checkbox("Display the labels?", value = True) |
|
|
|
with st.expander("Open to see the data"): |
|
if display_full_df: |
|
st.dataframe(df) |
|
if display_X_df: |
|
st.dataframe(df[column_name]) |
|
if task == "Classification": |
|
if display_y_df: |
|
st.dataframe(df[labels_column_name]) |
|
|
|
|
|
|
|
model_name = form.text_area("Enter the name of the pre-trained model from sentence transformers that we are using for featurization", value = "paraphrase-MiniLM-L6-v2") |
|
form.caption("This will download a new model, so it may take awhile or even break if the model is too large") |
|
form.caption("See the list of pre-trained models that are available here! https://www.sbert.net/docs/pretrained_models.html") |
|
|
|
|
|
|
|
|
|
|
|
@st.cache |
|
def load_model_and_return_embedder(model_name): |
|
model = SentenceTransformer(model_name) |
|
embedder = FunctionTransformer(lambda item:model.encode(item, convert_to_numpy=True, show_progress_bar=False)) |
|
return embedder |
|
|
|
embedder = load_model_and_return_embedder(model_name=model_name) |
|
|
|
|
|
|
|
form_classification = st.sidebar.form("classification") |
|
form_classification.header("Classifier Settings") |
|
form_classification.caption("These settings are for the final random forest classification model which is trained with the input being the sentence embeddings from the sentence-transformers model") |
|
form_classification.caption("If in clusteirng mode, this final classification head is run on the cluster labels generated by the clustering. This must be done to make the explanability algorthim work") |
|
n_estimators = form_classification.number_input("How many trees should we use in the random forest classification model? More trees take longer to compute", value = 100) |
|
criterion = form_classification.radio("Which splitting criterion should we use?", ("gini", "entropy")) |
|
min_samples = form_classification.number_input("What's the minimum number of samples required to split the tree?", value = 2) |
|
form_classification.form_submit_button("Submit") |
|
|
|
if task == "Clustering": |
|
form_clustering = st.sidebar.form("clustering") |
|
form_clustering.header("Clustering Settings") |
|
form_clustering.caption("These settings are for the final K-means clustering model which is trained with the input being the sentence embeddings from the sentence-transformers model") |
|
n_clusters = form_clustering.number_input("How many clusters are we looking for?", value = 10) |
|
n_init = form_clustering.number_input("How many times will we run K means with different seeds? Higher is slower but more accurate", value = 10) |
|
max_iter = form_clustering.number_input("How many iteration of K means do we run for each seed? Higher is slower but more accurate", value = 300) |
|
form_clustering.form_submit_button("Submit") |
|
|
|
|
|
text_clf = Pipeline([ |
|
('vect', embedder), |
|
('clf', RandomForestClassifier(n_estimators=n_estimators, criterion = criterion, min_samples_split = min_samples)), |
|
]) |
|
|
|
|
|
|
|
if task == "Clustering": |
|
cluster_clf = Pipeline([ |
|
('vect', embedder), |
|
('cluster', KMeans(n_clusters = n_clusters, n_init = n_init, max_iter = max_iter)), |
|
]) |
|
|
|
|
|
if task == "Classification": |
|
text_clf.fit(df[column_name], df[labels_column_name]) |
|
else: |
|
kmeans = cluster_clf.fit(df[column_name]) |
|
labels = list(cluster_clf['cluster'].labels_) |
|
text_clf.fit(df[column_name], labels) |
|
st.write("Generated Clusters for each example") |
|
st.write(labels) |
|
|
|
|
|
|
|
text_example = """Judge Leon last week questioned the effectiveness of the government's program, asserting that federal officials did not "cite a single instance in which analysis of the NSA’s bulk metadata collection actually stopped an imminent attack." Judge Pauley asserted the exact opposite: "The effectiveness of bulk telephony metadata collection cannot be seriously disputed." |
|
""" |
|
|
|
form_explainer = st.sidebar.form("explainer_form") |
|
form_explainer.header("Explainer Settings") |
|
position_dep = form_explainer.checkbox("Check this if you want to take into account the position of a word in the interpretation", value = False) |
|
number_samples = form_explainer.number_input("Enter the number of explainer peterbuted samples, higher creates a better explanation but takes longer", value = 1000) |
|
char_based = form_explainer.checkbox("Check this if you want to use a character based explanier", value = False) |
|
form_explainer.form_submit_button("Submit") |
|
|
|
|
|
te = TextExplainer(random_state=42, char_based=char_based, n_samples = number_samples, position_dependent=position_dep) |
|
|
|
input_choice = st.checkbox("Check this if you want to enter your own example to explain", value = False) |
|
if input_choice == False: |
|
record_to_explain = st.number_input("Enter the index of the document from the original dataset to interpret", value = 30) |
|
te.fit(df[column_name][record_to_explain], text_clf.predict_proba) |
|
if task == "Classification": |
|
st.write("Ground truth label") |
|
st.write(df[labels_column_name][record_to_explain]) |
|
st.write("Model prediction") |
|
model_prediction = text_clf.predict([df[column_name][record_to_explain]]) |
|
st.write(model_prediction) |
|
else: |
|
st.write("Ground 'truth' label (original cluster)") |
|
st.write(cluster_clf['cluster'].labels_[record_to_explain]) |
|
st.write("model_prediction") |
|
model_prediction = text_clf.predict([df[column_name][record_to_explain]]) |
|
st.write(model_prediction) |
|
else: |
|
record_to_explain = st.text_area("Enter the example document to explain", value = text_example) |
|
te.fit(record_to_explain, text_clf.predict_proba) |
|
if task == "Classification": |
|
st.write("Model prediction") |
|
model_prediction = text_clf.predict([record_to_explain]) |
|
st.write(model_prediction) |
|
else: |
|
st.write("Ground 'truth' label (original cluster)") |
|
st.write(cluster_clf.predict([record_to_explain])) |
|
st.write("model_prediction") |
|
model_prediction = text_clf.predict([record_to_explain]) |
|
st.write(model_prediction) |
|
|
|
|
|
if task == "Classification": |
|
target_feature_names = text_clf['clf'].classes_ |
|
|
|
target_feature_names_list = list(target_feature_names) |
|
t_pred = te.explain_prediction(target_names = target_feature_names_list) |
|
else: |
|
t_pred = te.explain_prediction() |
|
html = format_as_html(t_pred) |
|
|
|
form_html = st.sidebar.form("html_size_form") |
|
form_html.header("Model Explanation Display Settings") |
|
output_width = form_html.number_input("Enter the number of pixels for width of model explanation html display", value = 4000) |
|
output_height = form_html.number_input("Enter the number of pixels for height of model explanation html display", value = 4000) |
|
form_html.form_submit_button("Submit") |
|
st.caption("Scroll to see the full output!") |
|
components.html(html, width = output_width, height = output_height, scrolling = True) |
|
|
|
display_model_explanation_score = st.sidebar.checkbox("Display model explanation score metrics?", value = True) |
|
|
|
if display_model_explanation_score: |
|
st.caption("Scores of model explanation accuracy at explaining the black-box model: From the eli5 docs: https://eli5.readthedocs.io/en/latest/_notebooks/text-explainer.html") |
|
st.caption("‘mean_KL_divergence’ is a mean Kullback–Leibler divergence for all target classes; it is also weighted by distance. KL divergence shows how well are probabilities approximated; 0.0 means a perfect match.") |
|
st.caption("‘score’ is an accuracy score weighted by cosine distance between generated sample and the original document (i.e. texts which are closer to the example are more important). Accuracy shows how good are ‘top 1’ predictions.") |
|
st.write(te.metrics_) |
|
|
|
|