File size: 6,677 Bytes
69b2866
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39ab335
 
69b2866
39ab335
 
 
69b2866
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39ab335
 
 
 
 
 
 
 
 
69b2866
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39ab335
 
 
 
 
 
 
 
 
 
 
 
69b2866
39ab335
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
# Import required libraries
import streamlit as st
import pandas as pd
import numpy as np
from ucimlrepo import fetch_ucirepo
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
import torch
import torch.nn as nn
import torch.optim as optim

# Fetch the diabetes dataset (ID 891)
cdc_diabetes_health_indicators = fetch_ucirepo(id=891)

# Extract features and targets
X_raw = cdc_diabetes_health_indicators.data.features
y = cdc_diabetes_health_indicators.data.targets

# Combine features and targets into a single DataFrame
df = pd.concat([X_raw, y], axis=1)

# Drop duplicates if there are any
df.drop_duplicates(inplace=True)

# Features and target selection
X_raw = df[['AnyHealthcare', 'Sex', 'Smoker', 'MentHlth', 'CholCheck', 'Stroke',
            'PhysHlth', 'HeartDiseaseorAttack', 'Age', 'HighChol', 'DiffWalk',
            'BMI', 'HighBP', 'GenHlth']]
y = df['Diabetes_binary']

# Data Preprocessing
scaler = StandardScaler()
X = scaler.fit_transform(X_raw)

# Train-test split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, stratify=y, random_state=123)

# Convert to PyTorch tensors
X_train_tensor = torch.tensor(X_train, dtype=torch.float32)
X_test_tensor = torch.tensor(X_test, dtype=torch.float32)
y_train_tensor = torch.tensor(y_train.values, dtype=torch.float32).view(-1, 1)
y_test_tensor = torch.tensor(y_test.values, dtype=torch.float32).view(-1, 1)

# Define the PyTorch model
class NeuralNet(nn.Module):
    def __init__(self, input_size, hidden_size, output_size):
        super(NeuralNet, self).__init__()
        self.fc1 = nn.Linear(input_size, hidden_size)
        self.fc2 = nn.Linear(hidden_size, hidden_size)
        self.fc3 = nn.Linear(hidden_size, output_size)
        self.relu = nn.ReLU()
        self.sigmoid = nn.Sigmoid()

    def forward(self, x):
        x = self.relu(self.fc1(x))
        x = self.relu(self.fc2(x))
        x = self.sigmoid(self.fc3(x))
        return x

# Instantiate PyTorch model
input_size = X_train.shape[1]
hidden_size = 64
output_size = 1
deep_model = NeuralNet(input_size, hidden_size, output_size)

# Define loss and optimizer
criterion = nn.BCELoss()
optimizer = optim.Adam(deep_model.parameters(), lr=0.001)

# Title and description in Streamlit
st.title("BERTO AI😊 : Personalized Diabetes Treatment Predictor")
st.write("""
BERTO AI is a personalized diabetes prediction tool built to assist users in better understanding their health risks. 
Berto honors the legacy of one of our founder's dad, Roberto Ferrer, who unfortunately succumbed to Type 2 Diabetes.
This application uses a deep learning model powered by PyTorch to predict whether you may have diabetes based on various health indicators. 
We aim to provide insights and suggestions for personalizing diabetes treatment. The Application allows you to choose between two options, Yes and No, 
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 
mission to help manage, prevent, and provide personalized treatment to Type 2 Diabetic Patients.
""")

# Input form for user to enter health information with descriptions
st.subheader("Enter Your Health Information")

AnyHealthcare = st.selectbox("Any Healthcare (1: Yes, 0: No)", [0, 1])
Sex = st.selectbox("Sex (1: Male, 0: Female)", [0, 1])
Smoker = st.selectbox("Smoker (1: Yes, 0: No)", [0, 1])
MentHlth = st.slider("Mental Health (Bad days in last 30 days)", 0, 30, 0)
CholCheck = st.selectbox("Cholesterol Check in Last 5 Years (1: Yes, 0: No)", [0, 1])
Stroke = st.selectbox("History of Stroke (1: Yes, 0: No)", [0, 1])
PhysHlth = st.slider("Physical Health (Bad days in last 30 days)", 0, 30, 0)
HeartDiseaseorAttack = st.selectbox("History of Heart Disease or Attack (1: Yes, 0: No)", [0, 1])
Age = st.slider("Age", 18, 100, 30)
HighChol = st.selectbox("High Cholesterol (1: Yes, 0: No)", [0, 1])
DiffWalk = st.selectbox("Difficulty Walking (1: Yes, 0: No)", [0, 1])
HighBP = st.selectbox("High Blood Pressure (1: Yes, 0: No)", [0, 1])
GenHlth = st.slider("General Health (1=Excellent, 5=Poor)", 1, 5, 3)

# Get height and weight input
height_cm = st.slider("Height (in cm)", 100, 250, 170)
weight_kg = st.slider("Weight (in kg)", 30, 200, 70)

# Calculate BMI
BMI = weight_kg / (height_cm / 100) ** 2
st.write(f"Your BMI is: {BMI:.2f}")

# Create a feature array from the inputs, including the calculated BMI
user_input = np.array([[AnyHealthcare, Sex, Smoker, MentHlth, CholCheck, Stroke,
                        PhysHlth, HeartDiseaseorAttack, Age, HighChol, DiffWalk,
                        BMI, HighBP, GenHlth]])

# Convert the NumPy array to a DataFrame with the same column names used in the scaler
user_input_df = pd.DataFrame(user_input, columns=X_raw.columns)

# Standardize the user input using the same scaler
user_input_scaled = scaler.transform(user_input_df)

# Convert user input to PyTorch tensor
user_input_tensor = torch.tensor(user_input_scaled, dtype=torch.float32)

# Perform prediction when the user clicks "Predict"
if st.button("Predict"):
    with torch.no_grad():
        deep_model.eval()  # Set model to evaluation mode
        prediction = deep_model(user_input_tensor).round().numpy()

    # Display prediction result
    if prediction == 1:
        st.success("The model predicts that you likely **have diabetes**.")
        
        # Provide tips for managing diabetes
        st.subheader("Tips for Managing Diabetes")
        st.markdown("""
        - **Maintain a balanced diet**: Focus on eating whole grains, vegetables, lean protein, and healthy fats.
        - **Exercise regularly**: Physical activity helps control your blood sugar.
        - **Monitor blood sugar levels**: Regular monitoring helps you keep track of your glucose levels.
        - **Take medications as prescribed**: Follow your doctor's instructions regarding medications.
        - **Manage stress**: Chronic stress can raise blood sugar levels, so practice relaxation techniques.
        - **Get regular check-ups**: Regular health check-ups are crucial for managing diabetes effectively.
        """)
    else:
        st.success("✅ Lower risk detected. Keep up the good work!")
        
        # Provide tips for maintaining low diabetes risk
        st.subheader("Tips to Maintain Low Diabetes Risk")
        st.markdown("""
        - **Keep a healthy weight**
        - **Exercise often**
        - **Eat well-balanced meals**
        - **Cut down on sugar and unhealthy fats**
        - **Check your blood sugar**
        - **Manage stress**
        - **Get regular check-ups**
        """)