EdgarDataScientist commited on
Commit
02812b7
·
verified ·
1 Parent(s): 39ab335

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +114 -122
app.py CHANGED
@@ -1,47 +1,13 @@
1
- # Import required libraries
2
  import streamlit as st
3
  import pandas as pd
4
  import numpy as np
5
- from ucimlrepo import fetch_ucirepo
6
  from sklearn.model_selection import train_test_split
7
  from sklearn.preprocessing import StandardScaler
8
  import torch
9
  import torch.nn as nn
10
  import torch.optim as optim
11
 
12
- # Fetch the diabetes dataset (ID 891)
13
- cdc_diabetes_health_indicators = fetch_ucirepo(id=891)
14
-
15
- # Extract features and targets
16
- X_raw = cdc_diabetes_health_indicators.data.features
17
- y = cdc_diabetes_health_indicators.data.targets
18
-
19
- # Combine features and targets into a single DataFrame
20
- df = pd.concat([X_raw, y], axis=1)
21
-
22
- # Drop duplicates if there are any
23
- df.drop_duplicates(inplace=True)
24
-
25
- # Features and target selection
26
- X_raw = df[['AnyHealthcare', 'Sex', 'Smoker', 'MentHlth', 'CholCheck', 'Stroke',
27
- 'PhysHlth', 'HeartDiseaseorAttack', 'Age', 'HighChol', 'DiffWalk',
28
- 'BMI', 'HighBP', 'GenHlth']]
29
- y = df['Diabetes_binary']
30
-
31
- # Data Preprocessing
32
- scaler = StandardScaler()
33
- X = scaler.fit_transform(X_raw)
34
-
35
- # Train-test split
36
- X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, stratify=y, random_state=123)
37
-
38
- # Convert to PyTorch tensors
39
- X_train_tensor = torch.tensor(X_train, dtype=torch.float32)
40
- X_test_tensor = torch.tensor(X_test, dtype=torch.float32)
41
- y_train_tensor = torch.tensor(y_train.values, dtype=torch.float32).view(-1, 1)
42
- y_test_tensor = torch.tensor(y_test.values, dtype=torch.float32).view(-1, 1)
43
-
44
- # Define the PyTorch model
45
  class NeuralNet(nn.Module):
46
  def __init__(self, input_size, hidden_size, output_size):
47
  super(NeuralNet, self).__init__()
@@ -57,97 +23,123 @@ class NeuralNet(nn.Module):
57
  x = self.sigmoid(self.fc3(x))
58
  return x
59
 
60
- # Instantiate PyTorch model
61
- input_size = X_train.shape[1]
62
  hidden_size = 64
63
  output_size = 1
64
  deep_model = NeuralNet(input_size, hidden_size, output_size)
 
65
 
66
- # Define loss and optimizer
67
- criterion = nn.BCELoss()
68
- optimizer = optim.Adam(deep_model.parameters(), lr=0.001)
69
-
70
- # Title and description in Streamlit
71
- st.title("BERTO AI😊 : Personalized Diabetes Treatment Predictor")
72
- st.write("""
73
- BERTO AI is a personalized diabetes prediction tool built to assist users in better understanding their health risks.
74
- Berto honors the legacy of one of our founder's dad, Roberto Ferrer, who unfortunately succumbed to Type 2 Diabetes.
75
- This application uses a deep learning model powered by PyTorch to predict whether you may have diabetes based on various health indicators.
76
- We aim to provide insights and suggestions for personalizing diabetes treatment. The Application allows you to choose between two options, Yes and No,
77
- which have been given binary values. There is also a slider for various features, which have ranges as indicated. Berto is part of DiabeTrek Health's
78
- mission to help manage, prevent, and provide personalized treatment to Type 2 Diabetic Patients.
79
- """)
80
-
81
- # Input form for user to enter health information with descriptions
82
- st.subheader("Enter Your Health Information")
83
-
84
- AnyHealthcare = st.selectbox("Any Healthcare (1: Yes, 0: No)", [0, 1])
85
- Sex = st.selectbox("Sex (1: Male, 0: Female)", [0, 1])
86
- Smoker = st.selectbox("Smoker (1: Yes, 0: No)", [0, 1])
87
- MentHlth = st.slider("Mental Health (Bad days in last 30 days)", 0, 30, 0)
88
- CholCheck = st.selectbox("Cholesterol Check in Last 5 Years (1: Yes, 0: No)", [0, 1])
89
- Stroke = st.selectbox("History of Stroke (1: Yes, 0: No)", [0, 1])
90
- PhysHlth = st.slider("Physical Health (Bad days in last 30 days)", 0, 30, 0)
91
- HeartDiseaseorAttack = st.selectbox("History of Heart Disease or Attack (1: Yes, 0: No)", [0, 1])
92
- Age = st.slider("Age", 18, 100, 30)
93
- HighChol = st.selectbox("High Cholesterol (1: Yes, 0: No)", [0, 1])
94
- DiffWalk = st.selectbox("Difficulty Walking (1: Yes, 0: No)", [0, 1])
95
- HighBP = st.selectbox("High Blood Pressure (1: Yes, 0: No)", [0, 1])
96
- GenHlth = st.slider("General Health (1=Excellent, 5=Poor)", 1, 5, 3)
97
-
98
- # Get height and weight input
99
- height_cm = st.slider("Height (in cm)", 100, 250, 170)
100
- weight_kg = st.slider("Weight (in kg)", 30, 200, 70)
101
-
102
- # Calculate BMI
103
- BMI = weight_kg / (height_cm / 100) ** 2
104
- st.write(f"Your BMI is: {BMI:.2f}")
105
-
106
- # Create a feature array from the inputs, including the calculated BMI
107
- user_input = np.array([[AnyHealthcare, Sex, Smoker, MentHlth, CholCheck, Stroke,
108
- PhysHlth, HeartDiseaseorAttack, Age, HighChol, DiffWalk,
109
- BMI, HighBP, GenHlth]])
110
-
111
- # Convert the NumPy array to a DataFrame with the same column names used in the scaler
112
- user_input_df = pd.DataFrame(user_input, columns=X_raw.columns)
113
-
114
- # Standardize the user input using the same scaler
115
- user_input_scaled = scaler.transform(user_input_df)
116
-
117
- # Convert user input to PyTorch tensor
118
- user_input_tensor = torch.tensor(user_input_scaled, dtype=torch.float32)
119
-
120
- # Perform prediction when the user clicks "Predict"
121
- if st.button("Predict"):
122
- with torch.no_grad():
123
- deep_model.eval() # Set model to evaluation mode
124
- prediction = deep_model(user_input_tensor).round().numpy()
125
-
126
- # Display prediction result
127
- if prediction == 1:
128
- st.success("The model predicts that you likely **have diabetes**.")
129
-
130
- # Provide tips for managing diabetes
131
- st.subheader("Tips for Managing Diabetes")
132
- st.markdown("""
133
- - **Maintain a balanced diet**: Focus on eating whole grains, vegetables, lean protein, and healthy fats.
134
- - **Exercise regularly**: Physical activity helps control your blood sugar.
135
- - **Monitor blood sugar levels**: Regular monitoring helps you keep track of your glucose levels.
136
- - **Take medications as prescribed**: Follow your doctor's instructions regarding medications.
137
- - **Manage stress**: Chronic stress can raise blood sugar levels, so practice relaxation techniques.
138
- - **Get regular check-ups**: Regular health check-ups are crucial for managing diabetes effectively.
139
- """)
 
 
 
 
 
 
140
  else:
141
- st.success(" Lower risk detected. Keep up the good work!")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
142
 
143
- # Provide tips for maintaining low diabetes risk
144
- st.subheader("Tips to Maintain Low Diabetes Risk")
145
- st.markdown("""
146
- - **Keep a healthy weight**
147
- - **Exercise often**
148
- - **Eat well-balanced meals**
149
- - **Cut down on sugar and unhealthy fats**
150
- - **Check your blood sugar**
151
- - **Manage stress**
152
- - **Get regular check-ups**
153
  """)
 
 
1
  import streamlit as st
2
  import pandas as pd
3
  import numpy as np
 
4
  from sklearn.model_selection import train_test_split
5
  from sklearn.preprocessing import StandardScaler
6
  import torch
7
  import torch.nn as nn
8
  import torch.optim as optim
9
 
10
+ # Neural network definition (same as before)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  class NeuralNet(nn.Module):
12
  def __init__(self, input_size, hidden_size, output_size):
13
  super(NeuralNet, self).__init__()
 
23
  x = self.sigmoid(self.fc3(x))
24
  return x
25
 
26
+ # Instantiate the model
27
+ input_size = 13
28
  hidden_size = 64
29
  output_size = 1
30
  deep_model = NeuralNet(input_size, hidden_size, output_size)
31
+ scaler = StandardScaler()
32
 
33
+ # Sidebar for navigation
34
+ st.sidebar.title("Navigation")
35
+ app_mode = st.sidebar.selectbox("Choose the app mode", ["Diabetes Predictor", "Chronotherapy Scheduler"])
36
+
37
+ # Diabetes Predictor Section
38
+ if app_mode == "Diabetes Predictor":
39
+ st.title("BERTO AI😊 : Personalized Diabetes Treatment Predictor")
40
+ st.write("""
41
+ Berto AI is a personalized diabetes prediction tool built to assist users in better understanding their health risks.
42
+ This tool uses a deep learning model powered by PyTorch to predict whether you may have diabetes based on various health indicators.
43
+ """)
44
+
45
+ # Input form for user health information
46
+ st.subheader("Enter Your Health Information")
47
+
48
+ AnyHealthcare = st.selectbox("Any Healthcare (1: Yes, 0: No)", [0, 1])
49
+ Sex = st.selectbox("Sex (1: Male, 0: Female)", [0, 1])
50
+ Smoker = st.selectbox("Smoker (1: Yes, 0: No)", [0, 1])
51
+ MentHlth = st.slider("Mental Health (Bad days in last 30 days)", 0, 30, 0)
52
+ CholCheck = st.selectbox("Cholesterol Check in Last 5 Years (1: Yes, 0: No)", [0, 1])
53
+ Stroke = st.selectbox("History of Stroke (1: Yes, 0: No)", [0, 1])
54
+ PhysHlth = st.slider("Physical Health (Bad days in last 30 days)", 0, 30, 0)
55
+ HeartDiseaseorAttack = st.selectbox("History of Heart Disease or Attack (1: Yes, 0: No)", [0, 1])
56
+ Age = st.slider("Age", 18, 100, 30)
57
+ HighChol = st.selectbox("High Cholesterol (1: Yes, 0: No)", [0, 1])
58
+ DiffWalk = st.selectbox("Difficulty Walking (1: Yes, 0: No)", [0, 1])
59
+ HighBP = st.selectbox("High Blood Pressure (1: Yes, 0: No)", [0, 1])
60
+ GenHlth = st.slider("General Health (1=Excellent, 5=Poor)", 1, 5, 3)
61
+
62
+ # Create a feature array from the inputs
63
+ user_input = np.array([[AnyHealthcare, Sex, Smoker, MentHlth, CholCheck, Stroke,
64
+ PhysHlth, HeartDiseaseorAttack, Age, HighChol, DiffWalk,
65
+ HighBP, GenHlth]])
66
+
67
+ # Convert the NumPy array to a DataFrame
68
+ user_input_df = pd.DataFrame(user_input, columns=[
69
+ 'AnyHealthcare', 'Sex', 'Smoker', 'MentHlth', 'CholCheck', 'Stroke', 'PhysHlth',
70
+ 'HeartDiseaseorAttack', 'Age', 'HighChol', 'DiffWalk', 'HighBP', 'GenHlth'])
71
+
72
+ # Standardize the user input
73
+ user_input_scaled = scaler.fit_transform(user_input_df) # Use pre-trained scaler in practice
74
+ user_input_tensor = torch.tensor(user_input_scaled, dtype=torch.float32)
75
+
76
+ # Perform prediction
77
+ if st.button("Predict"):
78
+ with torch.no_grad():
79
+ deep_model.eval() # Set model to evaluation mode
80
+ prediction = deep_model(user_input_tensor).round().numpy()
81
+
82
+ if prediction == 1:
83
+ st.success("The model predicts that you likely **have diabetes**.")
84
+ st.warning("Tips to Manage Diabetes:\n\n- Manage blood sugar\n- Eat healthy meals\n- Exercise regularly\n- Monitor your blood pressure\n- Get enough sleep.")
85
+ else:
86
+ st.success("✅ Lower risk detected. Keep up the good work!")
87
+ st.info("""
88
+ Tips to Maintain Low Diabetes Risk:
89
+ - Keep a healthy weight
90
+ - Exercise often
91
+ - Eat well-balanced meals
92
+ - Cut down on sugar and unhealthy fats
93
+ - Check your blood sugar
94
+ - Manage stress
95
+ - Get regular check-ups
96
+ """)
97
+
98
+ # Chronotherapy Scheduler Section
99
+ elif app_mode == "Chronotherapy Scheduler":
100
+ st.title("Chronotherapy Scheduler for Type 2 Diabetes")
101
+ st.write("""
102
+ This scheduler generates a personalized routine for Type 2 Diabetes management based on your inputs.
103
+ Chronotherapy involves timing medical treatment and lifestyle interventions to better align with your body's natural rhythms.
104
+ """)
105
+
106
+ # Input fields
107
+ city = st.text_input("Enter your city name:")
108
+ a1c_level = st.slider("A1C level (%)", 4.0, 14.0, 7.0)
109
+
110
+ weight_unit = st.radio("Weight unit", ["kg", "lbs"])
111
+ if weight_unit == "kg":
112
+ weight = st.number_input("Weight (kg)", min_value=30.0, max_value=200.0, value=70.0)
113
  else:
114
+ weight = st.number_input("Weight (lbs)", min_value=66.0, max_value=440.0, value=154.0)
115
+
116
+ height_unit = st.radio("Height unit", ["cm", "feet & inches"])
117
+ if height_unit == "cm":
118
+ height_cm = st.number_input("Height (cm)", min_value=100.0, max_value=250.0, value=170.0)
119
+ else:
120
+ height_ft = st.number_input("Height (feet)", min_value=3, max_value=8, value=5)
121
+ height_in = st.number_input("Height (inches)", min_value=0, max_value=11, value=7)
122
+ height_cm = height_ft * 30.48 + height_in * 2.54
123
+
124
+ glucose_level = st.number_input("Glucose level (mg/dL)", min_value=50.0, max_value=600.0, value=70.0)
125
+ age = st.slider("Age", min_value=18, max_value=100, value=45)
126
+ sex = st.radio("Sex", ["M", "F"])
127
+ smoking_status = st.radio("Do you smoke?", ["No", "Yes"])
128
+ diabetes_status = st.radio("Diabetes Status", ["Prediabetic", "Type 2 Diabetic"])
129
+
130
+ # Generate routine based on input
131
+ if st.button("Generate Schedule"):
132
+ st.subheader(f"Chronotherapy Routine for {city}")
133
+ st.write(f"""
134
+ Based on your inputs, here's a suggested routine for managing Type 2 Diabetes:
135
+
136
+ - **Morning (7:00 AM)**: Wake up and take your morning medication (if prescribed).
137
+ - **Breakfast (7:30 AM)**: A balanced meal with low sugar and carbs.
138
+ - **Mid-morning (10:00 AM)**: Light physical activity or a short walk.
139
+ - **Lunch (12:30 PM)**: A well-balanced meal with lean protein and fiber.
140
+ - **Afternoon (3:00 PM)**: Check glucose levels if needed, and have a light snack.
141
+ - **Evening (6:00 PM)**: Dinner with a focus on vegetables and healthy fats.
142
+ - **Before bed (10:00 PM)**: Wind down and manage stress with relaxation techniques.
143
 
144
+ Adjust this routine as needed based on medical advice.
 
 
 
 
 
 
 
 
 
145
  """)