Rainsilves commited on
Commit
e08a900
1 Parent(s): ee8a91d

fixed name of app

Browse files
Files changed (2) hide show
  1. app.py +19 -11
  2. interpretable_text_clustering.py +0 -206
app.py CHANGED
@@ -31,7 +31,6 @@ st.set_page_config(page_title="Interpretable Classification/Clustering")
31
  st.title("Interpretable Clustering/Classification - by Allen Roush")
32
 
33
  st.caption("Under active development! Please contact me or drop a star/issue on https://github.com/Hellisotherpeople/Active-Explainable-Classification")
34
- st.caption("Note, use the huggingface LIGHT theme for best results")
35
 
36
  form = st.sidebar.form("choose_settings")
37
 
@@ -41,7 +40,7 @@ task = form.radio("Which task are we solving?", ('Classification', 'Clustering')
41
  dataset_name = form.text_area("Enter the name of the huggingface Dataset to do analysis of:", value = "Hellisotherpeople/DebateSum")
42
  dataset_name_2 = form.text_area("Enter the name of the config for the dataset if it has one", value = "")
43
  split_name = form.text_area("Enter the name of the split of the dataset that you want to use", value = "train")
44
- number_of_records = form.number_input("Enter the number of documents that you want to analyze from the dataset", value = 200)
45
  column_name = form.text_area("Enter the name of the column that we are doing analysis on (the X value)", value = "Full-Document")
46
 
47
  if task == "Classification":
@@ -49,10 +48,14 @@ if task == "Classification":
49
 
50
  form.form_submit_button("Submit")
51
 
 
 
 
 
 
 
52
 
53
- dataset = load_dataset(path = dataset_name, name = dataset_name_2, streaming=True)
54
- dataset_head = dataset[split_name].take(number_of_records)
55
- df = pd.DataFrame.from_dict(dataset_head)
56
 
57
  display_full_df = form.checkbox("Display the full dataset dataframe?")
58
  display_X_df = form.checkbox("Display the training data?", value = True)
@@ -74,13 +77,17 @@ model_name = form.text_area("Enter the name of the pre-trained model from senten
74
  form.caption("This will download a new model, so it may take awhile or even break if the model is too large")
75
  form.caption("See the list of pre-trained models that are available here! https://www.sbert.net/docs/pretrained_models.html")
76
 
77
- model = SentenceTransformer(model_name)
78
 
79
 
80
 
81
- #embeddings = model.encode(sentences, convert_to_numpy = True)
 
 
 
 
82
 
83
- embedder = FunctionTransformer(lambda item:model.encode(item, convert_to_numpy=True, show_progress_bar=False))
84
 
85
 
86
 
@@ -115,6 +122,7 @@ if task == "Clustering":
115
  ('vect', embedder),
116
  ('cluster', KMeans(n_clusters = n_clusters, n_init = n_init, max_iter = max_iter)),
117
  ])
 
118
 
119
  if task == "Classification":
120
  text_clf.fit(df[column_name], df[labels_column_name])
@@ -133,7 +141,7 @@ text_example = """Judge Leon last week questioned the effectiveness of the gover
133
  form_explainer = st.sidebar.form("explainer_form")
134
  form_explainer.header("Explainer Settings")
135
  position_dep = form_explainer.checkbox("Check this if you want to take into account the position of a word in the interpretation", value = False)
136
- number_samples = form_explainer.number_input("Enter the number of explainer peterbuted samples, higher creates a better explanation but takes longer", value = 5000)
137
  char_based = form_explainer.checkbox("Check this if you want to use a character based explanier", value = False)
138
  form_explainer.form_submit_button("Submit")
139
 
@@ -142,7 +150,7 @@ te = TextExplainer(random_state=42, char_based=char_based, n_samples = number_sa
142
 
143
  input_choice = st.checkbox("Check this if you want to enter your own example to explain", value = False)
144
  if input_choice == False:
145
- record_to_explain = st.number_input("Enter the index of the document from the original dataset to interpret", value = 151)
146
  te.fit(df[column_name][record_to_explain], text_clf.predict_proba)
147
  if task == "Classification":
148
  st.write("Ground truth label")
@@ -183,7 +191,7 @@ html = format_as_html(t_pred)
183
  form_html = st.sidebar.form("html_size_form")
184
  form_html.header("Model Explanation Display Settings")
185
  output_width = form_html.number_input("Enter the number of pixels for width of model explanation html display", value = 1920)
186
- output_height = form_html.number_input("Enter the number of pixels for height of model explanation html display", value = 3000)
187
  form_html.form_submit_button("Submit")
188
  st.caption("Scroll to see the full output!")
189
  components.html(html, width = output_width, height = output_height, scrolling = True)
 
31
  st.title("Interpretable Clustering/Classification - by Allen Roush")
32
 
33
  st.caption("Under active development! Please contact me or drop a star/issue on https://github.com/Hellisotherpeople/Active-Explainable-Classification")
 
34
 
35
  form = st.sidebar.form("choose_settings")
36
 
 
40
  dataset_name = form.text_area("Enter the name of the huggingface Dataset to do analysis of:", value = "Hellisotherpeople/DebateSum")
41
  dataset_name_2 = form.text_area("Enter the name of the config for the dataset if it has one", value = "")
42
  split_name = form.text_area("Enter the name of the split of the dataset that you want to use", value = "train")
43
+ number_of_records = form.number_input("Enter the number of documents that you want to analyze from the dataset", value = 50)
44
  column_name = form.text_area("Enter the name of the column that we are doing analysis on (the X value)", value = "Full-Document")
45
 
46
  if task == "Classification":
 
48
 
49
  form.form_submit_button("Submit")
50
 
51
+ @st.cache
52
+ def load_and_process_data(path, name, streaming, split_name, number_of_records):
53
+ dataset = load_dataset(path = path, name = name, streaming=streaming)
54
+ dataset_head = dataset[split_name].take(number_of_records)
55
+ df = pd.DataFrame.from_dict(dataset_head)
56
+ return df
57
 
58
+ df = load_and_process_data(dataset_name, dataset_name_2, True, split_name, number_of_records)
 
 
59
 
60
  display_full_df = form.checkbox("Display the full dataset dataframe?")
61
  display_X_df = form.checkbox("Display the training data?", value = True)
 
77
  form.caption("This will download a new model, so it may take awhile or even break if the model is too large")
78
  form.caption("See the list of pre-trained models that are available here! https://www.sbert.net/docs/pretrained_models.html")
79
 
80
+ #embeddings = model.encode(sentences, convert_to_numpy = True)
81
 
82
 
83
 
84
+ @st.cache
85
+ def load_model_and_return_embedder(model_name):
86
+ model = SentenceTransformer(model_name)
87
+ embedder = FunctionTransformer(lambda item:model.encode(item, convert_to_numpy=True, show_progress_bar=False))
88
+ return embedder
89
 
90
+ embedder = load_model_and_return_embedder(model_name=model_name)
91
 
92
 
93
 
 
122
  ('vect', embedder),
123
  ('cluster', KMeans(n_clusters = n_clusters, n_init = n_init, max_iter = max_iter)),
124
  ])
125
+
126
 
127
  if task == "Classification":
128
  text_clf.fit(df[column_name], df[labels_column_name])
 
141
  form_explainer = st.sidebar.form("explainer_form")
142
  form_explainer.header("Explainer Settings")
143
  position_dep = form_explainer.checkbox("Check this if you want to take into account the position of a word in the interpretation", value = False)
144
+ number_samples = form_explainer.number_input("Enter the number of explainer peterbuted samples, higher creates a better explanation but takes longer", value = 1000)
145
  char_based = form_explainer.checkbox("Check this if you want to use a character based explanier", value = False)
146
  form_explainer.form_submit_button("Submit")
147
 
 
150
 
151
  input_choice = st.checkbox("Check this if you want to enter your own example to explain", value = False)
152
  if input_choice == False:
153
+ record_to_explain = st.number_input("Enter the index of the document from the original dataset to interpret", value = 30)
154
  te.fit(df[column_name][record_to_explain], text_clf.predict_proba)
155
  if task == "Classification":
156
  st.write("Ground truth label")
 
191
  form_html = st.sidebar.form("html_size_form")
192
  form_html.header("Model Explanation Display Settings")
193
  output_width = form_html.number_input("Enter the number of pixels for width of model explanation html display", value = 1920)
194
+ output_height = form_html.number_input("Enter the number of pixels for height of model explanation html display", value = 2000)
195
  form_html.form_submit_button("Submit")
196
  st.caption("Scroll to see the full output!")
197
  components.html(html, width = output_width, height = output_height, scrolling = True)
interpretable_text_clustering.py DELETED
@@ -1,206 +0,0 @@
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
- st.set_page_config(page_title="Interpretable Classification/Clustering")
30
-
31
- st.title("Interpretable Clustering/Classification - by Allen Roush")
32
-
33
- st.caption("Under active development! Please contact me or drop a star/issue on https://github.com/Hellisotherpeople/Active-Explainable-Classification")
34
-
35
- form = st.sidebar.form("choose_settings")
36
-
37
- form.header("Main Settings")
38
- task = form.radio("Which task are we solving?", ('Classification', 'Clustering'))
39
-
40
- dataset_name = form.text_area("Enter the name of the huggingface Dataset to do analysis of:", value = "Hellisotherpeople/DebateSum")
41
- dataset_name_2 = form.text_area("Enter the name of the config for the dataset if it has one", value = "")
42
- split_name = form.text_area("Enter the name of the split of the dataset that you want to use", value = "train")
43
- number_of_records = form.number_input("Enter the number of documents that you want to analyze from the dataset", value = 50)
44
- column_name = form.text_area("Enter the name of the column that we are doing analysis on (the X value)", value = "Full-Document")
45
-
46
- if task == "Classification":
47
- 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")
48
-
49
- form.form_submit_button("Submit")
50
-
51
- @st.cache
52
- def load_and_process_data(path, name, streaming, split_name, number_of_records):
53
- dataset = load_dataset(path = path, name = name, streaming=streaming)
54
- dataset_head = dataset[split_name].take(number_of_records)
55
- df = pd.DataFrame.from_dict(dataset_head)
56
- return df
57
-
58
- df = load_and_process_data(dataset_name, dataset_name_2, True, split_name, number_of_records)
59
-
60
- display_full_df = form.checkbox("Display the full dataset dataframe?")
61
- display_X_df = form.checkbox("Display the training data?", value = True)
62
- if task == "Classification":
63
- display_y_df = form.checkbox("Display the labels?", value = True)
64
-
65
- with st.expander("Open to see the data"):
66
- if display_full_df:
67
- st.dataframe(df)
68
- if display_X_df:
69
- st.dataframe(df[column_name])
70
- if task == "Classification":
71
- if display_y_df:
72
- st.dataframe(df[labels_column_name])
73
-
74
-
75
-
76
- 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")
77
- form.caption("This will download a new model, so it may take awhile or even break if the model is too large")
78
- form.caption("See the list of pre-trained models that are available here! https://www.sbert.net/docs/pretrained_models.html")
79
-
80
- #embeddings = model.encode(sentences, convert_to_numpy = True)
81
-
82
-
83
-
84
- @st.cache
85
- def load_model_and_return_embedder(model_name):
86
- model = SentenceTransformer(model_name)
87
- embedder = FunctionTransformer(lambda item:model.encode(item, convert_to_numpy=True, show_progress_bar=False))
88
- return embedder
89
-
90
- embedder = load_model_and_return_embedder(model_name=model_name)
91
-
92
-
93
-
94
- form_classification = st.sidebar.form("classification")
95
- form_classification.header("Classifier Settings")
96
- 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")
97
- 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")
98
- 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)
99
- criterion = form_classification.radio("Which splitting criterion should we use?", ("gini", "entropy"))
100
- min_samples = form_classification.number_input("What's the minimum number of samples required to split the tree?", value = 2)
101
- form_classification.form_submit_button("Submit")
102
-
103
- if task == "Clustering":
104
- form_clustering = st.sidebar.form("clustering")
105
- form_clustering.header("Clustering Settings")
106
- 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")
107
- n_clusters = form_clustering.number_input("How many clusters are we looking for?", value = 10)
108
- 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)
109
- 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)
110
- form_clustering.form_submit_button("Submit")
111
-
112
-
113
- text_clf = Pipeline([
114
- ('vect', embedder),
115
- ('clf', RandomForestClassifier(n_estimators=n_estimators, criterion = criterion, min_samples_split = min_samples)),
116
- ])
117
-
118
-
119
-
120
- if task == "Clustering":
121
- cluster_clf = Pipeline([
122
- ('vect', embedder),
123
- ('cluster', KMeans(n_clusters = n_clusters, n_init = n_init, max_iter = max_iter)),
124
- ])
125
-
126
-
127
- if task == "Classification":
128
- text_clf.fit(df[column_name], df[labels_column_name])
129
- else:
130
- kmeans = cluster_clf.fit(df[column_name])
131
- labels = list(cluster_clf['cluster'].labels_)
132
- text_clf.fit(df[column_name], labels)
133
- st.write("Generated Clusters for each example")
134
- st.write(labels)
135
-
136
-
137
-
138
- 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."
139
- """
140
-
141
- form_explainer = st.sidebar.form("explainer_form")
142
- form_explainer.header("Explainer Settings")
143
- position_dep = form_explainer.checkbox("Check this if you want to take into account the position of a word in the interpretation", value = False)
144
- number_samples = form_explainer.number_input("Enter the number of explainer peterbuted samples, higher creates a better explanation but takes longer", value = 1000)
145
- char_based = form_explainer.checkbox("Check this if you want to use a character based explanier", value = False)
146
- form_explainer.form_submit_button("Submit")
147
-
148
-
149
- te = TextExplainer(random_state=42, char_based=char_based, n_samples = number_samples, position_dependent=position_dep)
150
-
151
- input_choice = st.checkbox("Check this if you want to enter your own example to explain", value = False)
152
- if input_choice == False:
153
- record_to_explain = st.number_input("Enter the index of the document from the original dataset to interpret", value = 30)
154
- te.fit(df[column_name][record_to_explain], text_clf.predict_proba)
155
- if task == "Classification":
156
- st.write("Ground truth label")
157
- st.write(df[labels_column_name][record_to_explain])
158
- st.write("Model prediction")
159
- model_prediction = text_clf.predict([df[column_name][record_to_explain]])
160
- st.write(model_prediction)
161
- else:
162
- st.write("Ground 'truth' label (original cluster)")
163
- st.write(cluster_clf['cluster'].labels_[record_to_explain])
164
- st.write("model_prediction")
165
- model_prediction = text_clf.predict([df[column_name][record_to_explain]])
166
- st.write(model_prediction)
167
- else:
168
- record_to_explain = st.text_area("Enter the example document to explain", value = text_example)
169
- te.fit(record_to_explain, text_clf.predict_proba)
170
- if task == "Classification":
171
- st.write("Model prediction")
172
- model_prediction = text_clf.predict([record_to_explain])
173
- st.write(model_prediction)
174
- else:
175
- st.write("Ground 'truth' label (original cluster)")
176
- st.write(cluster_clf.predict([record_to_explain]))
177
- st.write("model_prediction")
178
- model_prediction = text_clf.predict([record_to_explain])
179
- st.write(model_prediction)
180
-
181
-
182
- if task == "Classification":
183
- target_feature_names = text_clf['clf'].classes_
184
- #target_feature_names = pd.unique(df[labels_column_name])
185
- target_feature_names_list = list(target_feature_names)
186
- t_pred = te.explain_prediction(target_names = target_feature_names_list)
187
- else:
188
- t_pred = te.explain_prediction()
189
- html = format_as_html(t_pred)
190
-
191
- form_html = st.sidebar.form("html_size_form")
192
- form_html.header("Model Explanation Display Settings")
193
- output_width = form_html.number_input("Enter the number of pixels for width of model explanation html display", value = 1920)
194
- output_height = form_html.number_input("Enter the number of pixels for height of model explanation html display", value = 2000)
195
- form_html.form_submit_button("Submit")
196
- st.caption("Scroll to see the full output!")
197
- components.html(html, width = output_width, height = output_height, scrolling = True)
198
-
199
- display_model_explanation_score = st.sidebar.checkbox("Display model explanation score metrics?", value = True)
200
-
201
- if display_model_explanation_score:
202
- 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")
203
- 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.")
204
- 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.")
205
- st.write(te.metrics_)
206
-