ranimeree commited on
Commit
e6c7a23
·
verified ·
1 Parent(s): 3b173d8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +30 -61
app.py CHANGED
@@ -1,82 +1,51 @@
1
  import gradio as gr
2
  import pandas as pd
3
  import numpy as np
4
- import os
5
- import joblib # Change to joblib for direct loading
6
 
7
- # Load the model - for Hugging Face deployment
8
- try:
9
- # Load model directly from python_model.pkl
10
- model = joblib.load("python_model.pkl")
11
- print("Model loaded successfully")
12
- print("Model type:", type(model))
13
-
14
- except Exception as e:
15
- print(f"Error loading model: {str(e)}")
16
- print(f"Current working directory: {os.getcwd()}")
17
- print("Files in current directory:", os.listdir())
18
- raise
19
 
20
- def predict_stroke_risk(age, gender, hypertension, heart_disease, ever_married,
21
- work_type, residence_type, avg_glucose_level, bmi, smoking_status):
22
- """Make stroke prediction with the trained model"""
23
- try:
24
- # Create a DataFrame with the input data
25
- data = pd.DataFrame({
26
- 'gender': [gender],
27
- 'age': [float(age)],
28
- 'hypertension': [int(hypertension)],
29
- 'heart_disease': [int(heart_disease)],
30
- 'ever_married': [ever_married],
31
- 'work_type': [work_type],
32
- 'Residence_type': [residence_type],
33
- 'avg_glucose_level': [float(avg_glucose_level)],
34
- 'bmi': [float(bmi)],
35
- 'smoking_status': [smoking_status]
36
- })
37
-
38
- # Make prediction
39
- prediction = model.predict(data)
40
- probability = model.predict_proba(data)[0][1]
41
-
42
- # Create result message
43
- if prediction[0] == 1:
44
- result = f"High Risk of Stroke (Probability: {probability:.2%})"
45
- else:
46
- result = f"Low Risk of Stroke (Probability: {probability:.2%})"
47
-
48
- return result
49
- except Exception as e:
50
- print(f"Error during prediction: {str(e)}")
51
- return f"Error making prediction: {str(e)}"
52
 
53
  # Create the Gradio interface
54
  iface = gr.Interface(
55
- fn=predict_stroke_risk,
56
  inputs=[
57
- gr.Slider(minimum=0, maximum=120, step=1, label="Age"),
58
  gr.Dropdown(choices=["Male", "Female"], label="Gender"),
 
59
  gr.Checkbox(label="Hypertension"),
60
  gr.Checkbox(label="Heart Disease"),
61
  gr.Dropdown(choices=["Yes", "No"], label="Ever Married"),
62
- gr.Dropdown(
63
- choices=["Private", "Self-employed", "Govt_job", "children", "Never_worked"],
64
- label="Work Type"
65
- ),
66
  gr.Dropdown(choices=["Urban", "Rural"], label="Residence Type"),
67
- gr.Slider(minimum=50, maximum=300, step=1, label="Average Glucose Level"),
68
- gr.Slider(minimum=10, maximum=70, step=0.1, label="BMI"),
69
- gr.Dropdown(
70
- choices=["formerly smoked", "never smoked", "smokes", "Unknown"],
71
- label="Smoking Status"
72
- )
 
73
  ],
74
- outputs=gr.Text(label="Prediction Result"),
75
  title="Stroke Risk Prediction",
76
  description="Enter patient information to predict stroke risk.",
77
  examples=[
78
- [67, "Male", True, False, "Yes", "Private", "Urban", 228.69, 36.6, "formerly smoked"],
79
- [61, "Female", False, False, "Yes", "Self-employed", "Rural", 202.21, 30.0, "never smoked"]
 
80
  ]
81
  )
82
 
 
1
  import gradio as gr
2
  import pandas as pd
3
  import numpy as np
4
+ import pickle
5
+ from sklearn.ensemble import RandomForestClassifier
6
 
7
+ # Load the trained model
8
+ model = pickle.load(open('stroke_prediction_model.pkl', 'rb'))
 
 
 
 
 
 
 
 
 
 
9
 
10
+ def predict_stroke(gender, age, hypertension, heart_disease, ever_married,
11
+ work_type, residence_type, avg_glucose_level, bmi, smoking_status):
12
+ # Create a DataFrame with the input features
13
+ input_data = pd.DataFrame([[gender, age, hypertension, heart_disease, ever_married,
14
+ work_type, residence_type, avg_glucose_level, bmi, smoking_status]],
15
+ columns=['gender', 'age', 'hypertension', 'heart_disease', 'ever_married',
16
+ 'work_type', 'Residence_type', 'avg_glucose_level', 'bmi', 'smoking_status'])
17
+
18
+ # Make prediction
19
+ prediction = model.predict(input_data)[0]
20
+ probability = model.predict_proba(input_data)[0][1]
21
+
22
+ return "High Risk" if prediction == 1 else "Low Risk", f"{probability:.2%}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
 
24
  # Create the Gradio interface
25
  iface = gr.Interface(
26
+ fn=predict_stroke,
27
  inputs=[
 
28
  gr.Dropdown(choices=["Male", "Female"], label="Gender"),
29
+ gr.Slider(minimum=0, maximum=100, label="Age"),
30
  gr.Checkbox(label="Hypertension"),
31
  gr.Checkbox(label="Heart Disease"),
32
  gr.Dropdown(choices=["Yes", "No"], label="Ever Married"),
33
+ gr.Dropdown(choices=["Private", "Self-employed", "Govt_job", "children", "Never_worked"], label="Work Type"),
 
 
 
34
  gr.Dropdown(choices=["Urban", "Rural"], label="Residence Type"),
35
+ gr.Slider(minimum=50, maximum=300, label="Average Glucose Level"),
36
+ gr.Slider(minimum=10, maximum=100, label="BMI"),
37
+ gr.Dropdown(choices=["formerly smoked", "never smoked", "smokes", "Unknown"], label="Smoking Status")
38
+ ],
39
+ outputs=[
40
+ gr.Label(label="Stroke Risk"),
41
+ gr.Label(label="Probability")
42
  ],
 
43
  title="Stroke Risk Prediction",
44
  description="Enter patient information to predict stroke risk.",
45
  examples=[
46
+ ["Male", 67, True, True, "Yes", "Private", "Urban", 228.69, 36.6, "formerly smoked"],
47
+ ["Female", 61, False, False, "Yes", "Self-employed", "Rural", 202.21, 30.0, "never smoked"],
48
+ ["Male", 80, False, True, "Yes", "Private", "Rural", 105.92, 32.5, "never smoked"]
49
  ]
50
  )
51