Hellisotherpeople commited on
Commit
04ca93e
·
verified ·
1 Parent(s): 5f2a284

Modernize: unpin sklearn/eli5, py3.12, cache_data/cache_resource, st.iframe, fix Series->encode

Browse files
Files changed (3) hide show
  1. README.md +2 -1
  2. app.py +24 -35
  3. requirements.txt +4 -3
README.md CHANGED
@@ -4,8 +4,9 @@ emoji: 📃➡️🗄️
4
  colorFrom: green
5
  colorTo: pink
6
  sdk: streamlit
 
7
  app_file: app.py
8
- pinned: True
9
  ---
10
 
11
  # Configuration
 
4
  colorFrom: green
5
  colorTo: pink
6
  sdk: streamlit
7
+ python_version: "3.12"
8
  app_file: app.py
9
+ pinned: true
10
  ---
11
 
12
  # Configuration
app.py CHANGED
@@ -1,4 +1,3 @@
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
@@ -13,7 +12,6 @@ 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
@@ -98,9 +96,9 @@ if task == "Classification":
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
@@ -131,10 +129,12 @@ form.caption("See the list of pre-trained models that are available here! https:
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)
@@ -160,40 +160,34 @@ if task == "Clustering":
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
 
@@ -214,11 +208,6 @@ form_explainer.form_submit_button("Submit")
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)
@@ -271,7 +260,7 @@ output_width = form_html.number_input("Enter the number of pixels for width of m
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
 
 
 
1
  from sentence_transformers import SentenceTransformer
2
  from sklearn.pipeline import make_union
3
  from sklearn.feature_extraction.text import CountVectorizer
 
12
  from sklearn.ensemble import RandomForestClassifier
13
  from eli5.formatters import format_as_text, format_as_html
14
  import streamlit as st
 
15
  from sklearn.tree import DecisionTreeClassifier
16
  from datasets import load_dataset
17
  import pandas as pd
 
96
 
97
  form.form_submit_button("Submit")
98
 
99
+ @st.cache_data
100
  def load_and_process_data(path, name, streaming, split_name, number_of_records):
101
+ dataset = load_dataset(path = path, name = name or None, streaming=streaming)
102
  dataset_head = dataset[split_name].take(number_of_records)
103
  df = pd.DataFrame.from_dict(dataset_head)
104
  return df
 
129
 
130
 
131
 
132
+ @st.cache_resource
133
  def load_model_and_return_embedder(model_name):
134
  model = SentenceTransformer(model_name)
135
+ ## sentence-transformers >=5 only accepts str/list-of-str, so coerce whatever
136
+ ## scikit-learn or eli5 hands us (Series, ndarray, ...) into a plain list of str
137
+ embedder = FunctionTransformer(lambda item: model.encode([str(x) for x in item], convert_to_numpy=True, show_progress_bar=False))
138
  return embedder
139
 
140
  embedder = load_model_and_return_embedder(model_name=model_name)
 
160
  form_clustering.form_submit_button("Submit")
161
 
162
 
163
+ ## The pipelines are built inside the cached functions so that every hyperparameter is
164
+ ## part of the cache key - st.cache_resource only hashes arguments, unlike legacy st.cache
165
+ @st.cache_resource
166
+ def fit_text_clf(X, y, model_name, n_estimators, criterion, min_samples):
167
+ text_clf = Pipeline([
168
+ ('vect', load_model_and_return_embedder(model_name)),
169
+ ('clf', RandomForestClassifier(n_estimators=n_estimators, criterion = criterion, min_samples_split = min_samples)),
170
+ ])
171
+ text_clf.fit(X, y)
172
+ return text_clf
173
 
174
+ @st.cache_resource
175
+ def fit_cluster_clf(X, model_name, n_clusters, n_init, max_iter):
176
  cluster_clf = Pipeline([
177
+ ('vect', load_model_and_return_embedder(model_name)),
178
  ('cluster', KMeans(n_clusters = n_clusters, n_init = n_init, max_iter = max_iter)),
179
  ])
 
 
 
 
 
 
 
 
180
  cluster_clf.fit(X)
181
  return cluster_clf
182
+
183
 
184
  if task == "Classification":
185
+ text_clf = fit_text_clf(df[column_name], df[labels_column_name], model_name, n_estimators, criterion, min_samples)
 
186
  else:
187
+ cluster_clf = fit_cluster_clf(df[column_name], model_name, n_clusters, n_init, max_iter)
 
188
  kmeans = cluster_clf
189
  labels = list(cluster_clf['cluster'].labels_)
190
+ text_clf = fit_text_clf(df[column_name], labels, model_name, n_estimators, criterion, min_samples)
 
191
  st.write("Generated Clusters for each example")
192
  st.write(labels)
193
 
 
208
 
209
  te = TextExplainer(random_state=42, char_based=char_based, n_samples = number_samples, position_dependent=position_dep)
210
 
 
 
 
 
 
211
  input_choice = st.checkbox("Check this if you want to enter your own example to explain", value = False)
212
  if input_choice == False:
213
  record_to_explain = st.number_input("Enter the index of the document from the original dataset to interpret", value = 30)
 
260
  output_height = form_html.number_input("Enter the number of pixels for height of model explanation html display", value = 2000)
261
  form_html.form_submit_button("Submit")
262
  st.caption("Scroll to see the full output!")
263
+ st.iframe(html, width = output_width, height = output_height)
264
 
265
  display_model_explanation_score = st.sidebar.checkbox("Display model explanation score metrics?", value = True)
266
 
requirements.txt CHANGED
@@ -1,7 +1,8 @@
1
- altair<5
2
- scikit-learn<1.3
3
  scipy
4
  sentence-transformers
5
  eli5
6
  pandas
7
- datasets
 
 
1
+ streamlit
2
+ scikit-learn
3
  scipy
4
  sentence-transformers
5
  eli5
6
  pandas
7
+ datasets
8
+ numpy