Zen-4011 commited on
Commit
8711647
·
verified ·
1 Parent(s): b2dd38d

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +68 -92
src/streamlit_app.py CHANGED
@@ -10,98 +10,50 @@ 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)
@@ -111,7 +63,7 @@ def user_input_features():
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,
@@ -121,24 +73,48 @@ def user_input_features():
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}%")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
  # Title
12
  st.set_page_config(page_title="Diabetes Prediction", page_icon="🩺")
13
+ st.title("Diabetes Prediction System")
14
+ st.write("This app predicts the likelihood of diabetes using the PIMA Indians Diabetes Dataset.")
15
+
16
+ # Load the data
17
+ data_file = "diabetes.csv"
18
+ if not os.path.exists(data_file):
19
+ # check inside src if not found in root
20
+ data_file = "src/diabetes.csv"
21
+
22
+ if not os.path.exists(data_file):
23
+ st.error("Error: 'diabetes.csv' not found. Please upload the file.")
24
+ st.stop()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
 
26
+ # Training the model
27
  @st.cache_resource
28
+ def build_model(path):
29
  df = pd.read_csv(path)
30
 
31
+ # Split features and target
32
+ X = df.drop('Outcome', axis=1)
33
  y = df['Outcome']
34
+
35
  X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
36
 
37
+ # Random Forest Classifier
38
+ rf = RandomForestClassifier(random_state=42)
39
+ rf.fit(X_train, y_train)
40
 
41
+ # Check accuracy
42
+ acc = accuracy_score(y_test, rf.predict(X_test))
43
 
44
+ return rf, acc, df
 
 
 
45
 
46
+ # Get model and data
47
+ model, accuracy, df = build_model(data_file)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
 
49
+ # Display basic stats
50
+ st.write(f"Model Accuracy: **{accuracy * 100:.2f}%**")
51
  st.markdown("---")
52
 
53
+ # Sidebar for user inputs
54
+ st.sidebar.header("Enter Patient Details")
55
 
56
+ def get_user_input():
57
  pregnancies = st.sidebar.slider('Pregnancies', 0, 17, 3)
58
  glucose = st.sidebar.slider('Glucose', 0, 199, 117)
59
  bp = st.sidebar.slider('Blood Pressure', 0, 122, 72)
 
63
  dpf = st.sidebar.slider('Diabetes Pedigree Function', 0.078, 2.42, 0.3725)
64
  age = st.sidebar.slider('Age', 21, 81, 29)
65
 
66
+ user_data = {
67
  'Pregnancies': pregnancies,
68
  'Glucose': glucose,
69
  'BloodPressure': bp,
 
73
  'DiabetesPedigreeFunction': dpf,
74
  'Age': age
75
  }
76
+ return pd.DataFrame(user_data, index=[0])
 
77
 
78
+ input_df = get_user_input()
79
 
80
+ st.subheader('Patient Data')
81
  st.write(input_df)
82
 
83
+ # Prediction button
84
+ if st.button('Predict'):
85
  prediction = model.predict(input_df)
86
+ probs = model.predict_proba(input_df)
87
 
88
+ st.subheader('Results')
 
89
  if prediction[0] == 1:
90
+ st.error(f'High Risk of Diabetes (Confidence: {probs[0][1]*100:.2f}%)')
 
91
  else:
92
+ st.success(f'Low Risk of Diabetes (Confidence: {probs[0][0]*100:.2f}%)')
93
+
94
+ st.markdown("---")
95
+
96
+ # Graphs and Analysis
97
+ if st.checkbox("Show Graphs"):
98
+ st.subheader("Data Analysis")
99
+
100
+ col1, col2 = st.columns(2)
101
+
102
+ with col1:
103
+ st.write("Outcome Distribution")
104
+ fig1, ax1 = plt.subplots()
105
+ df['Outcome'].value_counts().plot.pie(autopct='%1.1f%%', ax=ax1, labels=['Healthy', 'Diabetic'], colors=['lightblue', 'lightcoral'])
106
+ ax1.set_ylabel('')
107
+ st.pyplot(fig1)
108
+
109
+ with col2:
110
+ st.write("Correlation Heatmap")
111
+ fig2, ax2 = plt.subplots()
112
+ sns.heatmap(df.corr(), annot=False, cmap='coolwarm', ax=ax2)
113
+ st.pyplot(fig2)
114
+
115
+ st.write("Feature Importance")
116
+ fig3, ax3 = plt.subplots()
117
+ feat_importances = pd.Series(model.feature_importances_, index=df.drop('Outcome', axis=1).columns)
118
+ feat_importances.sort_values().plot(kind='barh', color='teal', ax=ax3)
119
+ st.pyplot(fig3)
120
+