3v324v23 commited on
Commit
7c2f911
·
1 Parent(s): c3c28df

fixed demo

Browse files
Files changed (1) hide show
  1. app.py +36 -24
app.py CHANGED
@@ -8,7 +8,7 @@ import pandas as pd
8
  from ControllableNesymres.architectures.data import compute_properties, create_negatives,\
9
  prepare_negative_pool, sympify_equation,\
10
  return_costants, description2tokens, prepare_pointers,\
11
- tokenize, is_token_constant
12
  import base64
13
  import streamlit as st
14
  from ControllableNesymres.dataset.generator import Generator
@@ -92,17 +92,25 @@ def main():
92
  cfg.inference.bfgs.activated = True
93
  cfg.inference.bfgs.n_restarts=10
94
  cfg.inference.n_jobs=-1
 
 
95
  cfg.inference.beam_size = beam_size
96
 
97
  metadata = retrofit_word2id(metadata, cfg)
98
 
99
  is_cuda = False #st.checkbox("Tick this if you want to load the models into the GPU", True)
100
-
 
 
 
 
 
 
101
 
102
  negative_pool = prepare_negative_pool(cfg)
103
 
104
  st.markdown("### Define the equation to test")
105
- equation_examples = ["0.01*x_1**2+x_2+exp(x_3)+x_4", "sin(x_1)+sqrt(x_2)+sin(x_3/2+x_4)", "x_1**(1/2)+0.3*x_2**2+x_3**2", "exp(0.043*sin(x_1*x_2))+x_3+3*x_4", "0.2*x_1**2+x_2**2+(x_3*x_4**2)", "other"]
106
  eq_string = st.selectbox("Select an equation or select on 'other' to write your own equation to test", equation_examples, index=4)
107
 
108
  if eq_string == "other":
@@ -116,18 +124,28 @@ def main():
116
  variables = sorted([str(x) for x in tmp])
117
  f = sympy.lambdify(variables, eq_sympy_infix_with_constants)
118
 
119
- number_of_points = st.number_input("Select the number of points that you would like to be sampled", 10, 1000, 100)
120
  noise_applied = st.number_input("Select the amount of noise to be applied to the Y", 0.0, 1.0, 0.0)
121
 
122
- # Sample the points
123
- X = np.random.uniform(-10, 10, (number_of_points, len(variables)))
124
- X_dict = {}
125
- for idx, var in enumerate(variables):
126
- X_dict[var] = torch.tensor(X[:,idx:idx+1]).half()
127
-
128
- y = f(**X_dict).T + np.random.normal(0, noise_applied, number_of_points)
129
- y = y.squeeze()
 
 
 
130
 
 
 
 
 
 
 
 
131
  if is_cuda:
132
  X = torch.tensor(X).cuda()
133
  y = torch.tensor(y).cuda()
@@ -144,7 +162,7 @@ def main():
144
  """
145
  )
146
 
147
- conditioning_to_give = st.multiselect("Select conditionings:", ["Complexity", "Symmetry", "Appearing branches", "Absent branches"], [])
148
  pointer_words = None
149
  description = {"positive_prefix_examples": [], "negative_prefix_examples": []}
150
  if "Complexity" in conditioning_to_give:
@@ -164,7 +182,7 @@ def main():
164
  if "Appearing branches" in conditioning_to_give:
165
  st.markdown("###### Appearing branches")
166
  gt_appearing_branches = properties["all_positives_examples"]
167
- appearing_branches = st.multiselect("Select which appearing branches to pass (Max 2)", gt_appearing_branches, gt_appearing_branches[0:2])
168
  assert len(appearing_branches) <= 2, "You can only select up to 2 appearing branches"
169
  # for branch in appearing_branches:
170
  # mix_ptr_constants(branch, cfg)
@@ -233,14 +251,10 @@ def main():
233
  conditioning = {"symbolic_conditioning": cond_tokens, "numerical_conditioning": torch.tensor(numberical_conditioning).float()}
234
  #conditioning = {"symbolic_conditioning": torch.tensor([1,2],device="cuda").long(), "numerical_conditioning": torch.tensor([],device="cuda").float()}
235
 
236
- st.markdown("#### NSR")
237
- do_inference_with_also_nsr = st.checkbox("Tick this if you want to also run the NSR model", False)
238
- if do_inference_with_also_nsr:
239
- nsr = st.text_input("Path to the NSR model", "ControllableNeuralSymbolicRegressionWeights/nsr_200000000_epoch=149.ckpt")
240
-
241
  fit = st.button("Run the model")
242
  if fit:
243
- st.write("Results are being computed, please wait...")
244
  if is_cuda:
245
  fitfunc = return_fitfunc(cfg, metadata, nsrwh, device="cuda")
246
  else:
@@ -248,7 +262,7 @@ def main():
248
 
249
  new_outputs = fitfunc(X, y,conditioning, cond_str_tokens, is_batch=False)
250
 
251
- st.markdown("### Model Evaluation")
252
  st.markdown("#### NSRwH")
253
 
254
  best_prediction = new_outputs["best_pred"]
@@ -265,9 +279,7 @@ def main():
265
  st.latex(f"\\text{{Prediction {idx+1}: }} {sympy.latex(pred)}")
266
 
267
 
268
-
269
- if do_inference_with_also_nsr:
270
- st.write("Results for nsr are being computed, please wait...")
271
  cfg_nsr = omegaconf.OmegaConf.load(Path("configs/nsr_network_config.yaml"))
272
  cfg_nsr.inference.bfgs.activated = True
273
  cfg_nsr.inference.bfgs.n_restarts=10
 
8
  from ControllableNesymres.architectures.data import compute_properties, create_negatives,\
9
  prepare_negative_pool, sympify_equation,\
10
  return_costants, description2tokens, prepare_pointers,\
11
+ tokenize, is_token_constant, get_robust_random_data, return_support_limits,sample_support,sample_images
12
  import base64
13
  import streamlit as st
14
  from ControllableNesymres.dataset.generator import Generator
 
92
  cfg.inference.bfgs.activated = True
93
  cfg.inference.bfgs.n_restarts=10
94
  cfg.inference.n_jobs=-1
95
+ cfg.dataset.fun_support.max =5
96
+ cfg.dataset.fun_support.min = -5
97
  cfg.inference.beam_size = beam_size
98
 
99
  metadata = retrofit_word2id(metadata, cfg)
100
 
101
  is_cuda = False #st.checkbox("Tick this if you want to load the models into the GPU", True)
102
+
103
+ do_inference_with_also_nsr = st.checkbox("Tick this if you want to also run the NSR model", True)
104
+ if do_inference_with_also_nsr:
105
+ nsr = "ControllableNeuralSymbolicRegressionWeights/nsr_200000000_epoch=149.ckpt"
106
+ else:
107
+ nsr = None
108
+
109
 
110
  negative_pool = prepare_negative_pool(cfg)
111
 
112
  st.markdown("### Define the equation to test")
113
+ equation_examples = ["0.01*x_1+x_2+exp(x_3)", "sin(x_1)+sqrt(x_2)+sin(x_3+x_4)", "0.5*x_1**(1/2)+x_2**2 + x_3**2", "exp(0.043*sin(x_1*x_2))+x_3", "x_1**2+log(x_3+x_2)", "other"]
114
  eq_string = st.selectbox("Select an equation or select on 'other' to write your own equation to test", equation_examples, index=4)
115
 
116
  if eq_string == "other":
 
124
  variables = sorted([str(x) for x in tmp])
125
  f = sympy.lambdify(variables, eq_sympy_infix_with_constants)
126
 
127
+ number_of_points = st.number_input("Select the number of points that you would like to be sampled", 10, 1000, 200)
128
  noise_applied = st.number_input("Select the amount of noise to be applied to the Y", 0.0, 1.0, 0.0)
129
 
130
+ cnt = 0
131
+ MAX_ATTEMPTS = 5
132
+ while cnt < MAX_ATTEMPTS:
133
+ support_limits = return_support_limits(cfg, metadata, support=None)
134
+ support = sample_support(support_limits, variables, cfg.dataset.max_number_of_points*5, metadata.total_variables, cfg)
135
+ is_valid, data_points = sample_images(f, support, variables, cfg)
136
+ if is_valid:
137
+ break
138
+ cnt += 1
139
+ if not is_valid:
140
+ raise ValueError("Could not find a valid support")
141
 
142
+ # Shuffle the datapoints along the points dimension
143
+ data_points = data_points[:, :, torch.randperm(data_points.shape[2])]
144
+ data_points = data_points[:, :, :number_of_points]
145
+ X = data_points[0,:5,:].T
146
+ y = data_points[0,5,:]
147
+
148
+
149
  if is_cuda:
150
  X = torch.tensor(X).cuda()
151
  y = torch.tensor(y).cuda()
 
162
  """
163
  )
164
 
165
+ conditioning_to_give = st.multiselect("Select conditionings:", ["Complexity", "Symmetry", "Appearing branches", "Absent branches"], ["Appearing branches"])
166
  pointer_words = None
167
  description = {"positive_prefix_examples": [], "negative_prefix_examples": []}
168
  if "Complexity" in conditioning_to_give:
 
182
  if "Appearing branches" in conditioning_to_give:
183
  st.markdown("###### Appearing branches")
184
  gt_appearing_branches = properties["all_positives_examples"]
185
+ appearing_branches = st.multiselect("Select which appearing branches to pass (Max 2)", gt_appearing_branches, gt_appearing_branches[2:3]+ gt_appearing_branches[10:11])
186
  assert len(appearing_branches) <= 2, "You can only select up to 2 appearing branches"
187
  # for branch in appearing_branches:
188
  # mix_ptr_constants(branch, cfg)
 
251
  conditioning = {"symbolic_conditioning": cond_tokens, "numerical_conditioning": torch.tensor(numberical_conditioning).float()}
252
  #conditioning = {"symbolic_conditioning": torch.tensor([1,2],device="cuda").long(), "numerical_conditioning": torch.tensor([],device="cuda").float()}
253
 
254
+
 
 
 
 
255
  fit = st.button("Run the model")
256
  if fit:
257
+ st.write("Results are being computed, will be displayed in a few seconds...")
258
  if is_cuda:
259
  fitfunc = return_fitfunc(cfg, metadata, nsrwh, device="cuda")
260
  else:
 
262
 
263
  new_outputs = fitfunc(X, y,conditioning, cond_str_tokens, is_batch=False)
264
 
265
+ st.markdown("### Results")
266
  st.markdown("#### NSRwH")
267
 
268
  best_prediction = new_outputs["best_pred"]
 
279
  st.latex(f"\\text{{Prediction {idx+1}: }} {sympy.latex(pred)}")
280
 
281
 
282
+ if nsr is not None:
 
 
283
  cfg_nsr = omegaconf.OmegaConf.load(Path("configs/nsr_network_config.yaml"))
284
  cfg_nsr.inference.bfgs.activated = True
285
  cfg_nsr.inference.bfgs.n_restarts=10