cuadratica / app.py
Cast094's picture
Update app.py
c48750c verified
raw
history blame contribute delete
No virus
2.13 kB
import streamlit as st
import numpy as np
import matplotlib.pyplot as plt
import optuna
# T铆tulo de la aplicaci贸n
st.title("Optimization tool")
# Selecci贸n de la funci贸n
func_user = st.selectbox("Choose a function:", ("cuadratic", "sine", "gaussian"))
# ("sin(x/10)", "(x-2)^2", "exp-(x-4)^2")
# Definici贸n de las funciones a optimizar
def func_cuadratic(x):
return (x - 2) ** 2
def func_sine(x):
return np.sin(x / 10)
def func_gauss(x):
return np.exp(-((x - 4) ** 2))
# Mostrar la f贸rmula de la funci贸n seleccionada y asignar la funci贸n correspondiente
if func_user == "cuadratic":
st.latex(r"(x - 2)^2")
func_to_use = func_cuadratic
elif func_user == "sine":
st.latex(r"sin({ x \over 10 })")
func_to_use = func_sine
else:
st.latex(r"e^{-(x-4)^2}")
func_to_use = func_gauss
# Selecci贸n de la direcci贸n de optimizaci贸n
opt_user = st.selectbox("Choose the optimization direction:", ("minimize", "maximize"))
# Entrada de los l铆mites inferiores y superiores
x_low = st.number_input("Please, give me the lower bound:", value=-10)
x_upp = st.number_input("Please, give me the upper bound:", value=10)
# Definici贸n de la funci贸n objetivo para Optuna
def objective(trial):
x = trial.suggest_float("x", x_low, x_upp)
return func_to_use(x)
# Crear el estudio de Optuna
study = optuna.create_study(direction=opt_user)
# Ejecutar la optimizaci贸n
study.optimize(objective, n_trials=500)
# Obtener el valor 贸ptimo de x y la funci贸n en ese punto
x_opt = study.best_params["x"]
y_opt = func_to_use(x_opt)
# Mostrar los resultados de la optimizaci贸n
st.write(f"The critical point found is ({x_opt:,.4f}, {y_opt:,.4f}).")
# Visualizaci贸n de los resultados
x_to_use = np.linspace(x_low, x_upp)
plt.title("Plot of critical point within interval given by user")
plt.xlabel("x axis")
plt.ylabel("y axis")
plt.plot(x_to_use, func_to_use(x_to_use))
plt.scatter(x_opt, func_to_use(x_opt), c="red")
plt.annotate(
f"({x_opt:,.2f}, {y_opt:,.2f})",
(x_opt, y_opt),
textcoords="offset points",
ha="center",
)
# Mostrar la gr谩fica en Streamlit
st.pyplot(plt)