File size: 10,629 Bytes
ff2b709 a13d7ed ff2b709 e08a900 ff2b709 e08a900 ff2b709 e08a900 ff2b709 e08a900 ff2b709 e08a900 ff2b709 e08a900 ff2b709 e08a900 ff2b709 e08a900 ff2b709 b2644a1 ff2b709 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 |
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
#TODO: Add support for all clustering algorithms, all classifiers, and all surrogate model classifiers
#TODO: Performance improvements
#TODO: Better UI design
#TODO: Proper QA
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")
#embeddings = model.encode(sentences, convert_to_numpy = True)
@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 = pd.unique(df[labels_column_name])
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_)
|