Axwell15/AN_proyecto
0
1import gradio as gr2import csv3import os4import numpy as np5from sklearn.datasets import load_iris6from sklearn.preprocessing import StandardScaler7 8 9# ---------CONFIGURACIÓN DE HISTORIAL----------10HISTORY_FILE = "historial.csv"11 12def load_history():13 if os.path.exists(HISTORY_FILE):14 with open(HISTORY_FILE, mode="r", newline="") as f:15 reader = csv.reader(f)16 #Convirtiendo a float 17 return[18 [float(row[0]), float(row[1]), float(row[2]), float(row[3]), row[4]]19 for row in reader20 ]21 return []22 23def save_history_row(row):24 with open(HISTORY_FILE, mode="a", newline="") as f:25 writer = csv.writer(f)26 writer.writerow(row)27 28def clear_history_file():29 if os.path.exists(HISTORY_FILE):30 os.remove(HISTORY_FILE)31 32 33# Cargar el conjunto de datos Iris34iris = load_iris()35X_iris = iris.data36y_iris = iris.target37 38# --------- Custom Logistic Regression (One-vs-Rest, Gradient Descent) ---------39def sigmoid(z):40 return 1 / (1 + np.exp(-z))41 42def gradient_descent(X, y, lr=0.1, epochs=1000):43 m, n = X.shape44 X = np.hstack((np.ones((m,1)), X))45 weights = np.zeros(n + 1)46 for _ in range(epochs):47 z = np.dot(X, weights)48 h = sigmoid(z)49 grad = np.dot(X.T, (h - y)) / m50 weights -= lr * grad51 return weights52 53def predict_custom(X, weights_all):54 X = np.hstack((np.ones((X.shape[0],1)), X))55 preds = np.array([sigmoid(np.dot(X, w)) for w in weights_all]).T56 return np.argmax(preds, axis=1)57 58# Escalar los datos para el modelo personalizado59scaler_custom = StandardScaler()60X_iris_scaled = scaler_custom.fit_transform(X_iris)61 62# Entrenar modelo personalizado One-vs-Rest63weights_all_custom = []64for class_label in np.unique(y_iris):65 y_binary = (y_iris == class_label).astype(int)66 weights = gradient_descent(X_iris_scaled, y_binary, lr=0.1, epochs=1000)67 weights_all_custom.append(weights)68 69 70# ------------------- Función de predicción -------------------71def predict(sepal_length, sepal_width, petal_length, petal_width):72 if all(float(val) == 0.0 for val in [sepal_length, sepal_width, petal_length, petal_width]):73 return "⚠️ Por favor ingresa valores válidos (mayores a cero).", load_history(), None74 input_data = np.array([[sepal_length, sepal_width, petal_length, petal_width]])75 input_scaled = scaler_custom.transform(input_data)76 pred_idx = predict_custom(input_scaled, weights_all_custom)[0]77 class_name = iris.target_names[pred_idx]78 result = f"Predicción (Regresión Logística Custom GD): {class_name}"79 80 image_path = f"./imagenes/{class_name}.jpg"81 row = [sepal_length, sepal_width, petal_length, petal_width, class_name]82 83 history = load_history()84 history.append(row)85 save_history_row(row)86 87 return result, history, image_path88 89 90 91# ------------------- Función para limpiar las entradas -------------------92def clear_inputs():93 clear_history_file()94 return 0.0, 0.0, 0.0, 0.0, [], None95 96# ------------------- Interfaz de Gradio -------------------97def iris_interface():98 history = load_history()99 with gr.Blocks() as demo:100 gr.Markdown("## Clasificación Iris con Regresión Logística (Descenso de Gradiente Custom)")101 with gr.Row():102 with gr.Column(scale=2):103 with gr.Row():104 sepal_length = gr.Number(label="Sepal Length (cm)", value=0.0)105 sepal_width = gr.Number(label="Sepal Width (cm)", value=0.0)106 petal_length = gr.Number(label="Petal Length (cm)", value=0.0)107 petal_width = gr.Number(label="Petal Width (cm)", value=0.0)108 output = gr.Textbox(label="Output")109 with gr.Column(scale=4):110 with gr.Row():111 with gr.Column(scale=1):112 image_output = gr.Image(113 label="Imagen de la Flor",114 type="filepath",115 interactive=False,116 height=267,117 width=300,118 )119 clear_button = gr.Button("Clear")120 submit_button = gr.Button("Submit")121 122 123 history_output = gr.Dataframe(124 headers=["Sepal Length", "Sepal Width", "Petal Length", "Petal Width", "Predicción"],125 label="Historial de Predicciones",126 interactive=False,127 wrap=True,128 value=history 129 )130 131 submit_button.click(132 predict,133 inputs=[sepal_length, sepal_width, petal_length, petal_width],134 outputs=[output, history_output, image_output]135 )136 137 clear_button.click(138 clear_inputs,139 inputs=[],140 outputs=[sepal_length, sepal_width, petal_length, petal_width, history_output, image_output]141 )142 143 144# Lanzar la aplicación145 return demo146 