Spaces:
Runtime error
Runtime error
marvin niu commited on
new app
Browse files- README.md +5 -5
- app.py +151 -172
- packages.txt +0 -8
- requirements.txt +2 -23
README.md
CHANGED
|
@@ -1,12 +1,12 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: gradio
|
| 7 |
sdk_version: 3.1.1
|
| 8 |
app_file: app.py
|
| 9 |
-
pinned:
|
| 10 |
license: apache-2.0
|
| 11 |
---
|
| 12 |
|
|
|
|
| 1 |
---
|
| 2 |
+
title: Classification
|
| 3 |
+
emoji: 🌲
|
| 4 |
+
colorFrom: red
|
| 5 |
+
colorTo: purple
|
| 6 |
sdk: gradio
|
| 7 |
sdk_version: 3.1.1
|
| 8 |
app_file: app.py
|
| 9 |
+
pinned: false
|
| 10 |
license: apache-2.0
|
| 11 |
---
|
| 12 |
|
app.py
CHANGED
|
@@ -1,192 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import math
|
| 2 |
-
import
|
| 3 |
-
import sys
|
| 4 |
|
| 5 |
-
import gradio as gr
|
| 6 |
-
import matplotlib.pyplot as plt
|
| 7 |
-
import numpy as np
|
| 8 |
-
from PIL import Image
|
| 9 |
-
import torch
|
| 10 |
-
import torchvision
|
| 11 |
-
|
| 12 |
-
os.system("git clone https://github.com/xplip/pixel.git")
|
| 13 |
-
sys.path.append('./pixel')
|
| 14 |
-
|
| 15 |
-
from transformers import set_seed
|
| 16 |
-
from pixel.src.pixel import (
|
| 17 |
-
PIXELConfig,
|
| 18 |
-
PIXELForPreTraining,
|
| 19 |
-
SpanMaskingGenerator,
|
| 20 |
-
PyGameTextRenderer,
|
| 21 |
-
get_transforms,
|
| 22 |
-
resize_model_embeddings,
|
| 23 |
-
truncate_decoder_pos_embeddings,
|
| 24 |
-
get_attention_mask
|
| 25 |
-
)
|
| 26 |
-
|
| 27 |
-
model_name_or_path = "Team-PIXEL/pixel-base"
|
| 28 |
-
max_seq_length = 529
|
| 29 |
-
text_renderer = PyGameTextRenderer.from_pretrained(model_name_or_path, max_seq_length=max_seq_length)
|
| 30 |
-
config = PIXELConfig.from_pretrained(model_name_or_path)
|
| 31 |
-
model = PIXELForPreTraining.from_pretrained(model_name_or_path, config=config)
|
| 32 |
-
|
| 33 |
-
def clip(x: torch.Tensor):
|
| 34 |
-
x = torch.einsum("chw->hwc", x)
|
| 35 |
-
x = torch.clip(x * 255, 0, 255)
|
| 36 |
-
x = torch.einsum("hwc->chw", x)
|
| 37 |
-
return x
|
| 38 |
-
|
| 39 |
-
def get_image(img: torch.Tensor, do_clip: bool = True):
|
| 40 |
-
if do_clip:
|
| 41 |
-
img = clip(img)
|
| 42 |
-
img = torchvision.utils.make_grid(img, normalize=True)
|
| 43 |
-
image = Image.fromarray(
|
| 44 |
-
img.mul(255).clamp(0, 255).byte().permute(1, 2, 0).cpu().numpy()
|
| 45 |
-
)
|
| 46 |
-
return image
|
| 47 |
|
| 48 |
-
def inference(text: str, mask_ratio: float = 0.25, max_span_length: int = 6, seed: int = 42):
|
| 49 |
-
config.update({"mask_ratio": mask_ratio})
|
| 50 |
-
resize_model_embeddings(model, max_seq_length)
|
| 51 |
-
truncate_decoder_pos_embeddings(model, max_seq_length)
|
| 52 |
|
| 53 |
-
|
|
|
|
|
|
|
|
|
|
| 54 |
|
| 55 |
-
transforms = get_transforms(
|
| 56 |
-
do_resize=True,
|
| 57 |
-
size=(text_renderer.pixels_per_patch, text_renderer.pixels_per_patch * text_renderer.max_seq_length),
|
| 58 |
-
)
|
| 59 |
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
|
|
|
|
|
|
| 68 |
|
| 69 |
-
mask_generator = SpanMaskingGenerator(
|
| 70 |
-
num_patches=text_renderer.max_seq_length,
|
| 71 |
-
num_masking_patches=math.ceil(mask_ratio * text_renderer.max_seq_length),
|
| 72 |
-
max_span_length=max_span_length,
|
| 73 |
-
spacing="span"
|
| 74 |
-
)
|
| 75 |
-
mask = torch.tensor(mask_generator(num_text_patches=(encoding.num_text_patches + 1))).unsqueeze(0)
|
| 76 |
-
inputs.update({"patch_mask": mask})
|
| 77 |
|
| 78 |
-
|
| 79 |
-
with torch.no_grad():
|
| 80 |
-
outputs = model(**inputs)
|
| 81 |
|
| 82 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
|
| 88 |
-
attention_mask = attention_mask.unsqueeze(-1).repeat(1, 1, text_renderer.pixels_per_patch ** 2 * 3)
|
| 89 |
-
attention_mask = model.unpatchify(attention_mask).squeeze()
|
| 90 |
|
| 91 |
-
original_img = model.unpatchify(model.patchify(img)).squeeze()
|
| 92 |
|
| 93 |
-
|
|
|
|
|
|
|
|
|
|
| 94 |
|
| 95 |
-
masked_predictions = predictions * mask * attention_mask
|
| 96 |
|
| 97 |
-
reconstruction = im_masked + masked_predictions
|
| 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 |
-
label="Masked Predictions",
|
| 158 |
-
show_label=False,
|
| 159 |
-
elem_id="output_image"
|
| 160 |
-
)
|
| 161 |
with gr.Column():
|
| 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 |
-
gr.HTML("<p style='text-align: center'><a href='https://arxiv.org/abs/2207.06991' target='_blank'><b>Paper</b></a> | <a href='https://github.com/xplip/pixel' target='_blank'><b>Github</b></a></p>")
|
| 189 |
-
gr.HTML("<center><img src='https://visitor-badge.glitch.me/badge?page_id=Team-PIXEL/PIXEL' alt='visitor badge'></center>")
|
| 190 |
-
|
| 191 |
-
btn.click(fn=inference, inputs=[tb_text, sl_ratio, sl_len, sl_seed], outputs=[out_original, out_masked, out_masked_pred, out_reconstruction])
|
| 192 |
-
demo.launch(debug=True)
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import matplotlib.pyplot as plt
|
| 3 |
+
from matplotlib.colors import ListedColormap
|
| 4 |
+
from sklearn.model_selection import train_test_split
|
| 5 |
+
from sklearn.preprocessing import StandardScaler
|
| 6 |
+
from sklearn.datasets import make_moons, make_circles, make_classification
|
| 7 |
+
from sklearn.neural_network import MLPClassifier
|
| 8 |
+
from sklearn.neighbors import KNeighborsClassifier
|
| 9 |
+
from sklearn.svm import SVC
|
| 10 |
+
from sklearn.gaussian_process import GaussianProcessClassifier
|
| 11 |
+
from sklearn.gaussian_process.kernels import RBF
|
| 12 |
+
from sklearn.tree import DecisionTreeClassifier
|
| 13 |
+
from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier
|
| 14 |
+
from sklearn.naive_bayes import GaussianNB
|
| 15 |
+
from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis
|
| 16 |
+
from sklearn.inspection import DecisionBoundaryDisplay
|
| 17 |
+
from sklearn.datasets import make_blobs, make_circles, make_moons
|
| 18 |
+
import gradio as gr
|
| 19 |
import math
|
| 20 |
+
from functools import partial
|
|
|
|
| 21 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
|
| 24 |
+
### DATASETS
|
| 25 |
+
|
| 26 |
+
def normalize(X):
|
| 27 |
+
return StandardScaler().fit_transform(X)
|
| 28 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
+
def linearly_separable():
|
| 31 |
+
X, y = make_classification(
|
| 32 |
+
n_features=2, n_redundant=0, n_informative=2, random_state=1, n_clusters_per_class=1
|
| 33 |
)
|
| 34 |
+
rng = np.random.RandomState(2)
|
| 35 |
+
X += 2 * rng.uniform(size=X.shape)
|
| 36 |
+
linearly_separable = (X, y)
|
| 37 |
+
return linearly_separable
|
| 38 |
|
| 39 |
+
DATA_MAPPING = {
|
| 40 |
+
"Moons": make_moons(noise=0.3, random_state=0),
|
| 41 |
+
"Circles":make_circles(noise=0.2, factor=0.5, random_state=1),
|
| 42 |
+
"Linearly Separable Random Dataset": linearly_separable(),
|
| 43 |
+
}
|
| 44 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
|
| 46 |
+
#### MODELS
|
|
|
|
|
|
|
| 47 |
|
| 48 |
+
def get_groundtruth_model(X, labels):
|
| 49 |
+
# dummy model to show true label distribution
|
| 50 |
+
class Dummy:
|
| 51 |
+
def __init__(self, y):
|
| 52 |
+
self.labels_ = labels
|
| 53 |
|
| 54 |
+
return Dummy(labels)
|
| 55 |
+
|
| 56 |
+
DATASETS = [
|
| 57 |
+
make_moons(noise=0.3, random_state=0),
|
| 58 |
+
make_circles(noise=0.2, factor=0.5, random_state=1),
|
| 59 |
+
linearly_separable()
|
| 60 |
+
]
|
| 61 |
+
NAME_CLF_MAPPING = {
|
| 62 |
+
"Ground Truth":get_groundtruth_model,
|
| 63 |
+
"Nearest Neighbors":KNeighborsClassifier(3),
|
| 64 |
+
"Linear SVM":SVC(kernel="linear", C=0.025),
|
| 65 |
+
"RBF SVM":SVC(gamma=2, C=1),
|
| 66 |
+
"Gaussian Process":GaussianProcessClassifier(1.0 * RBF(1.0)),
|
| 67 |
+
"Decision Tree":DecisionTreeClassifier(max_depth=5),
|
| 68 |
+
"Random Forest":RandomForestClassifier(max_depth=5, n_estimators=10, max_features=1),
|
| 69 |
+
"Neural Net":MLPClassifier(alpha=1, max_iter=1000),
|
| 70 |
+
"AdaBoost":AdaBoostClassifier(),
|
| 71 |
+
"Naive Bayes":GaussianNB(),
|
| 72 |
+
}
|
| 73 |
|
|
|
|
|
|
|
| 74 |
|
|
|
|
| 75 |
|
| 76 |
+
#### PLOT
|
| 77 |
+
FIGSIZE = 7,7
|
| 78 |
+
figure = plt.figure(figsize=(25, 10))
|
| 79 |
+
i = 1
|
| 80 |
|
|
|
|
| 81 |
|
|
|
|
| 82 |
|
| 83 |
+
|
| 84 |
+
def train_models(selected_data, clf_name):
|
| 85 |
+
cm = plt.cm.RdBu
|
| 86 |
+
cm_bright = ListedColormap(["#FF0000", "#0000FF"])
|
| 87 |
+
clf = NAME_CLF_MAPPING[clf_name]
|
| 88 |
+
|
| 89 |
+
X, y = DATA_MAPPING[selected_data]
|
| 90 |
+
X = StandardScaler().fit_transform(X)
|
| 91 |
+
X_train, X_test, y_train, y_test = train_test_split(
|
| 92 |
+
X, y, test_size=0.4, random_state=42
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
x_min, x_max = X[:, 0].min() - 0.5, X[:, 0].max() + 0.5
|
| 96 |
+
y_min, y_max = X[:, 1].min() - 0.5, X[:, 1].max() + 0.5
|
| 97 |
+
if clf_name != "Ground Truth":
|
| 98 |
+
clf.fit(X_train, y_train)
|
| 99 |
+
score = clf.score(X_test, y_test)
|
| 100 |
+
fig, ax = plt.subplots(figsize=FIGSIZE)
|
| 101 |
+
ax.set_title(clf_name, fontsize = 10)
|
| 102 |
+
|
| 103 |
+
DecisionBoundaryDisplay.from_estimator(
|
| 104 |
+
clf, X, cmap=cm, alpha=0.8, ax=ax, eps=0.5
|
| 105 |
+
).plot()
|
| 106 |
+
return fig
|
| 107 |
+
else:
|
| 108 |
+
#########
|
| 109 |
+
|
| 110 |
+
for ds_cnt, ds in enumerate(DATASETS):
|
| 111 |
+
X, y = ds
|
| 112 |
+
|
| 113 |
+
x_min, x_max = X[:, 0].min() - 0.5, X[:, 0].max() + 0.5
|
| 114 |
+
y_min, y_max = X[:, 1].min() - 0.5, X[:, 1].max() + 0.5
|
| 115 |
+
|
| 116 |
+
# just plot the dataset first
|
| 117 |
+
cm = plt.cm.RdBu
|
| 118 |
+
cm_bright = ListedColormap(["#FF0000", "#0000FF"])
|
| 119 |
+
fig, ax = plt.subplots(figsize=FIGSIZE)
|
| 120 |
+
ax.set_title("Input data")
|
| 121 |
+
# Plot the training points
|
| 122 |
+
|
| 123 |
+
ax.scatter(X_train[:, 0], X_train[:, 1], c=y_train, cmap=cm_bright, edgecolors="k")
|
| 124 |
+
# Plot the testing points
|
| 125 |
+
ax.scatter(
|
| 126 |
+
X_test[:, 0], X_test[:, 1], c=y_test, cmap=cm_bright, alpha=0.6, edgecolors="k"
|
| 127 |
)
|
| 128 |
+
ax.set_xlim(x_min, x_max)
|
| 129 |
+
ax.set_ylim(y_min, y_max)
|
| 130 |
+
ax.set_xticks(())
|
| 131 |
+
ax.set_yticks(())
|
| 132 |
+
|
| 133 |
+
return fig
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
###########
|
| 138 |
+
description = "Learn how different statistical classifiers perform in different datasets."
|
| 139 |
+
|
| 140 |
+
def iter_grid(n_rows, n_cols):
|
| 141 |
+
# create a grid using gradio Block
|
| 142 |
+
for _ in range(n_rows):
|
| 143 |
+
with gr.Row():
|
| 144 |
+
for _ in range(n_cols):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 145 |
with gr.Column():
|
| 146 |
+
yield
|
| 147 |
+
|
| 148 |
+
title = "Compare Classifiers!"
|
| 149 |
+
with gr.Blocks(title=title) as demo:
|
| 150 |
+
gr.Markdown(f"## {title}")
|
| 151 |
+
gr.Markdown(description)
|
| 152 |
+
|
| 153 |
+
input_models = list(NAME_CLF_MAPPING)
|
| 154 |
+
input_data = gr.Radio(
|
| 155 |
+
choices=["Moons", "Circles", "Linearly Separable Random Dataset"],
|
| 156 |
+
value="Moons"
|
| 157 |
+
)
|
| 158 |
+
counter = 0
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
for _ in iter_grid(2, 5):
|
| 162 |
+
if counter >= len(input_models):
|
| 163 |
+
break
|
| 164 |
+
|
| 165 |
+
input_model = input_models[counter]
|
| 166 |
+
plot = gr.Plot(label=input_model)
|
| 167 |
+
fn = partial(train_models, clf_name=input_model)
|
| 168 |
+
input_data.change(fn=fn, inputs=[input_data], outputs=plot)
|
| 169 |
+
counter += 1
|
| 170 |
+
|
| 171 |
+
demo.launch(debug=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
packages.txt
DELETED
|
@@ -1,8 +0,0 @@
|
|
| 1 |
-
libgirepository1.0-dev
|
| 2 |
-
gcc
|
| 3 |
-
libcairo2-dev
|
| 4 |
-
pkg-config
|
| 5 |
-
python3-dev
|
| 6 |
-
gir1.2-gtk-3.0
|
| 7 |
-
libpango1.0-dev
|
| 8 |
-
libpangocairo-1.0-0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
requirements.txt
CHANGED
|
@@ -1,23 +1,2 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
gradio
|
| 4 |
-
manimpango
|
| 5 |
-
matplotlib
|
| 6 |
-
nltk
|
| 7 |
-
numpy
|
| 8 |
-
opencv-python-headless
|
| 9 |
-
pandas
|
| 10 |
-
pyarrow
|
| 11 |
-
pycairo
|
| 12 |
-
pygame
|
| 13 |
-
PyGObject
|
| 14 |
-
pyyaml
|
| 15 |
-
scipy
|
| 16 |
-
seqeval
|
| 17 |
-
sklearn
|
| 18 |
-
spacy
|
| 19 |
-
submitit
|
| 20 |
-
torch
|
| 21 |
-
torchvision
|
| 22 |
-
transformers==4.17.0
|
| 23 |
-
wandb
|
|
|
|
| 1 |
+
scikit-learn
|
| 2 |
+
matplotlib
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|