Spaces:
Sleeping
Sleeping
File size: 7,750 Bytes
3b89855 9d85ec7 3b89855 9d85ec7 3b89855 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 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 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 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 158 159 160 161 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 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 | import gradio as gr
import numpy as np
import numexpr
import pandas as pd
import time
NUMEXPR_CONSTANTS = {
'pi': np.pi,
'PI': np.pi,
'e': np.e,
}
def get_function(function, xlim=(-1, 1), nsample=100):
x = np.linspace(xlim[0], xlim[1], nsample)
y = numexpr.evaluate(function, local_dict={'x': x, **NUMEXPR_CONSTANTS})
x = x.reshape(-1, 1)
return x, y
def get_data_points(function, xlim=(-1, 1), nsample=10, sigma=0, seed=0):
num_points_to_generate = 100
if nsample > num_points_to_generate:
raise ValueError(f"nsample too large, limit to {num_points_to_generate}")
rng = np.random.default_rng(seed)
x = rng.uniform(xlim[0], xlim[1], size=num_points_to_generate)
x = x[:nsample]
x = np.sort(x)
rng = np.random.default_rng(seed)
noise = sigma * rng.standard_normal(nsample)
y = numexpr.evaluate(function, local_dict={'x': x, **NUMEXPR_CONSTANTS}) + noise
x = x.reshape(-1, 1)
return x, y
class Dataset:
def __init__(
self,
mode: str = "generate",
function: str = "sin(2 * pi * x)",
xmin: float = -1.0,
xmax: float = 1.0,
nsample: int = 30,
sigma: float = 0.0,
seed: int = 0,
csv_path: str = None,
):
self.mode = mode
self.function = function
self.xmin = xmin
self.xmax = xmax
self.nsample = nsample
self.sigma = sigma
self.seed = seed
self.csv_path = csv_path
self.x, self.y = self._get_data()
def _get_data(self):
if self.mode == "generate":
return get_data_points(
function=self.function,
xlim=(self.xmin, self.xmax),
nsample=self.nsample,
sigma=self.sigma,
seed=self.seed,
)
elif self.mode == "csv":
if self.csv_path is None:
return np.array([]), np.array([])
df = pd.read_csv(self.csv_path)
if df.shape[1] != 2:
raise ValueError("CSV file must have exactly two columns")
x = df.iloc[:, 0].values.reshape(-1, 1)
y = df.iloc[:, 1].values
return x, y
else:
raise ValueError(f"Unknown dataset mode: {self.mode}")
def update(self, **kwargs):
return Dataset(
mode=kwargs.get("mode", self.mode),
function=kwargs.get("function", self.function),
xmin=kwargs.get("xmin", self.xmin),
xmax=kwargs.get("xmax", self.xmax),
nsample=kwargs.get("nsample", self.nsample),
sigma=kwargs.get("sigma", self.sigma),
seed=kwargs.get("seed", self.seed),
csv_path=kwargs.get("csv_path", self.csv_path),
)
def _safe_hash(self, val: int) -> int | tuple[int, str]:
# special handling for -1 (same hash number as -2)
if val == -1:
return (-1, "special")
return val
def __hash__(self):
return hash(
(
self.mode,
self.function,
self._safe_hash(self.xmin),
self._safe_hash(self.xmax),
self.nsample,
self.sigma,
self.seed,
self.csv_path,
)
)
class DatasetView:
def update_mode(self, mode: str, state: gr.State):
state = state.update(mode=mode)
if mode == "generate":
return (
state,
gr.update(visible=True), # function
gr.update(visible=True), # xmin
gr.update(visible=True), # xmax
gr.update(visible=True), # sigma
gr.update(visible=True), # nsample
gr.update(visible=True), # regenerate
gr.update(visible=False), # csv upload
)
elif mode == "csv":
return (
state,
gr.update(visible=False), # function
gr.update(visible=False), # xmin
gr.update(visible=False), # xmax
gr.update(visible=False), # sigma
gr.update(visible=False), # nsample
gr.update(visible=False), # regenerate
gr.update(visible=True), # csv upload
)
else:
raise ValueError(f"Unknown mode: {mode}")
def upload_csv(self, file, state):
try:
state = state.update(
mode="csv",
csv_path=file.name,
)
except Exception as e:
gr.Info(f"⚠️ {e}")
return state
def regenerate_data(self, state: gr.State):
seed = int(time.time() * 1000) % (2 ** 32)
state = state.update(seed=seed)
return state
def update_all(self, function, xmin, xmax, sigma, nsample, state):
state = state.update(
function=function,
xmin=xmin,
xmax=xmax,
sigma=sigma,
nsample=nsample,
)
return state
def build(self, state: gr.State):
options = state.value
with gr.Column():
mode = gr.Radio(
label="Dataset",
choices=["generate", "csv"],
value="generate",
)
function = gr.Textbox(
label="Function (in terms of x)",
value=options.function,
)
with gr.Row():
xmin = gr.Number(
label="x min",
value=options.xmin,
)
xmax = gr.Number(
label="x max",
value=options.xmax,
)
sigma = gr.Number(
label="Gaussian noise standard deviation",
value=options.sigma,
)
nsample = gr.Slider(
label="Number of samples",
minimum=0,
maximum=100,
step=1,
value=options.nsample,
)
regenerate = gr.Button("Regenerate Data")
csv_upload = gr.File(
label="Upload CSV file",
file_types=['.csv'],
visible=False, # function mode is default
)
mode.change(
fn=self.update_mode,
inputs=[mode, state],
outputs=[state, function, xmin, xmax, sigma, nsample, regenerate, csv_upload],
)
# generate mode
function.submit(
lambda f, s: s.update(function=f),
inputs=[function, state],
outputs=[state],
)
xmin.submit(
lambda xmn, s: s.update(xmin=xmn),
inputs=[xmin, state],
outputs=[state],
)
xmax.submit(
lambda xmx, s: s.update(xmax=xmx),
inputs=[xmax, state],
outputs=[state],
)
sigma.submit(
lambda sig, s: s.update(sigma=sig),
inputs=[sigma, state],
outputs=[state],
)
nsample.change(
lambda n, s: s.update(nsample=n),
inputs=[nsample, state],
outputs=[state],
)
regenerate.click(
self.update_all,
inputs=[function, xmin, xmax, sigma, nsample, state],
outputs=[state],
).then(
fn=self.regenerate_data,
inputs=[state],
outputs=[state],
)
# csv mode
csv_upload.upload(
self.upload_csv,
inputs=[csv_upload, state],
outputs=[state],
)
|