Parinthapat Pengpun commited on
Commit
2b9f83a
1 Parent(s): f4f4f9e
Files changed (3) hide show
  1. __pycache__/app.cpython-39.pyc +0 -0
  2. app.py +229 -0
  3. requirements.txt +1 -0
__pycache__/app.cpython-39.pyc ADDED
Binary file (6.93 kB). View file
 
app.py ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import pandas as pd
3
+ import numpy as np
4
+ from sklearn.datasets import fetch_20newsgroups
5
+ from sklearn.feature_extraction.text import TfidfVectorizer
6
+ from sklearn.linear_model import LogisticRegression, RidgeClassifier, SGDClassifier
7
+ from sklearn.metrics import accuracy_score
8
+ from sklearn.naive_bayes import ComplementNB
9
+ from sklearn.neighbors import KNeighborsClassifier, NearestCentroid
10
+ from sklearn.ensemble import RandomForestClassifier
11
+ from sklearn.svm import LinearSVC
12
+ from sklearn.utils.extmath import density
13
+ from time import time
14
+ import matplotlib.pyplot as plt
15
+ import matplotlib
16
+ from sklearn.metrics import ConfusionMatrixDisplay
17
+ import io
18
+ import base64
19
+ matplotlib.use('Agg') # set the backend to avoid GUI warning
20
+
21
+
22
+ all_categories = [
23
+ 'alt.atheism',
24
+ 'comp.graphics',
25
+ 'comp.os.ms-windows.misc',
26
+ 'comp.sys.ibm.pc.hardware',
27
+ 'comp.sys.mac.hardware',
28
+ 'comp.windows.x',
29
+ 'misc.forsale',
30
+ 'rec.autos',
31
+ 'rec.motorcycles',
32
+ 'rec.sport.baseball',
33
+ 'rec.sport.hockey',
34
+ 'sci.crypt',
35
+ 'sci.electronics',
36
+ 'sci.med',
37
+ 'sci.space',
38
+ 'soc.religion.christian',
39
+ 'talk.politics.guns',
40
+ 'talk.politics.mideast',
41
+ 'talk.politics.misc',
42
+ 'talk.religion.misc'
43
+ ]
44
+
45
+
46
+ def size_mb(docs):
47
+ return sum(len(s.encode("utf-8")) for s in docs) / 1e6
48
+
49
+
50
+ def load_dataset(categories, verbose=False, remove=()):
51
+ """Load and vectorize the 20 newsgroups dataset."""
52
+
53
+ data_train = fetch_20newsgroups(
54
+ subset="train",
55
+ categories=categories,
56
+ shuffle=True,
57
+ random_state=42,
58
+ remove=remove,
59
+ )
60
+
61
+ data_test = fetch_20newsgroups(
62
+ subset="test",
63
+ categories=categories,
64
+ shuffle=True,
65
+ random_state=42,
66
+ remove=remove,
67
+ )
68
+
69
+ # order of labels in `target_names` can be different from `categories`
70
+ target_names = data_train.target_names
71
+
72
+ # split target in a training set and a test set
73
+ y_train, y_test = data_train.target, data_test.target
74
+
75
+ # Extracting features from the training data using a sparse vectorizer
76
+ t0 = time()
77
+ vectorizer = TfidfVectorizer(
78
+ sublinear_tf=True, max_df=0.5, min_df=5, stop_words="english"
79
+ )
80
+ X_train = vectorizer.fit_transform(data_train.data)
81
+ duration_train = time() - t0
82
+
83
+ # Extracting features from the test data using the same vectorizer
84
+ t0 = time()
85
+ X_test = vectorizer.transform(data_test.data)
86
+ duration_test = time() - t0
87
+
88
+ feature_names = vectorizer.get_feature_names_out()
89
+
90
+ if verbose:
91
+
92
+ # compute size of loaded data
93
+ data_train_size_mb = size_mb(data_train.data)
94
+ data_test_size_mb = size_mb(data_test.data)
95
+
96
+ print(
97
+ f"{len(data_train.data)} documents - "
98
+ f"{data_train_size_mb:.2f}MB (training set)"
99
+ )
100
+ print(f"{len(data_test.data)} documents - {data_test_size_mb:.2f}MB (test set)")
101
+ print(f"{len(target_names)} categories")
102
+ print(
103
+ f"vectorize training done in {duration_train:.3f}s "
104
+ f"at {data_train_size_mb / duration_train:.3f}MB/s"
105
+ )
106
+ print(f"n_samples: {X_train.shape[0]}, n_features: {X_train.shape[1]}")
107
+ print(
108
+ f"vectorize testing done in {duration_test:.3f}s "
109
+ f"at {data_test_size_mb / duration_test:.3f}MB/s"
110
+ )
111
+ print(f"n_samples: {X_test.shape[0]}, n_features: {X_test.shape[1]}")
112
+
113
+ return X_train, X_test, y_train, y_test, feature_names, target_names
114
+
115
+ def benchmark(clf, X_train, X_test, y_train, y_test):
116
+ print("_" * 80)
117
+ print("Training: ")
118
+ print(clf)
119
+ t0 = time()
120
+ clf.fit(X_train, y_train)
121
+ train_time = time() - t0
122
+ print(f"train time: {train_time:.3}s")
123
+
124
+ t0 = time()
125
+ pred = clf.predict(X_test)
126
+ test_time = time() - t0
127
+ print(f"test time: {test_time:.3}s")
128
+
129
+ score = accuracy_score(y_test, pred)
130
+ print(f"accuracy: {score:.3}")
131
+
132
+ if hasattr(clf, "coef_"):
133
+ print(f"dimensionality: {clf.coef_.shape[1]}")
134
+ print(f"density: {density(clf.coef_)}")
135
+ print()
136
+
137
+ print()
138
+ clf_descr = clf.__class__.__name__
139
+ return clf_descr, score, train_time, test_time
140
+
141
+
142
+ def run_experiment(categories, models):
143
+ X_train, X_test, y_train, y_test, feature_names, target_names = load_dataset(
144
+ categories, verbose=True
145
+ )
146
+ results = []
147
+ for clf, name in models:
148
+ print("=" * 80)
149
+ print(name)
150
+ results.append(benchmark(clf, X_train, X_test, y_train, y_test))
151
+ plot_feature_effects(clf, target_names, feature_names, X_train)
152
+ clf_names, score, training_time, test_time = [list(x) for x in zip(*results)]
153
+
154
+ training_time = np.array(training_time)
155
+ test_time = np.array(test_time)
156
+
157
+ fig, ax1 = plt.subplots(figsize=(10, 8))
158
+ ax1.scatter(score, training_time, s=60)
159
+ ax1.set(
160
+ title="Score-training time trade-off",
161
+ yscale="log",
162
+ xlabel="test accuracy",
163
+ ylabel="training time (s)",
164
+ )
165
+
166
+ fig, ax2 = plt.subplots(figsize=(10, 8))
167
+ ax2.scatter(score, test_time, s=60)
168
+
169
+ ax2.set(
170
+ title="Score-test time trade-off",
171
+ yscale="log",
172
+ xlabel="test accuracy",
173
+ ylabel="test time (s)",
174
+ )
175
+
176
+ for i, txt in enumerate(clf_names):
177
+ ax1.annotate(txt, (score[i], training_time[i]))
178
+ ax2.annotate(txt, (score[i], test_time[i]))
179
+
180
+ result_df = pd.DataFrame(
181
+ {"Model": clf_names, "Test Accuracy": score, "Training Time": training_time, "Test Time": test_time}
182
+ )
183
+
184
+ return result_df
185
+
186
+ def run_experiment_gradio():
187
+ models = [(LogisticRegression(C=5, max_iter=1000), "Logistic Regression"), (RidgeClassifier(alpha=1.0, solver="sparse_cg"), "Ridge Classifier"), (KNeighborsClassifier(n_neighbors=100), "kNN"), (RandomForestClassifier(), "Random Forest"), (LinearSVC(C=0.1, dual=False, max_iter=1000), "Linear SVC"), (SGDClassifier(loss="log_loss", alpha=1e-4, n_iter_no_change=3, early_stopping=True), "log-loss SGD"), (NearestCentroid(), "NearestCentroid"), (ComplementNB(alpha=0.1), "Complement naive Bayes")]
188
+
189
+ def run_model(model_names, categories):
190
+ results = []
191
+ print(model_names)
192
+ for model_name in model_names:
193
+ model = next((m[0] for m in models if str(m[0]) == model_name), None)
194
+ if model is None:
195
+ continue
196
+ X_train, X_test, y_train, y_test, feature_names, target_names = load_dataset(
197
+ categories, verbose=True
198
+ )
199
+ clf = model
200
+ clf_descr, score, train_time, test_time = benchmark(clf, X_train, X_test, y_train, y_test)
201
+ results.append({"Model": clf_descr, "Test Accuracy": score, "Training Time": train_time, "Test Time": test_time})
202
+ return pd.DataFrame(results)
203
+
204
+ category_options = [category for category in all_categories]
205
+ category_group = gr.inputs.CheckboxGroup(
206
+ label="Categories",
207
+ choices=category_options,
208
+ default=category_options[:5],
209
+ )
210
+
211
+ model_options = [model[0] for model in models]
212
+ model_dropdown = gr.inputs.CheckboxGroup(
213
+ choices=model_options,
214
+ label="Models",
215
+ )
216
+
217
+ interface = gr.Interface(
218
+ fn=run_model,
219
+ inputs=[model_dropdown, category_group],
220
+ outputs="dataframe",
221
+ title="20 Newsgroups Text Classification Experiment",
222
+ description="Select one or more categories and one or more models, then click 'Run Experiment' to evaluate them on the 20 newsgroups text classification task.",
223
+ allow_flagging=False,
224
+ analytics_enabled=False
225
+ )
226
+
227
+ return interface
228
+
229
+ run_experiment_gradio().launch(quiet=False)
requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ scikit-learn==1.2.2