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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import pandas as pd
|
3 |
+
from sklearn.model_selection import train_test_split
|
4 |
+
from sklearn.preprocessing import OneHotEncoder, StandardScaler
|
5 |
+
from sklearn.impute import SimpleImputer
|
6 |
+
from sklearn.linear_model import LogisticRegression
|
7 |
+
from sklearn.naive_bayes import GaussianNB
|
8 |
+
from sklearn.svm import SVC
|
9 |
+
from sklearn.tree import DecisionTreeClassifier
|
10 |
+
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
|
11 |
+
from sklearn.neural_network import MLPClassifier
|
12 |
+
from sklearn.metrics import confusion_matrix, classification_report
|
13 |
+
import matplotlib.pyplot as plt
|
14 |
+
import seaborn as sns
|
15 |
+
from huggingface_hub import login
|
16 |
+
from datasets import load_dataset
|
17 |
+
import io
|
18 |
+
from contextlib import redirect_stdout
|
19 |
+
import os
|
20 |
+
|
21 |
+
# Streamlit UI
|
22 |
+
dataset_name = "louiecerv/diabetes_dataset"
|
23 |
+
|
24 |
+
# Retrieve Hugging Face token from environment variable
|
25 |
+
hf_token = os.getenv("HF_TOKEN")
|
26 |
+
|
27 |
+
if not hf_token:
|
28 |
+
st.error("HF_TOKEN environment variable is not set. Please set it before running the app.")
|
29 |
+
st.stop()
|
30 |
+
|
31 |
+
# Login to Hugging Face Hub
|
32 |
+
login(token=hf_token)
|
33 |
+
|
34 |
+
# Load dataset
|
35 |
+
try:
|
36 |
+
with st.spinner("Loading dataset..."):
|
37 |
+
dataset = load_dataset(dataset_name)
|
38 |
+
st.success("Dataset loaded successfully.")
|
39 |
+
except ValueError:
|
40 |
+
st.error("Dataset not found or incorrect dataset name. Please check the dataset identifier.")
|
41 |
+
st.stop()
|
42 |
+
except PermissionError:
|
43 |
+
st.error("Authentication failed. Check if your Hugging Face token is correct.")
|
44 |
+
st.stop()
|
45 |
+
except Exception as e:
|
46 |
+
st.error(f"Unexpected error: {e}")
|
47 |
+
st.stop()
|
48 |
+
|
49 |
+
data = dataset["train"].to_pandas()
|
50 |
+
|
51 |
+
# Set the title of the Streamlit app
|
52 |
+
st.title("Diabetes Prediction App")
|
53 |
+
|
54 |
+
with st.expander("About This App"):
|
55 |
+
st.markdown("""
|
56 |
+
## Dataset Description
|
57 |
+
|
58 |
+
This app uses a dataset containing medical and lifestyle information about patients,
|
59 |
+
along with their diabetes status (positive or negative). The goal is to predict
|
60 |
+
whether a patient has diabetes based on their provided features.
|
61 |
+
|
62 |
+
The dataset includes the following features:
|
63 |
+
|
64 |
+
| Column | Description | Type |
|
65 |
+
|-----------------|-------------------------------------------|---------|
|
66 |
+
| gender | The gender of the patient | Object |
|
67 |
+
| age | The age of the patient | Float |
|
68 |
+
| hypertension | Whether the patient has hypertension (1 for yes, 0 for no) | Integer |
|
69 |
+
| heart_disease | Whether the patient has heart disease (1 for yes, 0 for no) | Integer |
|
70 |
+
| smoking_history | The smoking history of the patient | Object |
|
71 |
+
| bmi | The body mass index of the patient | Float |
|
72 |
+
| HbA1c_level | The HbA1c level of the patient | Float |
|
73 |
+
| blood_glucose_level | The blood glucose level of the patient | Integer |
|
74 |
+
| diabetes | Whether the patient has diabetes (1 for yes, 0 for no) | Integer |
|
75 |
+
|
76 |
+
## Preprocessing Tasks
|
77 |
+
|
78 |
+
The following preprocessing steps were performed on the data:
|
79 |
+
|
80 |
+
* **Handle Missing Values:** Missing values were checked and imputed using appropriate methods.
|
81 |
+
* **Encode Categorical Features:** Categorical features (gender, smoking_history) were converted
|
82 |
+
into numerical representations using one-hot encoding.
|
83 |
+
* **Scale Numerical Features:** Numerical features (age, bmi, HbA1c_level, blood_glucose_level)
|
84 |
+
were scaled to a standard range.
|
85 |
+
* **Split Data:** The dataset was divided into training and testing sets.
|
86 |
+
* **Handle Class Imbalance (if present):** Techniques like oversampling or undersampling were used if needed.
|
87 |
+
|
88 |
+
## ML Model Recommendation
|
89 |
+
|
90 |
+
This app utilizes a machine learning model for binary classification. Suitable models for this type of prediction include:
|
91 |
+
|
92 |
+
* Logistic Regression
|
93 |
+
* Support Vector Machines (SVM)
|
94 |
+
* Decision Trees
|
95 |
+
* Random Forest
|
96 |
+
* Gradient Boosting Machines (GBM)
|
97 |
+
|
98 |
+
Created by Louie F. Cervantes, M.Eng. (Information Engineering)
|
99 |
+
""")
|
100 |
+
|
101 |
+
# Display the dataset in a dataframe
|
102 |
+
st.subheader("Dataset")
|
103 |
+
st.write(data)
|
104 |
+
|
105 |
+
# Show the statistics of the dataset
|
106 |
+
st.subheader("Dataset Statistics")
|
107 |
+
st.write(data.describe())
|
108 |
+
|
109 |
+
# Visualizations of the data
|
110 |
+
st.subheader("Data Visualizations")
|
111 |
+
|
112 |
+
# Histogram of age
|
113 |
+
st.write("Histogram of Age")
|
114 |
+
fig, ax = plt.subplots()
|
115 |
+
ax.hist(data['age'], bins=10)
|
116 |
+
ax.set_xlabel('Age')
|
117 |
+
ax.set_ylabel('Frequency')
|
118 |
+
st.pyplot(fig)
|
119 |
+
|
120 |
+
# Bar chart of gender
|
121 |
+
st.write("Bar Chart of Gender")
|
122 |
+
fig, ax = plt.subplots()
|
123 |
+
ax.bar(data['gender'].value_counts().index, data['gender'].value_counts().values)
|
124 |
+
ax.set_xlabel('Gender')
|
125 |
+
ax.set_ylabel('Count')
|
126 |
+
st.pyplot(fig)
|
127 |
+
|
128 |
+
# Preprocessing
|
129 |
+
st.subheader("Data Preprocessing")
|
130 |
+
|
131 |
+
# Check for null values
|
132 |
+
st.write("Null Values:")
|
133 |
+
st.write(data.isnull().sum())
|
134 |
+
|
135 |
+
# Handle null values
|
136 |
+
imputer = SimpleImputer(strategy='mean')
|
137 |
+
data['bmi'] = imputer.fit_transform(data[['bmi']])
|
138 |
+
|
139 |
+
# Check for consistency of data types
|
140 |
+
st.write("Data Types:")
|
141 |
+
|
142 |
+
# Create a buffer to capture the output of df.info()
|
143 |
+
buffer = io.StringIO()
|
144 |
+
|
145 |
+
# Redirect the output of df.info() to the buffer
|
146 |
+
with redirect_stdout(buffer):
|
147 |
+
data.info()
|
148 |
+
|
149 |
+
# Get the captured output from the buffer
|
150 |
+
info_string = buffer.getvalue()
|
151 |
+
|
152 |
+
# Split the output string into lines
|
153 |
+
lines = info_string.splitlines()
|
154 |
+
|
155 |
+
# Extract column names and their data types
|
156 |
+
columns = []
|
157 |
+
cname = []
|
158 |
+
counts = []
|
159 |
+
nulls = []
|
160 |
+
dtypes = []
|
161 |
+
for line in lines[5:-2]: # Skip header and footer lines
|
162 |
+
col_info = line.split()
|
163 |
+
columns.append(col_info[0])
|
164 |
+
cname.append(col_info[1])
|
165 |
+
counts.append(col_info[2])
|
166 |
+
nulls.append(col_info[3])
|
167 |
+
dtypes.append(col_info[4])
|
168 |
+
|
169 |
+
# Create a DataFrame
|
170 |
+
info_df = pd.DataFrame({'Column': columns,
|
171 |
+
'Name': cname,
|
172 |
+
'Count': counts,
|
173 |
+
'Null': nulls,
|
174 |
+
'Data Type': dtypes})
|
175 |
+
|
176 |
+
# Display the DataFrame in Streamlit
|
177 |
+
st.dataframe(info_df)
|
178 |
+
|
179 |
+
# Identify numeric and categorical data
|
180 |
+
numeric_features = data.select_dtypes(include=['int64', 'float64']).columns
|
181 |
+
categorical_features = data.select_dtypes(include=['object']).columns
|
182 |
+
st.write("Numeric Features:", numeric_features)
|
183 |
+
st.write("Categorical Features:", categorical_features)
|
184 |
+
|
185 |
+
# One-hot encoding for categorical data
|
186 |
+
encoder = OneHotEncoder(handle_unknown='ignore')
|
187 |
+
encoded_data = encoder.fit_transform(data[categorical_features])
|
188 |
+
encoded_df = pd.DataFrame(encoded_data.toarray())
|
189 |
+
data = data.drop(categorical_features, axis=1)
|
190 |
+
data = pd.concat([data, encoded_df], axis=1)
|
191 |
+
|
192 |
+
# Split data into training and testing sets
|
193 |
+
X = data.drop('diabetes', axis=1)
|
194 |
+
y = data['diabetes']
|
195 |
+
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
|
196 |
+
|
197 |
+
# Redefine numeric_features after one-hot encoding and after dropping the target column
|
198 |
+
numeric_features = X.select_dtypes(include=['int64', 'float64']).columns
|
199 |
+
|
200 |
+
# Convert all column names to strings
|
201 |
+
X_train.columns = X_train.columns.astype(str)
|
202 |
+
X_test.columns = X_test.columns.astype(str)
|
203 |
+
|
204 |
+
# Scale numeric features
|
205 |
+
scaler = StandardScaler()
|
206 |
+
|
207 |
+
# Save column names before scaling
|
208 |
+
X_train_df = X_train # Save as DataFrame before scaling
|
209 |
+
X_test_df = X_test # Save as DataFrame before scaling
|
210 |
+
feature_names = X_train_df.columns # Store feature names separately
|
211 |
+
|
212 |
+
# Apply StandardScaler (returns a NumPy array)
|
213 |
+
scaler = StandardScaler()
|
214 |
+
X_train = scaler.fit_transform(X_train)
|
215 |
+
X_test = scaler.transform(X_test)
|
216 |
+
|
217 |
+
# Convert back to DataFrame after scaling
|
218 |
+
X_train = pd.DataFrame(X_train, columns=feature_names)
|
219 |
+
X_test = pd.DataFrame(X_test, columns=feature_names)
|
220 |
+
|
221 |
+
# Initialize session state for model training flag
|
222 |
+
if 'models_trained' not in st.session_state:
|
223 |
+
st.session_state['models_trained'] = False
|
224 |
+
|
225 |
+
# ML Models
|
226 |
+
st.subheader("Machine Learning Models")
|
227 |
+
|
228 |
+
# Initialize session state for models
|
229 |
+
if 'models' not in st.session_state:
|
230 |
+
st.session_state['models'] = {
|
231 |
+
"Logistic Regression": LogisticRegression(),
|
232 |
+
"Naive Bayes": GaussianNB(),
|
233 |
+
"SVM": SVC(),
|
234 |
+
"Decision Tree": DecisionTreeClassifier(),
|
235 |
+
"Random Forest": RandomForestClassifier(),
|
236 |
+
"Gradient Boosting": GradientBoostingClassifier(),
|
237 |
+
"MLP Neural Network": MLPClassifier()
|
238 |
+
}
|
239 |
+
|
240 |
+
# Create tabs for different models
|
241 |
+
model_tabs = st.tabs(st.session_state['models'].keys())
|
242 |
+
|
243 |
+
# Train the models and store them in session state
|
244 |
+
if not st.session_state['models_trained']:
|
245 |
+
with st.spinner("Training Models..."):
|
246 |
+
for i, (model_name, model) in enumerate(st.session_state['models'].items()):
|
247 |
+
with model_tabs[i]:
|
248 |
+
st.write(model_name)
|
249 |
+
model.fit(X_train, y_train)
|
250 |
+
y_pred = model.predict(X_test)
|
251 |
+
st.write("Confusion Matrix:")
|
252 |
+
st.write(confusion_matrix(y_test, y_pred))
|
253 |
+
cr = classification_report(y_test, y_pred, output_dict=True)
|
254 |
+
# Display classification report as dataframe
|
255 |
+
cr_df = pd.DataFrame(cr).transpose()
|
256 |
+
st.write(f"Classification Report - {model_name}")
|
257 |
+
st.write(cr_df)
|
258 |
+
st.session_state['models_trained'] = True
|
259 |
+
|
260 |
+
# Diabetes Prediction
|
261 |
+
st.subheader("Diabetes Prediction")
|
262 |
+
|
263 |
+
# Select the trained model to use
|
264 |
+
selected_model_name = st.selectbox("Select Trained Model", list(st.session_state['models'].keys()))
|
265 |
+
selected_model = st.session_state['models'][selected_model_name]
|
266 |
+
|
267 |
+
# Input Fields
|
268 |
+
gender = st.selectbox("Gender", ["Female", "Male", "Other"])
|
269 |
+
age = st.number_input("Age", min_value=0, max_value=120, value=30)
|
270 |
+
hypertension = st.selectbox("Hypertension", ['0', '1'])
|
271 |
+
heart_disease = st.selectbox("Heart Disease", ['0', '1'])
|
272 |
+
smoking_history = st.selectbox("Smoking History", ['never', 'No Info', 'current', 'former', 'ever', 'not current'])
|
273 |
+
bmi = st.number_input("BMI", min_value=0.0, value=25.0)
|
274 |
+
hba1c_level = st.number_input("HbA1c Level", min_value=0.0, value=6.0)
|
275 |
+
blood_glucose_level = st.number_input("Blood Glucose Level", min_value=0, value=100)
|
276 |
+
|
277 |
+
if st.button("Predict Diabetes"):
|
278 |
+
# Create a DataFrame for the user input
|
279 |
+
input_data = pd.DataFrame({
|
280 |
+
'gender': [gender],
|
281 |
+
'age': [age],
|
282 |
+
'hypertension': [int(hypertension)], # Convert categorical numerical features to int
|
283 |
+
'heart_disease': [int(heart_disease)],
|
284 |
+
'smoking_history': [smoking_history],
|
285 |
+
'bmi': [bmi],
|
286 |
+
'HbA1c_level': [hba1c_level],
|
287 |
+
'blood_glucose_level': [blood_glucose_level]
|
288 |
+
})
|
289 |
+
|
290 |
+
# Ensure encoding is applied correctly
|
291 |
+
encoded_input = encoder.transform(input_data[['gender', 'smoking_history']])
|
292 |
+
encoded_input_df = pd.DataFrame(encoded_input.toarray(), columns=encoder.get_feature_names_out())
|
293 |
+
|
294 |
+
# Drop the original categorical columns and concatenate the encoded features
|
295 |
+
input_data = input_data.drop(['gender', 'smoking_history'], axis=1)
|
296 |
+
input_data = pd.concat([input_data, encoded_input_df], axis=1)
|
297 |
+
|
298 |
+
# Ensure that the input data has the same columns as training data
|
299 |
+
missing_cols = set(X_train.columns) - set(input_data.columns) # ✅ Corrected line
|
300 |
+
for col in missing_cols:
|
301 |
+
input_data[col] = 0 # Add missing columns with zero values
|
302 |
+
|
303 |
+
# Reorder columns to match training data
|
304 |
+
input_data = input_data.reindex(columns=X_train.columns, fill_value=0)
|
305 |
+
|
306 |
+
# Convert all column names to strings
|
307 |
+
input_data.columns = input_data.columns.astype(str)
|
308 |
+
|
309 |
+
# Scale the user input (convert back to DataFrame after transformation)
|
310 |
+
input_data_scaled = scaler.transform(input_data)
|
311 |
+
input_data_scaled = pd.DataFrame(input_data_scaled, columns=input_data.columns) # Convert back to DataFrame
|
312 |
+
|
313 |
+
# Make prediction using the selected model
|
314 |
+
prediction = selected_model.predict(input_data_scaled)
|
315 |
+
|
316 |
+
# Display the prediction
|
317 |
+
st.write("Prediction:")
|
318 |
+
if prediction[0] == 0:
|
319 |
+
st.info("The model predicts that you do not have diabetes.")
|
320 |
+
else:
|
321 |
+
st.warning("The model predicts that you have diabetes.")
|
322 |
+
|
requirements.txt
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
streamlit
|
2 |
+
pandas
|
3 |
+
scikit-learn
|
4 |
+
matplotlib
|
5 |
+
seaborn
|
6 |
+
datasets
|
7 |
+
huggingface_hub
|