Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import numpy as np
|
3 |
+
from joblib import load
|
4 |
+
from tensorflow.keras.models import load_model
|
5 |
+
import tensorflow as tf
|
6 |
+
import pickle
|
7 |
+
|
8 |
+
# Load the LabelEncoder from Hugging Face Space
|
9 |
+
with open('label_encoder.pkl', 'rb') as f:
|
10 |
+
label_encoder = pickle.load(f)
|
11 |
+
|
12 |
+
# Assuming 'ct' is your ColumnTransformer (replace this with the actual loading code for your preprocessor)
|
13 |
+
# If you have a preprocessor file (such as a pickle file), you can load it here, e.g.,
|
14 |
+
# with open('column_transformer.pkl', 'rb') as f:
|
15 |
+
# ct = pickle.load(f)
|
16 |
+
|
17 |
+
# UI Components for user input
|
18 |
+
input_Gender = gr.Radio(["male", "female"], label="Gender")
|
19 |
+
input_Race = gr.Dropdown(list(dict(df['Race (Reported)'].value_counts()).keys()), label="Race")
|
20 |
+
input_Age = gr.Dropdown(list(dict(df['Age'].value_counts())), label='Age')
|
21 |
+
input_Height = gr.Number(label='Height (cm)')
|
22 |
+
input_Weight = gr.Number(label='Weight (kg)')
|
23 |
+
input_Diabetes = gr.Radio([0.0, 1.0], label='Diabetes')
|
24 |
+
input_Simvastatin = gr.Radio([0.0, 1.0], label='Simvastatin (Zocor)')
|
25 |
+
input_Amiodarone = gr.Radio([0.0, 1.0], label='Amiodarone (Cordarone)')
|
26 |
+
input_INR_reported = gr.Number(label='INR on Reported Therapeutic Dose of Warfarin')
|
27 |
+
input_Cyp2C9_genotypes = gr.Dropdown(list(dict(df['Cyp2C9 genotypes'].value_counts())), label='Cyp2C9 genotypes')
|
28 |
+
input_VKORC1_genotypes = gr.Radio(list(dict(df['VKORC1 genotype: -1639 G>A (3673); chr16:31015190; rs9923231; C/T'].value_counts())), label='VKORC1 genotypes')
|
29 |
+
input_model = gr.Dropdown(['Decision Tree Regression', 'Support Vector Regression', 'Random Forest Regression', 'Deep Learning'], label='Model Selection')
|
30 |
+
|
31 |
+
# Output textbox to display predicted dose
|
32 |
+
output_warfarin_dosage = gr.Textbox(label='Therapeutic Dose of Warfarin')
|
33 |
+
|
34 |
+
# Prediction function with renamed input variables
|
35 |
+
def predict_dosage(gender, race, age, height, weight, diabetes, simvastatin, amiodarone, inr, cyp2c9, vkorc1, selected_model):
|
36 |
+
import numpy as np
|
37 |
+
from joblib import load
|
38 |
+
from tensorflow.keras.models import load_model
|
39 |
+
import tensorflow as tf
|
40 |
+
|
41 |
+
# Optional debug function to inspect data before prediction
|
42 |
+
def print_input_debug(transformed_input, final_array):
|
43 |
+
print("Transformed input shape:", transformed_input.shape)
|
44 |
+
print("Final input shape:", final_array.shape)
|
45 |
+
print("Input data type:", final_array.dtype)
|
46 |
+
|
47 |
+
try:
|
48 |
+
# Load the selected model
|
49 |
+
if selected_model == 'Deep Learning':
|
50 |
+
model = load_model('best_DeepLearning_model.h5')
|
51 |
+
elif selected_model == 'Support Vector Regression':
|
52 |
+
model = load('SVR_optimized.joblib')
|
53 |
+
elif selected_model == 'Random Forest Regression':
|
54 |
+
model = load('RandomForestRegressor_optimized.joblib')
|
55 |
+
else:
|
56 |
+
model = load("DecisionTreeRegressor_optimized.joblib")
|
57 |
+
|
58 |
+
# Handle unseen labels by attempting to map them to known labels
|
59 |
+
def safe_transform_label(encoder, label, default=None):
|
60 |
+
try:
|
61 |
+
return encoder.transform([label])[0]
|
62 |
+
except ValueError:
|
63 |
+
# If label is unseen, return default (e.g., most frequent label or a fallback value)
|
64 |
+
return default if default is not None else encoder.transform([encoder.classes_[0]])[0]
|
65 |
+
|
66 |
+
# Encode Age using LabelEncoder (catching unseen labels)
|
67 |
+
encoded_age = safe_transform_label(label_encoder, age, default=label_encoder.classes_[0])
|
68 |
+
|
69 |
+
# Ensure numerical inputs are valid floats
|
70 |
+
height = float(height) if height is not None else 0.0
|
71 |
+
weight = float(weight) if weight is not None else 0.0
|
72 |
+
inr = float(inr) if inr is not None else 0.0
|
73 |
+
|
74 |
+
# Assemble input for transformation
|
75 |
+
raw_inputs = [
|
76 |
+
str(gender),
|
77 |
+
str(race),
|
78 |
+
str(age),
|
79 |
+
height,
|
80 |
+
weight,
|
81 |
+
float(diabetes),
|
82 |
+
float(simvastatin),
|
83 |
+
float(amiodarone),
|
84 |
+
inr,
|
85 |
+
str(cyp2c9),
|
86 |
+
str(vkorc1)
|
87 |
+
]
|
88 |
+
|
89 |
+
# Apply preprocessing pipeline (ct should be defined or loaded)
|
90 |
+
transformed_input = ct.transform([raw_inputs])
|
91 |
+
transformed_input[0][-7] = encoded_age # Age is encoded, so replace it in the transformed input
|
92 |
+
|
93 |
+
# Convert to NumPy array for model input
|
94 |
+
input_array = np.array(transformed_input, dtype=np.float32)
|
95 |
+
print_input_debug(transformed_input, input_array)
|
96 |
+
|
97 |
+
# Predict using appropriate model type
|
98 |
+
if selected_model == 'Deep Learning':
|
99 |
+
tensor_input = tf.convert_to_tensor(input_array)
|
100 |
+
prediction = model.predict(tensor_input, verbose=0)
|
101 |
+
return float(prediction[0][0])
|
102 |
+
else:
|
103 |
+
prediction = model.predict(input_array)
|
104 |
+
return float(prediction[0])
|
105 |
+
|
106 |
+
except Exception as e:
|
107 |
+
print(f"Error in prediction: {str(e)}")
|
108 |
+
return f"Error in prediction: {str(e)}"
|
109 |
+
|
110 |
+
# Launch Gradio app
|
111 |
+
gr.Interface(
|
112 |
+
fn=predict_dosage,
|
113 |
+
inputs=[
|
114 |
+
input_Gender, input_Race, input_Age, input_Height, input_Weight,
|
115 |
+
input_Diabetes, input_Simvastatin, input_Amiodarone,
|
116 |
+
input_INR_reported, input_Cyp2C9_genotypes, input_VKORC1_genotypes, input_model
|
117 |
+
],
|
118 |
+
outputs=[output_warfarin_dosage]
|
119 |
+
).launch(debug=True)
|