sreekar8811 commited on
Commit
a3fedfd
·
verified ·
1 Parent(s): 8150ffa

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +207 -202
app.py CHANGED
@@ -1,203 +1,208 @@
1
- import streamlit as st
2
- import pandas as pd
3
- import numpy as np
4
- import joblib
5
- import random
6
- from sklearn.preprocessing import StandardScaler
7
- from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix
8
- from tensorflow.keras.models import load_model
9
- import warnings
10
- warnings.filterwarnings("ignore")
11
-
12
- # Health tips
13
- HEALTH_TIPS = [
14
- "Regular exercise can reduce your risk of heart disease by up to 30%.",
15
- "Eating a handful of nuts daily can improve heart health.",
16
- "Reducing salt intake can help lower blood pressure.",
17
- "Aim for 7-8 hours of quality sleep each night for heart health.",
18
- "Quitting smoking can cut your heart disease risk in half within a year.",
19
- "Managing stress through meditation can benefit your cardiovascular system."
20
- ]
21
-
22
- # Load models
23
- def load_ml_model(model_path):
24
- return joblib.load(model_path)
25
-
26
- def load_dl_model(model_path):
27
- return load_model(model_path)
28
-
29
- # Load scaler
30
- scaler = load_ml_model("models/scaler.sav")
31
-
32
- # Page config
33
- st.set_page_config(page_title="CardioPredictor", page_icon="❤️")
34
-
35
- def main():
36
- st.title("Cardiovascular Risk Predictor App ❤️")
37
-
38
- # Display random health tip
39
- st.info(f"💡 Health Tip: {random.choice(HEALTH_TIPS)}")
40
-
41
- # Create input form
42
- with st.form("prediction_form"):
43
- st.subheader("Patient Information")
44
-
45
- col1, col2 = st.columns(2)
46
-
47
- with col1:
48
- age = st.number_input("Age", min_value=20, max_value=100, value=50)
49
- sex = st.selectbox("Sex", ["Male", "Female"])
50
- cp = st.selectbox("Chest Pain Type", [
51
- "Typical angina",
52
- "Atypical angina",
53
- "Non-anginal pain",
54
- "Asymptomatic"
55
- ])
56
- trestbps = st.number_input("Resting Blood Pressure (mm Hg)", min_value=80, max_value=200, value=120)
57
- chol = st.number_input("Serum Cholesterol (mg/dl)", min_value=100, max_value=600, value=200)
58
- fbs = st.selectbox("Fasting Blood Sugar > 120 mg/dl", ["No", "Yes"])
59
-
60
- with col2:
61
- restecg = st.selectbox("Resting ECG Results", [
62
- "Normal",
63
- "ST-T wave abnormality",
64
- "Left ventricular hypertrophy"
65
- ])
66
- thalach = st.number_input("Maximum Heart Rate Achieved", min_value=60, max_value=220, value=150)
67
- exang = st.selectbox("Exercise Induced Angina", ["No", "Yes"])
68
- oldpeak = st.number_input("ST Depression Induced by Exercise", min_value=0.0, max_value=6.2, value=1.0, step=0.1)
69
- slope = st.selectbox("Slope of Peak Exercise ST Segment", [
70
- "Upsloping",
71
- "Flat",
72
- "Downsloping"
73
- ])
74
- ca = st.selectbox("Number of Major Vessels Colored by Fluoroscopy", [0, 1, 2, 3])
75
- thal = st.selectbox("Thalassemia", [
76
- "Normal",
77
- "Fixed defect",
78
- "Reversible defect"
79
- ])
80
-
81
- model_choice = st.selectbox("Select Prediction Model", [
82
- "Logistic Regression",
83
- "Artificial Neural Network (ANN)",
84
- "Long Short-Term Memory (LSTM)",
85
- "XGBoost"
86
- ])
87
-
88
- submitted = st.form_submit_button("Predict")
89
-
90
- if submitted:
91
- # Convert inputs to model format
92
- sex = 1 if sex == "Male" else 0
93
- cp_mapping = {
94
- "Typical angina": 0,
95
- "Atypical angina": 1,
96
- "Non-anginal pain": 2,
97
- "Asymptomatic": 3
98
- }
99
- cp = cp_mapping[cp]
100
-
101
- fbs = 1 if fbs == "Yes" else 0
102
-
103
- restecg_mapping = {
104
- "Normal": 0,
105
- "ST-T wave abnormality": 1,
106
- "Left ventricular hypertrophy": 2
107
- }
108
- restecg = restecg_mapping[restecg]
109
-
110
- exang = 1 if exang == "Yes" else 0
111
-
112
- slope_mapping = {
113
- "Upsloping": 0,
114
- "Flat": 1,
115
- "Downsloping": 2
116
- }
117
- slope = slope_mapping[slope]
118
-
119
- thal_mapping = {
120
- "Normal": 1,
121
- "Fixed defect": 2,
122
- "Reversible defect": 3
123
- }
124
- thal = thal_mapping[thal]
125
-
126
- # Prepare input data
127
- input_data = {
128
- 'age': age,
129
- 'sex': sex,
130
- 'cp': cp,
131
- 'trestbps': trestbps,
132
- 'chol': chol,
133
- 'fbs': fbs,
134
- 'restecg': restecg,
135
- 'thalach': thalach,
136
- 'exang': exang,
137
- 'oldpeak': oldpeak,
138
- 'slope': slope,
139
- 'ca': ca,
140
- 'thal': thal
141
- }
142
-
143
- # Preprocess input
144
- processed_input = scaler.transform(pd.DataFrame([input_data]))
145
-
146
- try:
147
- # Load model and make prediction
148
- if model_choice == "Logistic Regression":
149
- model = load_ml_model("models/logistic_model.sav")
150
- proba = model.predict_proba(processed_input)[0]
151
- prediction = model.predict(processed_input)
152
-
153
- elif model_choice == "Artificial Neural Network (ANN)":
154
- model = load_dl_model("models/ann_model.h5")
155
- proba = model.predict(processed_input)[0][0]
156
- proba = [1-proba, proba] # Convert to [prob_0, prob_1]
157
- prediction = [1 if proba[1] > 0.5 else 0]
158
-
159
- elif model_choice == "Long Short-Term Memory (LSTM)":
160
- model = load_dl_model("models/lstm_model.h5")
161
- lstm_input = processed_input.reshape(1, 1, processed_input.shape[1])
162
- proba = model.predict(lstm_input)[0][0]
163
- proba = [1-proba, proba] # Convert to [prob_0, prob_1]
164
- prediction = [1 if proba[1] > 0.5 else 0]
165
-
166
- elif model_choice == "XGBoost":
167
- model = load_ml_model("models/xgb_model.sav")
168
- proba = model.predict_proba(processed_input)[0]
169
- prediction = model.predict(processed_input)
170
-
171
- # 1. Probability Output
172
- st.subheader("Prediction Results")
173
- if prediction[0] == 1:
174
- st.error(f"High Risk of Cardiovascular Disease (Probability: {proba[1]:.2%})")
175
- else:
176
- st.success(f"Low Risk of Cardiovascular Disease (Probability: {proba[0]:.2%})")
177
-
178
- # 2. Evaluation Metrics
179
- st.subheader("Model Performance Metrics")
180
- test_data = pd.read_csv("heart.csv")
181
- X_test = test_data.drop('target', axis=1)
182
- y_test = test_data['target']
183
- X_test_scaled = scaler.transform(X_test)
184
-
185
- if model_choice in ["Logistic Regression", "XGBoost"]:
186
- y_pred = model.predict(X_test_scaled)
187
- elif model_choice == "Artificial Neural Network (ANN)":
188
- y_pred = (model.predict(X_test_scaled) > 0.5).astype(int).flatten()
189
- elif model_choice == "Long Short-Term Memory (LSTM)":
190
- lstm_test = X_test_scaled.reshape(X_test_scaled.shape[0], 1, X_test_scaled.shape[1])
191
- y_pred = (model.predict(lstm_test) > 0.5).astype(int).flatten()
192
-
193
- # Calculate metrics
194
- st.write(f"Accuracy: {accuracy_score(y_test, y_pred):.2%}")
195
- st.write(f"Precision: {precision_score(y_test, y_pred):.2%}")
196
- st.write(f"Recall: {recall_score(y_test, y_pred):.2%}")
197
- st.write(f"F1 Score: {f1_score(y_test, y_pred):.2%}")
198
-
199
- except Exception as e:
200
- st.error(f"Error during prediction: {str(e)}")
201
-
202
- if __name__ == '__main__':
 
 
 
 
 
203
  main()
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import numpy as np
4
+ import joblib
5
+ import random
6
+ from sklearn.preprocessing import StandardScaler
7
+ from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix
8
+ import os
9
+ os.environ["PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION"] = "python" # 🔥 Must be set before TF import
10
+
11
+ from tensorflow.keras.models import load_model
12
+
13
+ #from tensorflow.keras.models import load_model
14
+ import warnings
15
+ warnings.filterwarnings("ignore")
16
+
17
+ # Health tips
18
+ HEALTH_TIPS = [
19
+ "Regular exercise can reduce your risk of heart disease by up to 30%.",
20
+ "Eating a handful of nuts daily can improve heart health.",
21
+ "Reducing salt intake can help lower blood pressure.",
22
+ "Aim for 7-8 hours of quality sleep each night for heart health.",
23
+ "Quitting smoking can cut your heart disease risk in half within a year.",
24
+ "Managing stress through meditation can benefit your cardiovascular system."
25
+ ]
26
+
27
+ # Load models
28
+ def load_ml_model(model_path):
29
+ return joblib.load(model_path)
30
+
31
+ def load_dl_model(model_path):
32
+ return load_model(model_path)
33
+
34
+ # Load scaler
35
+ scaler = load_ml_model("models/scaler.sav")
36
+
37
+ # Page config
38
+ st.set_page_config(page_title="CardioPredictor", page_icon="❤️")
39
+
40
+ def main():
41
+ st.title("Cardiovascular Risk Predictor App ❤️")
42
+
43
+ # Display random health tip
44
+ st.info(f"💡 Health Tip: {random.choice(HEALTH_TIPS)}")
45
+
46
+ # Create input form
47
+ with st.form("prediction_form"):
48
+ st.subheader("Patient Information")
49
+
50
+ col1, col2 = st.columns(2)
51
+
52
+ with col1:
53
+ age = st.number_input("Age", min_value=20, max_value=100, value=50)
54
+ sex = st.selectbox("Sex", ["Male", "Female"])
55
+ cp = st.selectbox("Chest Pain Type", [
56
+ "Typical angina",
57
+ "Atypical angina",
58
+ "Non-anginal pain",
59
+ "Asymptomatic"
60
+ ])
61
+ trestbps = st.number_input("Resting Blood Pressure (mm Hg)", min_value=80, max_value=200, value=120)
62
+ chol = st.number_input("Serum Cholesterol (mg/dl)", min_value=100, max_value=600, value=200)
63
+ fbs = st.selectbox("Fasting Blood Sugar > 120 mg/dl", ["No", "Yes"])
64
+
65
+ with col2:
66
+ restecg = st.selectbox("Resting ECG Results", [
67
+ "Normal",
68
+ "ST-T wave abnormality",
69
+ "Left ventricular hypertrophy"
70
+ ])
71
+ thalach = st.number_input("Maximum Heart Rate Achieved", min_value=60, max_value=220, value=150)
72
+ exang = st.selectbox("Exercise Induced Angina", ["No", "Yes"])
73
+ oldpeak = st.number_input("ST Depression Induced by Exercise", min_value=0.0, max_value=6.2, value=1.0, step=0.1)
74
+ slope = st.selectbox("Slope of Peak Exercise ST Segment", [
75
+ "Upsloping",
76
+ "Flat",
77
+ "Downsloping"
78
+ ])
79
+ ca = st.selectbox("Number of Major Vessels Colored by Fluoroscopy", [0, 1, 2, 3])
80
+ thal = st.selectbox("Thalassemia", [
81
+ "Normal",
82
+ "Fixed defect",
83
+ "Reversible defect"
84
+ ])
85
+
86
+ model_choice = st.selectbox("Select Prediction Model", [
87
+ "Logistic Regression",
88
+ "Artificial Neural Network (ANN)",
89
+ "Long Short-Term Memory (LSTM)",
90
+ "XGBoost"
91
+ ])
92
+
93
+ submitted = st.form_submit_button("Predict")
94
+
95
+ if submitted:
96
+ # Convert inputs to model format
97
+ sex = 1 if sex == "Male" else 0
98
+ cp_mapping = {
99
+ "Typical angina": 0,
100
+ "Atypical angina": 1,
101
+ "Non-anginal pain": 2,
102
+ "Asymptomatic": 3
103
+ }
104
+ cp = cp_mapping[cp]
105
+
106
+ fbs = 1 if fbs == "Yes" else 0
107
+
108
+ restecg_mapping = {
109
+ "Normal": 0,
110
+ "ST-T wave abnormality": 1,
111
+ "Left ventricular hypertrophy": 2
112
+ }
113
+ restecg = restecg_mapping[restecg]
114
+
115
+ exang = 1 if exang == "Yes" else 0
116
+
117
+ slope_mapping = {
118
+ "Upsloping": 0,
119
+ "Flat": 1,
120
+ "Downsloping": 2
121
+ }
122
+ slope = slope_mapping[slope]
123
+
124
+ thal_mapping = {
125
+ "Normal": 1,
126
+ "Fixed defect": 2,
127
+ "Reversible defect": 3
128
+ }
129
+ thal = thal_mapping[thal]
130
+
131
+ # Prepare input data
132
+ input_data = {
133
+ 'age': age,
134
+ 'sex': sex,
135
+ 'cp': cp,
136
+ 'trestbps': trestbps,
137
+ 'chol': chol,
138
+ 'fbs': fbs,
139
+ 'restecg': restecg,
140
+ 'thalach': thalach,
141
+ 'exang': exang,
142
+ 'oldpeak': oldpeak,
143
+ 'slope': slope,
144
+ 'ca': ca,
145
+ 'thal': thal
146
+ }
147
+
148
+ # Preprocess input
149
+ processed_input = scaler.transform(pd.DataFrame([input_data]))
150
+
151
+ try:
152
+ # Load model and make prediction
153
+ if model_choice == "Logistic Regression":
154
+ model = load_ml_model("models/logistic_model.sav")
155
+ proba = model.predict_proba(processed_input)[0]
156
+ prediction = model.predict(processed_input)
157
+
158
+ elif model_choice == "Artificial Neural Network (ANN)":
159
+ model = load_dl_model("models/ann_model.h5")
160
+ proba = model.predict(processed_input)[0][0]
161
+ proba = [1-proba, proba] # Convert to [prob_0, prob_1]
162
+ prediction = [1 if proba[1] > 0.5 else 0]
163
+
164
+ elif model_choice == "Long Short-Term Memory (LSTM)":
165
+ model = load_dl_model("models/lstm_model.h5")
166
+ lstm_input = processed_input.reshape(1, 1, processed_input.shape[1])
167
+ proba = model.predict(lstm_input)[0][0]
168
+ proba = [1-proba, proba] # Convert to [prob_0, prob_1]
169
+ prediction = [1 if proba[1] > 0.5 else 0]
170
+
171
+ elif model_choice == "XGBoost":
172
+ model = load_ml_model("models/xgb_model.sav")
173
+ proba = model.predict_proba(processed_input)[0]
174
+ prediction = model.predict(processed_input)
175
+
176
+ # 1. Probability Output
177
+ st.subheader("Prediction Results")
178
+ if prediction[0] == 1:
179
+ st.error(f"High Risk of Cardiovascular Disease (Probability: {proba[1]:.2%})")
180
+ else:
181
+ st.success(f"Low Risk of Cardiovascular Disease (Probability: {proba[0]:.2%})")
182
+
183
+ # 2. Evaluation Metrics
184
+ st.subheader("Model Performance Metrics")
185
+ test_data = pd.read_csv("heart.csv")
186
+ X_test = test_data.drop('target', axis=1)
187
+ y_test = test_data['target']
188
+ X_test_scaled = scaler.transform(X_test)
189
+
190
+ if model_choice in ["Logistic Regression", "XGBoost"]:
191
+ y_pred = model.predict(X_test_scaled)
192
+ elif model_choice == "Artificial Neural Network (ANN)":
193
+ y_pred = (model.predict(X_test_scaled) > 0.5).astype(int).flatten()
194
+ elif model_choice == "Long Short-Term Memory (LSTM)":
195
+ lstm_test = X_test_scaled.reshape(X_test_scaled.shape[0], 1, X_test_scaled.shape[1])
196
+ y_pred = (model.predict(lstm_test) > 0.5).astype(int).flatten()
197
+
198
+ # Calculate metrics
199
+ st.write(f"Accuracy: {accuracy_score(y_test, y_pred):.2%}")
200
+ st.write(f"Precision: {precision_score(y_test, y_pred):.2%}")
201
+ st.write(f"Recall: {recall_score(y_test, y_pred):.2%}")
202
+ st.write(f"F1 Score: {f1_score(y_test, y_pred):.2%}")
203
+
204
+ except Exception as e:
205
+ st.error(f"Error during prediction: {str(e)}")
206
+
207
+ if __name__ == '__main__':
208
  main()