import pandas as pd import numpy as np import gradio as gr import os from sklearn.ensemble import GradientBoostingRegressor import joblib from sklearn.impute import SimpleImputer from sklearn.pipeline import Pipeline from sklearn.compose import ColumnTransformer from sklearn.preprocessing import ( MinMaxScaler, OneHotEncoder, OrdinalEncoder, StandardScaler, PolynomialFeatures, FunctionTransformer, ) #Load preprocessing and model pipelines preprocessor_file = os.path.join('model', 'preprocessor.pkl') #Parámetros preprocessor = joblib.load(preprocessor_file) model_file = os.path.join('model', 'model.pkl') #Parámetros model = joblib.load(model_file) explainer_file = os.path.join('model', 'shapExplainer.pkl') #Parámetros explainer = joblib.load(preprocessor_file) # Function to make prediction and generate SHAP force plot def predict_and_plot(X_test): X_test = preprocessor['preprocessor'].transform(X_test) prediction = model.predict(X_test)[0] # Generate SHAP force plot shap_values_single = explainer(input_array) force_plot_html = shap.force_plot(explainer.expected_value, shap_values_single.values, input_array, matplotlib=False) # Save the SHAP force plot to an HTML file shap_html_path = "force_plot.html" shap.save_html(shap_html_path, force_plot_html) return prediction, shap_html_path # Define the Gradio interface # Define the Gradio interface input_df = gr.Dataframe(headers=preprocessor['cols'], row_count=1, col_count=len(preprocessor['cols'])) iface = gr.Interface( fn=predict_and_plot, inputs=input_df, outputs=[gr.Textbox(label="Predicted Value"), gr.HTML(label="SHAP Force Plot")], live=True ) # Launch the Gradio app iface.launch(share=True)