hackerbyhobby commited on
Commit
d59529d
·
unverified ·
1 Parent(s): b6bf83e
Files changed (1) hide show
  1. app.py +22 -59
app.py CHANGED
@@ -1,50 +1,27 @@
1
 
 
 
 
 
2
  import gradio as gr
3
  import joblib
4
- import numpy as np
5
  import pandas as pd
6
 
7
- # Load the trained model
8
- model_path = "trained_model.pkl"
9
 
10
- def load_model(path):
11
- try:
12
- return joblib.load(path)
13
- except Exception as e:
14
- raise ValueError(f"Error loading model: {e}")
 
15
 
16
  # Define the prediction function
17
- def predict_heart_disease(
18
- PhysicalHealthDays: float,
19
- MentalHealthDays: float,
20
- SleepHours: float,
21
- BMI: float,
22
- PhysicalActivities: str,
23
- AlcoholDrinkers: str,
24
- HIVTesting: str,
25
- RemovedTeeth: str,
26
- HighRiskLastYear: str,
27
- CovidPos: str,
28
- ):
29
  try:
30
- model = load_model(model_path)
31
- # Encode categorical inputs as integers
32
- physical_activities = 1 if PhysicalActivities.lower() == "yes" else 0
33
- alcohol_drinkers = 1 if AlcoholDrinkers.lower() == "yes" else 0
34
- hiv_testing = 1 if HIVTesting.lower() == "yes" else 0
35
- removed_teeth = 1 if RemovedTeeth.lower() == "yes" else 0
36
- high_risk_last_year = 1 if HighRiskLastYear.lower() == "yes" else 0
37
- covid_pos = 1 if CovidPos.lower() == "yes" else 0
38
-
39
- # Combine inputs into a numpy array for prediction
40
- features = np.array([
41
- PhysicalHealthDays, MentalHealthDays, SleepHours, BMI,
42
- physical_activities, alcohol_drinkers, hiv_testing,
43
- removed_teeth, high_risk_last_year, covid_pos
44
- ]).reshape(1, -1)
45
-
46
- # Predict with the model
47
- prediction = model.predict(features)
48
  return "Heart Disease Risk" if prediction[0] == 1 else "No Risk"
49
  except Exception as e:
50
  return f"Error during prediction: {e}"
@@ -52,33 +29,19 @@ def predict_heart_disease(
52
  # Define the Gradio interface
53
  with gr.Blocks() as app:
54
  gr.Markdown("# Heart Disease Prediction App")
55
- gr.Markdown("### Provide input values and receive a prediction.")
56
-
57
- with gr.Row():
58
- PhysicalHealthDays = gr.Slider(0, 30, label="Physical Health Days")
59
- MentalHealthDays = gr.Slider(0, 30, label="Mental Health Days")
60
- SleepHours = gr.Slider(0, 24, label="Average Sleep Hours")
61
- BMI = gr.Slider(10, 50, label="Body Mass Index (BMI)")
62
-
63
- with gr.Row():
64
- PhysicalActivities = gr.Radio(["Yes", "No"], label="Engaged in Physical Activities?")
65
- AlcoholDrinkers = gr.Radio(["Yes", "No"], label="Consumes Alcohol?")
66
- HIVTesting = gr.Radio(["Yes", "No"], label="Tested for HIV?")
67
- RemovedTeeth = gr.Radio(["Yes", "No"], label="Has Removed Teeth?")
68
- HighRiskLastYear = gr.Radio(["Yes", "No"], label="High Risk Last Year?")
69
- CovidPos = gr.Radio(["Yes", "No"], label="Tested Positive for COVID-19?")
70
 
71
  predict_button = gr.Button("Predict")
72
  output = gr.Textbox(label="Prediction Result")
73
 
74
  # Connect prediction logic
75
  predict_button.click(
76
- fn=predict_heart_disease,
77
- inputs=[
78
- PhysicalHealthDays, MentalHealthDays, SleepHours, BMI,
79
- PhysicalActivities, AlcoholDrinkers, HIVTesting,
80
- RemovedTeeth, HighRiskLastYear, CovidPos
81
- ],
82
  outputs=output,
83
  )
84
 
 
1
 
2
+ """
3
+ Webapp Front End
4
+ """
5
+
6
  import gradio as gr
7
  import joblib
 
8
  import pandas as pd
9
 
10
+ MODEL_PATH = "Random_Foresttest_model.pkl"
 
11
 
12
+ try:
13
+ rf_model = joblib.load(MODEL_PATH)
14
+ except FileNotFoundError as e:
15
+ raise FileNotFoundError(
16
+ f"Model file not found at {MODEL_PATH}. Please check the path."
17
+ ) from e
18
 
19
  # Define the prediction function
20
+ def predict_with_model(State: float, Sex: float, GeneralHealth: float, PhysicalHealthDays: float, MentalHealthDays: float, LastCheckupTime: float, PhysicalActivities: float, SleepHours: float, HadStroke: float, HadArthritis: float, HadDiabetes: float, SmokerStatus: float, ECigaretteUsage: float, RaceEthnicityCategory: float, AgeCategory: float, HeightInMeters: float, WeightInKilograms: float, BMI: float, AlcoholDrinkers: float, HighRiskLastYear: float):
 
 
 
 
 
 
 
 
 
 
 
21
  try:
22
+ # Prepare input as a DataFrame
23
+ input_data = pd.DataFrame([[State, Sex, GeneralHealth, PhysicalHealthDays, MentalHealthDays, LastCheckupTime, PhysicalActivities, SleepHours, HadStroke, HadArthritis, HadDiabetes, SmokerStatus, ECigaretteUsage, RaceEthnicityCategory, AgeCategory, HeightInMeters, WeightInKilograms, BMI, AlcoholDrinkers, HighRiskLastYear]], columns=['State', 'Sex', 'GeneralHealth', 'PhysicalHealthDays', 'MentalHealthDays', 'LastCheckupTime', 'PhysicalActivities', 'SleepHours', 'HadStroke', 'HadArthritis', 'HadDiabetes', 'SmokerStatus', 'ECigaretteUsage', 'RaceEthnicityCategory', 'AgeCategory', 'HeightInMeters', 'WeightInKilograms', 'BMI', 'AlcoholDrinkers', 'HighRiskLastYear'])
24
+ prediction = rf_model.predict(input_data)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  return "Heart Disease Risk" if prediction[0] == 1 else "No Risk"
26
  except Exception as e:
27
  return f"Error during prediction: {e}"
 
29
  # Define the Gradio interface
30
  with gr.Blocks() as app:
31
  gr.Markdown("# Heart Disease Prediction App")
32
+ gr.Markdown("### Provide input values for the features below and get a prediction.")
33
+
34
+ input_components = []
35
+ for feature in ['State', 'Sex', 'GeneralHealth', 'PhysicalHealthDays', 'MentalHealthDays', 'LastCheckupTime', 'PhysicalActivities', 'SleepHours', 'HadStroke', 'HadArthritis', 'HadDiabetes', 'SmokerStatus', 'ECigaretteUsage', 'RaceEthnicityCategory', 'AgeCategory', 'HeightInMeters', 'WeightInKilograms', 'BMI', 'AlcoholDrinkers', 'HighRiskLastYear']:
36
+ input_components.append(gr.Slider(0, 100, step=1, label=feature))
 
 
 
 
 
 
 
 
 
 
37
 
38
  predict_button = gr.Button("Predict")
39
  output = gr.Textbox(label="Prediction Result")
40
 
41
  # Connect prediction logic
42
  predict_button.click(
43
+ fn=predict_with_model,
44
+ inputs=input_components,
 
 
 
 
45
  outputs=output,
46
  )
47