Spaces:
Running
Running
File size: 7,103 Bytes
222fbf0 13219e6 460af25 bb76c1f 13219e6 edbcfa6 71ed397 c6a43c4 46fdaa6 73042d9 46fdaa6 73042d9 deeb73e bb76c1f f072863 bb76c1f 73042d9 bb76c1f 73042d9 f072863 73042d9 bb76c1f 73042d9 13219e6 bb76c1f 13219e6 bb76c1f 13219e6 d39a013 5a5a76f deeb73e 13219e6 bb76c1f 13219e6 bb76c1f c6a43c4 bb76c1f c6a43c4 88a78a4 dd65136 5a5a76f dd65136 5a5a76f dd65136 f072863 dd65136 46fdaa6 dd65136 46fdaa6 dd65136 46fdaa6 c353ada bb76c1f c353ada 46fdaa6 dd65136 bb76c1f 46fdaa6 dd65136 bb76c1f dd65136 5a5a76f dd65136 46fdaa6 bb76c1f 46fdaa6 dd65136 edbcfa6 5a5a76f edbcfa6 dd65136 46fdaa6 222fbf0 f072863 |
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 273 274 275 276 277 278 279 280 281 282 |
import gradio as gr
import numpy as np
import pandas as pd
import multiprocessing as mp
import tempfile
from typing import Optional
empty_df = pd.DataFrame(
{
"equation": [],
"loss": [],
"complexity": [],
}
)
test_equations = [
"sin(x) + cos(2*x) + tan(x/3)",
]
def generate_data(s: str, num_points: int, noise_level: float):
x = np.linspace(0, 10, num_points)
for (k, v) in {
"sin": "np.sin",
"cos": "np.cos",
"exp": "np.exp",
"log": "np.log",
"tan": "np.tan",
"^": "**",
}.items():
s = s.replace(k, v)
y = eval(s)
noise = np.random.normal(0, noise_level, y.shape)
y_noisy = y + noise
return pd.DataFrame({"x": x}), y_noisy
def _greet_dispatch(
file_input,
force_run,
test_equation,
num_points,
noise_level,
niterations,
maxsize,
binary_operators,
unary_operators,
seed,
):
"""Load data, then spawn a process to run the greet function."""
if file_input is not None:
# Look at some statistics of the file:
df = pd.read_csv(file_input)
if len(df) == 0:
return (
empty_df,
"The file is empty!",
)
if len(df.columns) == 1:
return (
empty_df,
"The file has only one column!",
)
if len(df) > 10_000 and not force_run:
return (
empty_df,
"You have uploaded a file with more than 10,000 rows. "
"This will take very long to run. "
"Please upload a subsample of the data, "
"or check the box 'Ignore Warnings'.",
)
col_to_fit = df.columns[-1]
y = np.array(df[col_to_fit])
X = df.drop([col_to_fit], axis=1)
else:
# X, y = generate_data(block["test_equation"], block["num_points"], block["noise_level"])
X, y = generate_data(test_equation, num_points, noise_level)
queue = mp.Queue()
process = mp.Process(
target=greet,
kwargs=dict(
X=X,
y=y,
queue=queue,
niterations=niterations,
maxsize=maxsize,
binary_operators=binary_operators,
unary_operators=unary_operators,
seed=seed,
),
)
process.start()
output = queue.get()
process.join()
return output
def greet(
*,
queue: mp.Queue,
X,
y,
niterations: int,
maxsize: int,
binary_operators: list,
unary_operators: list,
seed: int,
):
import pysr
model = pysr.PySRRegressor(
progress=False,
maxsize=maxsize,
niterations=niterations,
binary_operators=binary_operators,
unary_operators=unary_operators,
timeout_in_seconds=1000,
multithreading=False,
procs=0,
deterministic=True,
random_state=seed,
)
model.fit(X, y)
df = model.equations_[["complexity", "loss", "equation"]]
# Convert all columns to string type:
queue.put(df)
return 0
def _data_layout():
with gr.Tab("Example Data"):
# Plot of the example data:
example_plot = gr.ScatterPlot(
x="x",
y="y",
tooltip=["x", "y"],
x_lim=[0, 10],
y_lim=[-5, 5],
width=350,
height=300,
)
test_equation = gr.Radio(
test_equations, value=test_equations[0], label="Test Equation"
)
num_points = gr.Slider(
minimum=10,
maximum=1000,
value=100,
label="Number of Data Points",
step=1,
)
noise_level = gr.Slider(minimum=0, maximum=1, value=0.1, label="Noise Level")
with gr.Tab("Upload Data"):
file_input = gr.File(label="Upload a CSV File")
gr.Markdown(
"Upload a CSV file with the data to fit. The last column will be used as the target variable."
)
return dict(
file_input=file_input,
test_equation=test_equation,
num_points=num_points,
noise_level=noise_level,
example_plot=example_plot,
)
def _settings_layout():
binary_operators = gr.CheckboxGroup(
choices=["+", "-", "*", "/", "^"],
label="Binary Operators",
value=["+", "-", "*", "/"],
)
unary_operators = gr.CheckboxGroup(
choices=[
"sin",
"cos",
"exp",
"log",
"square",
"cube",
"sqrt",
"abs",
"tan",
],
label="Unary Operators",
value=[],
)
niterations = gr.Slider(
minimum=1,
maximum=1000,
value=40,
label="Number of Iterations",
step=1,
)
maxsize = gr.Slider(
minimum=7,
maximum=35,
value=20,
label="Maximum Complexity",
step=1,
)
seed = gr.Number(
value=0,
label="Random Seed",
)
force_run = gr.Checkbox(
value=False,
label="Ignore Warnings",
)
return dict(
binary_operators=binary_operators,
unary_operators=unary_operators,
niterations=niterations,
maxsize=maxsize,
force_run=force_run,
seed=seed,
)
def main():
blocks = {}
with gr.Blocks() as demo:
with gr.Row():
with gr.Column():
with gr.Row():
blocks = {**blocks, **_data_layout()}
with gr.Row():
blocks = {**blocks, **_settings_layout()}
with gr.Column():
blocks["df"] = gr.Dataframe(
headers=["complexity", "loss", "equation"],
datatype=["number", "number", "str"],
)
blocks["run"] = gr.Button()
blocks["run"].click(
_greet_dispatch,
inputs=[
blocks[k]
for k in [
"file_input",
"force_run",
"test_equation",
"num_points",
"noise_level",
"niterations",
"maxsize",
"binary_operators",
"unary_operators",
"seed",
]
],
outputs=[blocks["df"]],
)
# Any update to the equation choice will trigger a replot:
eqn_components = [
blocks["test_equation"],
blocks["num_points"],
blocks["noise_level"],
]
for eqn_component in eqn_components:
eqn_component.change(replot, eqn_components, blocks["example_plot"])
demo.launch(debug=True)
def replot(test_equation, num_points, noise_level):
X, y = generate_data(test_equation, num_points, noise_level)
df = pd.DataFrame({"x": X["x"], "y": y})
return df
if __name__ == "__main__":
main()
|