hackerbyhobby commited on
Commit
00b26e4
·
unverified ·
1 Parent(s): 136e0e8
Files changed (1) hide show
  1. app.py +43 -56
app.py CHANGED
@@ -1,61 +1,48 @@
1
  import gradio as gr
2
- import pandas as pd
3
  import json
4
- from sklearn.compose import ColumnTransformer
5
- from sklearn.preprocessing import StandardScaler, OneHotEncoder
6
-
7
- # Load selected features from JSON file
8
- with open("selected_features.json", "r") as file:
9
- selected_features = json.load(file)
10
-
11
- def preprocess_data(data):
12
- # Identify numerical and categorical columns
13
- numerical_cols = [col for col in data.columns if data[col].dtype in ['int64', 'float64']]
14
- categorical_cols = [col for col in data.columns if col not in numerical_cols]
15
-
16
- # Preprocessing pipeline
17
- preprocessor = ColumnTransformer(
18
- transformers=[
19
- ('num', StandardScaler(), numerical_cols),
20
- ('cat', OneHotEncoder(sparse_output=False, drop='first'), categorical_cols)
21
- ]
22
- )
23
-
24
- # Apply preprocessing
25
- processed_data = preprocessor.fit_transform(data)
26
- feature_names = numerical_cols + list(preprocessor.named_transformers_['cat'].get_feature_names_out(categorical_cols))
27
- return pd.DataFrame(processed_data, columns=feature_names)
28
-
29
- def process_manual_input(**kwargs):
30
- # Create a DataFrame for a single patient from keyword arguments
31
- input_data = pd.DataFrame([kwargs])
32
-
33
- # Preprocess the data
34
- processed_data = preprocess_data(input_data)
35
- return processed_data.to_csv(index=False)
36
-
37
- # GUI inputs for each feature
38
- gui_inputs = []
39
- for feature in selected_features:
40
- if feature.startswith("Had"): # Binary categorical features
41
- gui_inputs.append(gr.Radio(label=feature, choices=["Yes", "No"], value="No"))
42
- elif feature in ["BMI", "WeightInKilograms", "HeightInMeters"]: # Numerical features
43
- gui_inputs.append(gr.Slider(label=feature, minimum=0, maximum=300, step=0.1, value=25))
44
- elif feature == "PhysicalHealthDays": # Numerical feature with a smaller range
45
- gui_inputs.append(gr.Slider(label=feature, minimum=0, maximum=30, step=1, value=5))
46
- elif feature == "SleepHours": # Hours of sleep
47
- gui_inputs.append(gr.Slider(label=feature, minimum=0, maximum=24, step=0.5, value=8))
48
- else: # Default for any remaining numerical features
49
- gui_inputs.append(gr.Slider(label=feature, minimum=0, maximum=100, step=1, value=50))
50
-
51
- # Create the Gradio app interface
52
- interface = gr.Interface(
53
- fn=process_manual_input,
54
- inputs=gui_inputs,
55
- outputs=gr.Textbox(label="Processed Data (CSV Format)"),
56
- title="Single Patient Data Preprocessor",
57
- description="Input data for a single patient using sliders and radio buttons. The data will be preprocessed and displayed as CSV."
58
  )
59
 
60
  # Launch the app
61
- interface.launch()
 
 
1
  import gradio as gr
2
+ import joblib
3
  import json
4
+ import numpy as np
5
+
6
+ # Load the trained model
7
+ model = joblib.load('trained_model.pkl')
8
+
9
+ # Load feature names
10
+ with open('selected_features.json', 'r') as f:
11
+ feature_names = json.load(f)
12
+
13
+ # Define prediction function
14
+ def predict_heart_failure(*args):
15
+ """
16
+ Predict heart failure likelihood based on input features.
17
+
18
+ Args:
19
+ *args: Input values for each feature.
20
+
21
+ Returns:
22
+ str: Prediction result.
23
+ str: Prediction probability as a percentage.
24
+ """
25
+ input_data = np.array(args).reshape(1, -1)
26
+ prediction = model.predict(input_data)
27
+ probability = model.predict_proba(input_data)
28
+ result = "Likely" if prediction[0] == 1 else "Unlikely"
29
+ return result, f"{probability[0][1] * 100:.2f}%"
30
+
31
+ # Create Gradio interface
32
+ inputs = [gr.inputs.Number(label=feature) for feature in feature_names]
33
+ outputs = [
34
+ gr.outputs.Textbox(label="Prediction"),
35
+ gr.outputs.Textbox(label="Probability (%)")
36
+ ]
37
+
38
+ app = gr.Interface(
39
+ fn=predict_heart_failure,
40
+ inputs=inputs,
41
+ outputs=outputs,
42
+ title="Heart Failure Prediction",
43
+ description="Enter the values for the features to predict the likelihood of heart failure."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
  )
45
 
46
  # Launch the app
47
+ if __name__ == "__main__":
48
+ app.launch()