Spaces:
Sleeping
Sleeping
Update src/streamlit_app.py
Browse files- src/streamlit_app.py +136 -33
src/streamlit_app.py
CHANGED
|
@@ -1,41 +1,144 @@
|
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
-
import os
|
| 3 |
import pandas as pd
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
-
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
-
|
| 10 |
-
st.subheader("Scanning for 'diabetes.csv'...")
|
| 11 |
-
found = False
|
| 12 |
-
csv_path = ""
|
| 13 |
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
if "diabetes" in file.lower():
|
| 19 |
-
full_path = os.path.join(root, file)
|
| 20 |
-
st.success(f"✅ FOUND IT! Path: `{full_path}`")
|
| 21 |
-
found = True
|
| 22 |
-
csv_path = full_path
|
| 23 |
|
| 24 |
-
if
|
| 25 |
-
|
| 26 |
-
st.warning("Make sure you didn't name it 'Diabetes.csv' (Capital D) or 'diabetes.csv.txt'.")
|
| 27 |
-
|
| 28 |
-
st.subheader("Listing ALL files I can see:")
|
| 29 |
-
# List all files so you can see what IS there
|
| 30 |
-
for root, dirs, files in os.walk("."):
|
| 31 |
-
for file in files:
|
| 32 |
-
st.code(os.path.join(root, file))
|
| 33 |
else:
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Libraries
|
| 2 |
import streamlit as st
|
|
|
|
| 3 |
import pandas as pd
|
| 4 |
+
import os
|
| 5 |
+
import matplotlib.pyplot as plt
|
| 6 |
+
import seaborn as sns
|
| 7 |
+
from sklearn.model_selection import train_test_split
|
| 8 |
+
from sklearn.ensemble import RandomForestClassifier
|
| 9 |
+
from sklearn.metrics import accuracy_score
|
| 10 |
|
| 11 |
+
# Title
|
| 12 |
+
st.set_page_config(page_title="Diabetes Prediction", page_icon="🩺")
|
| 13 |
+
st.title("🩺 Diabetes Prediction System")
|
| 14 |
+
st.write("A Machine Learning model trained on the PIMA Indians Diabetes Dataset.")
|
| 15 |
|
| 16 |
+
# File Loader
|
| 17 |
+
possible_paths = [
|
| 18 |
+
"diabetes.csv", # Root folder
|
| 19 |
+
"src/diabetes.csv", # src folder
|
| 20 |
+
"../diabetes.csv", # Parent folder
|
| 21 |
+
"/app/diabetes.csv" # Docker container absolute path
|
| 22 |
+
]
|
| 23 |
|
| 24 |
+
dataset_path = None
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
+
for path in possible_paths:
|
| 27 |
+
if os.path.exists(path):
|
| 28 |
+
dataset_path = path
|
| 29 |
+
break
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
+
if dataset_path:
|
| 32 |
+
pass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
else:
|
| 34 |
+
st.warning("'diabetes.csv' not found. Using dummy data for demonstration.")
|
| 35 |
+
dummy_data = {
|
| 36 |
+
'Pregnancies': [6, 1, 8, 1, 0, 5, 3, 10],
|
| 37 |
+
'Glucose': [148, 85, 183, 89, 137, 116, 78, 115],
|
| 38 |
+
'BloodPressure': [72, 66, 64, 66, 40, 74, 50, 0],
|
| 39 |
+
'SkinThickness': [35, 29, 0, 23, 35, 0, 32, 0],
|
| 40 |
+
'Insulin': [0, 0, 0, 94, 168, 0, 88, 0],
|
| 41 |
+
'BMI': [33.6, 26.6, 23.3, 28.1, 43.1, 25.6, 31.0, 35.3],
|
| 42 |
+
'DiabetesPedigreeFunction': [0.627, 0.351, 0.672, 0.167, 2.288, 0.201, 0.248, 0.134],
|
| 43 |
+
'Age': [50, 31, 32, 21, 33, 30, 26, 29],
|
| 44 |
+
'Outcome': [1, 0, 1, 0, 1, 0, 1, 0]
|
| 45 |
+
}
|
| 46 |
+
df_dummy = pd.DataFrame(dummy_data)
|
| 47 |
+
df_dummy.to_csv("diabetes.csv", index=False)
|
| 48 |
+
dataset_path = "diabetes.csv"
|
| 49 |
+
|
| 50 |
+
# Train Model
|
| 51 |
+
@st.cache_resource
|
| 52 |
+
def train_model(path):
|
| 53 |
+
df = pd.read_csv(path)
|
| 54 |
+
|
| 55 |
+
# Data Split
|
| 56 |
+
X = df.drop(columns=['Outcome'])
|
| 57 |
+
y = df['Outcome']
|
| 58 |
+
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
|
| 59 |
+
|
| 60 |
+
# Train Random Forest
|
| 61 |
+
model = RandomForestClassifier(random_state=42)
|
| 62 |
+
model.fit(X_train, y_train)
|
| 63 |
+
|
| 64 |
+
# Calculate accuracy
|
| 65 |
+
acc = accuracy_score(y_test, model.predict(X_test))
|
| 66 |
+
|
| 67 |
+
return model, acc, df # Return df as well for plotting
|
| 68 |
+
|
| 69 |
+
# Load and Train
|
| 70 |
+
model, accuracy, df = train_model(dataset_path)
|
| 71 |
+
|
| 72 |
+
# Display Accuracy
|
| 73 |
+
st.write(f"**Model Accuracy:** {accuracy * 100:.2f}%")
|
| 74 |
+
|
| 75 |
+
# UI/UX
|
| 76 |
+
if st.checkbox("Show Model Insights & Graphs"):
|
| 77 |
+
st.subheader("Data Visualizations")
|
| 78 |
+
|
| 79 |
+
col1, col2 = st.columns(2)
|
| 80 |
+
|
| 81 |
+
with col1:
|
| 82 |
+
st.write("**Outcome Distribution**")
|
| 83 |
+
fig1, ax1 = plt.subplots()
|
| 84 |
+
df['Outcome'].value_counts().plot.pie(autopct='%1.1f%%', ax=ax1, labels=['Non-Diabetic', 'Diabetic'], colors=['#66b3ff', '#ff9999'])
|
| 85 |
+
st.pyplot(fig1)
|
| 86 |
+
|
| 87 |
+
with col2:
|
| 88 |
+
st.write("**Correlation Heatmap**")
|
| 89 |
+
fig2, ax2 = plt.subplots()
|
| 90 |
+
sns.heatmap(df.corr(), annot=False, cmap='coolwarm', ax=ax2)
|
| 91 |
+
st.pyplot(fig2)
|
| 92 |
+
|
| 93 |
+
st.write("**Feature Importance (What matters most?)**")
|
| 94 |
+
fig3, ax3 = plt.subplots()
|
| 95 |
+
importances = pd.Series(model.feature_importances_, index=df.drop(columns=['Outcome']).columns)
|
| 96 |
+
importances.sort_values().plot(kind='barh', color='teal', ax=ax3)
|
| 97 |
+
st.pyplot(fig3)
|
| 98 |
+
|
| 99 |
+
st.markdown("---")
|
| 100 |
+
|
| 101 |
+
# Inputs
|
| 102 |
+
st.sidebar.header("Patient Data")
|
| 103 |
+
|
| 104 |
+
def user_input_features():
|
| 105 |
+
pregnancies = st.sidebar.slider('Pregnancies', 0, 17, 3)
|
| 106 |
+
glucose = st.sidebar.slider('Glucose', 0, 199, 117)
|
| 107 |
+
bp = st.sidebar.slider('Blood Pressure', 0, 122, 72)
|
| 108 |
+
skin = st.sidebar.slider('Skin Thickness', 0, 99, 23)
|
| 109 |
+
insulin = st.sidebar.slider('Insulin', 0, 846, 30)
|
| 110 |
+
bmi = st.sidebar.slider('BMI', 0.0, 67.1, 32.0)
|
| 111 |
+
dpf = st.sidebar.slider('Diabetes Pedigree Function', 0.078, 2.42, 0.3725)
|
| 112 |
+
age = st.sidebar.slider('Age', 21, 81, 29)
|
| 113 |
+
|
| 114 |
+
data = {
|
| 115 |
+
'Pregnancies': pregnancies,
|
| 116 |
+
'Glucose': glucose,
|
| 117 |
+
'BloodPressure': bp,
|
| 118 |
+
'SkinThickness': skin,
|
| 119 |
+
'Insulin': insulin,
|
| 120 |
+
'BMI': bmi,
|
| 121 |
+
'DiabetesPedigreeFunction': dpf,
|
| 122 |
+
'Age': age
|
| 123 |
+
}
|
| 124 |
+
features = pd.DataFrame(data, index=[0])
|
| 125 |
+
return features
|
| 126 |
+
|
| 127 |
+
input_df = user_input_features()
|
| 128 |
+
|
| 129 |
+
st.subheader('User Input parameters')
|
| 130 |
+
st.write(input_df)
|
| 131 |
+
|
| 132 |
+
# Prediction
|
| 133 |
+
if st.button('Predict Diabetes Risk'):
|
| 134 |
+
prediction = model.predict(input_df)
|
| 135 |
+
prediction_proba = model.predict_proba(input_df)
|
| 136 |
+
|
| 137 |
+
st.subheader('Prediction Result')
|
| 138 |
+
|
| 139 |
+
if prediction[0] == 1:
|
| 140 |
+
st.error(f' Positive (High Risk of Diabetes)')
|
| 141 |
+
st.write(f"Confidence: {prediction_proba[0][1] * 100:.2f}%")
|
| 142 |
+
else:
|
| 143 |
+
st.success(f' Negative (Low Risk of Diabetes)')
|
| 144 |
+
st.write(f"Confidence: {prediction_proba[0][0] * 100:.2f}%")
|