o-l1ru1 commited on
Commit
36e43f0
·
1 Parent(s): d0719c6

Upload 3 files

Browse files
Files changed (3) hide show
  1. README.md +33 -8
  2. app.py +283 -0
  3. requirements.txt +7 -0
README.md CHANGED
@@ -1,12 +1,37 @@
1
  ---
2
- title: Cluster
3
- emoji: 👀
4
- colorFrom: gray
5
- colorTo: yellow
6
- sdk: gradio
7
- sdk_version: 4.4.0
8
  app_file: app.py
9
- pinned: false
10
  ---
11
 
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Interpretable_Text_Classification_And_Clustering
3
+ emoji: 📃➡️🗄️
4
+ colorFrom: green
5
+ colorTo: pink
6
+ sdk: streamlit
 
7
  app_file: app.py
8
+ pinned: True
9
  ---
10
 
11
+ # Configuration
12
+
13
+ `title`: _string_
14
+ Display title for the Space
15
+
16
+ `emoji`: _string_
17
+ Space emoji (emoji-only character allowed)
18
+
19
+ `colorFrom`: _string_
20
+ Color for Thumbnail gradient (red, yellow, green, blue, indigo, purple, pink, gray)
21
+
22
+ `colorTo`: _string_
23
+ Color for Thumbnail gradient (red, yellow, green, blue, indigo, purple, pink, gray)
24
+
25
+ `sdk`: _string_
26
+ Can be either `gradio` or `streamlit`
27
+
28
+ `sdk_version` : _string_
29
+ Only applicable for `streamlit` SDK.
30
+ See [doc](https://hf.co/docs/hub/spaces) for more info on supported versions.
31
+
32
+ `app_file`: _string_
33
+ Path to your main application file (which contains either `gradio` or `streamlit` Python code).
34
+ Path is relative to the root of the repository.
35
+
36
+ `pinned`: _boolean_
37
+ Whether the Space stays on top of your list.
app.py ADDED
@@ -0,0 +1,283 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from numpy.core.records import record
2
+ from sentence_transformers import SentenceTransformer
3
+ from sklearn.pipeline import make_union
4
+ from sklearn.feature_extraction.text import CountVectorizer
5
+ from sklearn.base import TransformerMixin
6
+ import eli5
7
+ from eli5.lime import TextExplainer
8
+ from sklearn.pipeline import Pipeline, make_pipeline
9
+ import numpy as np
10
+ from sklearn.preprocessing import FunctionTransformer
11
+ from sklearn.pipeline import Pipeline
12
+ from sklearn.naive_bayes import MultinomialNB
13
+ from sklearn.ensemble import RandomForestClassifier
14
+ from eli5.formatters import format_as_text, format_as_html
15
+ import streamlit as st
16
+ import streamlit.components.v1 as components
17
+ from sklearn.tree import DecisionTreeClassifier
18
+ from datasets import load_dataset
19
+ import pandas as pd
20
+ from sklearn.cluster import KMeans
21
+
22
+ #TODO: Add support for all clustering algorithms, all classifiers, and all surrogate model classifiers
23
+ #TODO: Performance improvements
24
+ #TODO: Better UI design
25
+ #TODO: Proper QA
26
+
27
+
28
+
29
+ foster_text = """
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
+ We live in an era of terrible preoccupation with presentation and interpretation,
67
+ one in which relations between who someone is and what they believes
68
+ and how they "expresses themself" have been thrown into big time flux.”
69
+
70
+ ― David Foster Wallace,
71
+
72
+ """
73
+
74
+
75
+
76
+ st.set_page_config(page_title="Interpretable Classification/Clustering")
77
+
78
+ st.title("Interpretable Clustering/Classification - by Allen Roush")
79
+
80
+ st.caption("Under active development! Please contact me or drop a star/issue on https://github.com/Hellisotherpeople/Active-Explainable-Classification")
81
+
82
+ with st.expander("Dedicated to the late..."):
83
+ st.text(foster_text)
84
+
85
+ form = st.sidebar.form("choose_settings")
86
+
87
+ form.header("Main Settings")
88
+ task = form.radio("Which task are we solving?", ('Classification', 'Clustering'))
89
+
90
+ dataset_name = form.text_area("Enter the name of the huggingface Dataset to do analysis of:", value = "Hellisotherpeople/DebateSum")
91
+ dataset_name_2 = form.text_area("Enter the name of the config for the dataset if it has one", value = "")
92
+ split_name = form.text_area("Enter the name of the split of the dataset that you want to use", value = "train")
93
+ number_of_records = form.number_input("Enter the number of documents that you want to analyze from the dataset", value = 200)
94
+ column_name = form.text_area("Enter the name of the column that we are doing analysis on (the X value)", value = "Full-Document")
95
+
96
+ if task == "Classification":
97
+ 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")
98
+
99
+ form.form_submit_button("Submit")
100
+
101
+ @st.cache
102
+ def load_and_process_data(path, name, streaming, split_name, number_of_records):
103
+ dataset = load_dataset(path = path, name = name, streaming=streaming)
104
+ dataset_head = dataset[split_name].take(number_of_records)
105
+ df = pd.DataFrame.from_dict(dataset_head)
106
+ return df
107
+
108
+ df = load_and_process_data(dataset_name, dataset_name_2, True, split_name, number_of_records)
109
+
110
+ display_full_df = form.checkbox("Display the full dataset dataframe?")
111
+ display_X_df = form.checkbox("Display the training data?", value = True)
112
+ if task == "Classification":
113
+ display_y_df = form.checkbox("Display the labels?", value = True)
114
+
115
+ with st.expander("Open to see the data"):
116
+ if display_full_df:
117
+ st.dataframe(df)
118
+ if display_X_df:
119
+ st.dataframe(df[column_name])
120
+ if task == "Classification":
121
+ if display_y_df:
122
+ st.dataframe(df[labels_column_name])
123
+
124
+
125
+
126
+ 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")
127
+ form.caption("This will download a new model, so it may take awhile or even break if the model is too large")
128
+ form.caption("See the list of pre-trained models that are available here! https://www.sbert.net/docs/pretrained_models.html")
129
+
130
+ #embeddings = model.encode(sentences, convert_to_numpy = True)
131
+
132
+
133
+
134
+ @st.cache
135
+ def load_model_and_return_embedder(model_name):
136
+ model = SentenceTransformer(model_name)
137
+ embedder = FunctionTransformer(lambda item:model.encode(item, convert_to_numpy=True, show_progress_bar=False))
138
+ return embedder
139
+
140
+ embedder = load_model_and_return_embedder(model_name=model_name)
141
+
142
+
143
+
144
+ form_classification = st.sidebar.form("classification")
145
+ form_classification.header("Classifier Settings")
146
+ 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")
147
+ 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")
148
+ 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)
149
+ criterion = form_classification.radio("Which splitting criterion should we use?", ("gini", "entropy"))
150
+ min_samples = form_classification.number_input("What's the minimum number of samples required to split the tree?", value = 2)
151
+ form_classification.form_submit_button("Submit")
152
+
153
+ if task == "Clustering":
154
+ form_clustering = st.sidebar.form("clustering")
155
+ form_clustering.header("Clustering Settings")
156
+ 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")
157
+ n_clusters = form_clustering.number_input("How many clusters are we looking for?", value = 10)
158
+ 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)
159
+ 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)
160
+ form_clustering.form_submit_button("Submit")
161
+
162
+
163
+ text_clf = Pipeline([
164
+ ('vect', embedder),
165
+ ('clf', RandomForestClassifier(n_estimators=n_estimators, criterion = criterion, min_samples_split = min_samples)),
166
+ ])
167
+
168
+
169
+
170
+ if task == "Clustering":
171
+ cluster_clf = Pipeline([
172
+ ('vect', embedder),
173
+ ('cluster', KMeans(n_clusters = n_clusters, n_init = n_init, max_iter = max_iter)),
174
+ ])
175
+
176
+ @st.cache(allow_output_mutation=True)
177
+ def fit_text_clf(X, y):
178
+ text_clf.fit(X, y)
179
+ return text_clf
180
+
181
+ @st.cache(allow_output_mutation=True)
182
+ def fit_cluster_clf(X):
183
+ cluster_clf.fit(X)
184
+ return cluster_clf
185
+
186
+
187
+ if task == "Classification":
188
+ #text_clf.fit(df[column_name], df[labels_column_name])
189
+ text_clf = fit_text_clf(df[column_name], df[labels_column_name])
190
+ else:
191
+ #kmeans = cluster_clf.fit(df[column_name])
192
+ cluster_clf = fit_cluster_clf(df[column_name])
193
+ kmeans = cluster_clf
194
+ labels = list(cluster_clf['cluster'].labels_)
195
+ #text_clf.fit(df[column_name], labels)
196
+ text_clf = fit_text_clf(df[column_name], labels)
197
+ st.write("Generated Clusters for each example")
198
+ st.write(labels)
199
+
200
+
201
+
202
+ 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."
203
+ """
204
+
205
+ form_explainer = st.sidebar.form("explainer_form")
206
+ form_explainer.header("Explainer Settings")
207
+ position_dep = form_explainer.checkbox("Check this if you want to take into account the position of a word in the interpretation", value = False)
208
+ number_samples = form_explainer.number_input("Enter the number of explainer perpetuated samples, higher creates a better explanation but takes longer", value = 200)
209
+ char_based = form_explainer.checkbox("Check this if you want to use a character based explainer", value = False)
210
+ top_features = form_explainer.number_input("Enter the top number of features we want to show", value = 50)
211
+ top_targets = form_explainer.number_input("Enter the top number of targets we want to show explanations of", value = 5)
212
+ form_explainer.form_submit_button("Submit")
213
+
214
+
215
+ te = TextExplainer(random_state=42, char_based=char_based, n_samples = number_samples, position_dependent=position_dep)
216
+
217
+ @st.cache(allow_output_mutation=True) ##Seems to break shit :(
218
+ def fit_text_explainer(X, predict_proba):
219
+ te.fit(X, predict_proba)
220
+ return te
221
+
222
+ input_choice = st.checkbox("Check this if you want to enter your own example to explain", value = False)
223
+ if input_choice == False:
224
+ record_to_explain = st.number_input("Enter the index of the document from the original dataset to interpret", value = 30)
225
+ te.fit(df[column_name][record_to_explain], text_clf.predict_proba)
226
+ #te = fit_text_explainer(df[column_name][record_to_explain], text_clf.predict_proba)
227
+ if task == "Classification":
228
+ st.write("Ground truth label")
229
+ st.write(df[labels_column_name][record_to_explain])
230
+ st.write("Model prediction")
231
+ model_prediction = text_clf.predict([df[column_name][record_to_explain]])
232
+ st.write(model_prediction)
233
+ else:
234
+ st.write("Ground 'truth' label (original cluster)")
235
+ st.write(cluster_clf['cluster'].labels_[record_to_explain])
236
+ st.write("model_prediction")
237
+ model_prediction = text_clf.predict([df[column_name][record_to_explain]])
238
+ st.write(model_prediction)
239
+ else:
240
+ record_to_explain = st.text_area("Enter the example document to explain", value = text_example)
241
+ te.fit(record_to_explain, text_clf.predict_proba)
242
+ #te = fit_text_explainer(record_to_explain, text_clf.predict_proba)
243
+ if task == "Classification":
244
+ st.write("Model prediction")
245
+ model_prediction = text_clf.predict([record_to_explain])
246
+ st.write(model_prediction)
247
+ else:
248
+ st.write("Ground 'truth' label (original cluster)")
249
+ st.write(cluster_clf.predict([record_to_explain]))
250
+ st.write("model_prediction")
251
+ model_prediction = text_clf.predict([record_to_explain])
252
+ st.write(model_prediction)
253
+
254
+
255
+ if task == "Classification":
256
+ target_feature_names = text_clf['clf'].classes_
257
+ #target_feature_names = pd.unique(df[labels_column_name])
258
+ target_feature_names_list = list(target_feature_names)
259
+ try:
260
+ t_pred = te.explain_prediction(target_names = target_feature_names_list, top = top_features, top_targets = top_targets)
261
+ except TypeError:
262
+ st.error("Unable to get target label names - most likely due to a numeric label feature type")
263
+ t_pred = te.explain_prediction(top = top_features, top_targets = top_targets)
264
+ else:
265
+ t_pred = te.explain_prediction(top = top_features, top_targets = top_targets)
266
+ html = format_as_html(t_pred)
267
+
268
+ form_html = st.sidebar.form("html_size_form")
269
+ form_html.header("Model Explanation Display Settings")
270
+ output_width = form_html.number_input("Enter the number of pixels for width of model explanation html display", value = 800)
271
+ output_height = form_html.number_input("Enter the number of pixels for height of model explanation html display", value = 2000)
272
+ form_html.form_submit_button("Submit")
273
+ st.caption("Scroll to see the full output!")
274
+ components.html(html, width = output_width, height = output_height, scrolling = True)
275
+
276
+ display_model_explanation_score = st.sidebar.checkbox("Display model explanation score metrics?", value = True)
277
+
278
+ if display_model_explanation_score:
279
+ 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")
280
+ 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.")
281
+ 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.")
282
+ st.write(te.metrics_)
283
+
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ altair<5
2
+ scikit-learn
3
+ scipy
4
+ sentence-transformers
5
+ eli5
6
+ pandas
7
+ datasets