Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
151 lines (124 loc) · 5.38 KB
/
Copy pathapp.py
File metadata and controls
151 lines (124 loc) · 5.38 KB
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
import streamlit as st
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.neighbors import KNeighborsClassifier
from sklearn.preprocessing import LabelEncoder, StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, confusion_matrix
import os
st.set_page_config(
page_title="Diabetes Drug Prescriber",
page_icon="💉",
layout="wide"
)
st.title("💉 Diabetes Medication Prescriber & KNN Classification Studio")
st.markdown("""
Interactive Machine Learning Application for **Diabetes Drug Selection** using K-Nearest Neighbors (KNN) and Clinical Profile Analysis.
""")
# Load dataset
@st.cache_data
def load_drug_data():
if os.path.exists("drug200.csv"):
df = pd.read_csv("drug200.csv")
else:
np.random.seed(42)
n = 200
df = pd.DataFrame({
'Age': np.random.randint(15, 74, n),
'Sex': np.random.choice(['M', 'F'], n),
'BP': np.random.choice(['HIGH', 'NORMAL', 'LOW'], n),
'Cholesterol': np.random.choice(['HIGH', 'NORMAL'], n),
'Na_to_K': np.random.uniform(6.0, 38.0, n),
'Drug': np.random.choice(['drugA', 'drugB', 'drugC', 'drugX', 'DrugY'], n)
})
return df
df = load_drug_data()
tab1, tab2, tab3 = st.tabs(["🔮 Patient Medication Prescriber", "📈 KNN Elbow Curve & Hyperparameters", "📊 Clinical Profile EDA"])
# Preprocessing
X = df.copy()
le_sex = LabelEncoder()
le_bp = LabelEncoder()
le_chol = LabelEncoder()
le_drug = LabelEncoder()
X['Sex'] = le_sex.fit_transform(X['Sex'])
X['BP'] = le_bp.fit_transform(X['BP'])
X['Cholesterol'] = le_chol.fit_transform(X['Cholesterol'])
y = le_drug.fit_transform(X['Drug'])
X_features = X.drop(columns=['Drug'])
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X_features)
X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2, random_state=42)
with tab1:
st.subheader("Predict Recommended Diabetes Medication")
c1, c2, c3 = st.columns(3)
with c1:
age_in = st.slider("Patient Age", 15, 80, 45)
sex_in = st.selectbox("Gender", le_sex.classes_)
with c2:
bp_in = st.selectbox("Blood Pressure (BP)", le_bp.classes_)
chol_in = st.selectbox("Cholesterol Level", le_chol.classes_)
with c3:
nak_in = st.slider("Sodium-to-Potassium Ratio (Na_to_K)", 5.0, 40.0, 18.2)
k_val = st.slider("K Neighbors (KNN)", 1, 15, 5)
if st.button("🔮 Prescribe Medication", type="primary"):
sex_enc = le_sex.transform([sex_in])[0]
bp_enc = le_bp.transform([bp_in])[0]
chol_enc = le_chol.transform([chol_in])[0]
raw_vec = [[age_in, sex_enc, bp_enc, chol_enc, nak_in]]
scaled_vec = scaler.transform(raw_vec)
knn_model = KNeighborsClassifier(n_neighbors=k_val)
knn_model.fit(X_train, y_train)
pred_class = knn_model.predict(scaled_vec)[0]
pred_proba = knn_model.predict_proba(scaled_vec)[0]
rec_drug = le_drug.inverse_transform([pred_class])[0]
st.success(f"### Prescribed Drug: **{rec_drug}**")
# Display class probabilities
st.markdown("#### KNN Prediction Confidence:")
prob_df = pd.DataFrame({
'Drug Class': le_drug.classes_,
'Probability': pred_proba
}).sort_values(by='Probability', ascending=False)
st.dataframe(prob_df, use_container_width=True)
with tab2:
st.subheader("K-Neighbors Optimization (Elbow Method)")
k_range = range(1, 20)
acc_scores = []
for k in k_range:
m = KNeighborsClassifier(n_neighbors=k)
m.fit(X_train, y_train)
acc_scores.append(accuracy_score(y_test, m.predict(X_test)))
fig_k, ax_k = plt.subplots(figsize=(8, 3.5))
ax_k.plot(k_range, acc_scores, marker='o', color='#3b82f6', linewidth=2)
ax_k.set_xlabel("Value of K")
ax_k.set_ylabel("Testing Accuracy")
ax_k.set_title("KNN Accuracy vs Number of Neighbors (K)")
ax_k.grid(True, alpha=0.3)
st.pyplot(fig_k)
st.markdown("#### Confusion Matrix for Selected K")
m_opt = KNeighborsClassifier(n_neighbors=k_val)
m_opt.fit(X_train, y_train)
cm = confusion_matrix(y_test, m_opt.predict(X_test))
fig_cm, ax_cm = plt.subplots(figsize=(5, 4))
sns.heatmap(cm, annot=True, fmt='d', xticklabels=le_drug.classes_, yticklabels=le_drug.classes_, cmap='Blues', ax=ax_cm)
ax_cm.set_xlabel("Predicted")
ax_cm.set_ylabel("Actual")
st.pyplot(fig_cm)
with tab3:
st.subheader("Patient Clinical Data Exploratory Analysis")
col_a, col_b = st.columns(2)
with col_a:
st.markdown("#### Na_to_K Ratio vs Age by Drug Prescription")
fig_scatter, ax_scatter = plt.subplots(figsize=(5, 3.5))
sns.scatterplot(data=df, x='Age', y='Na_to_K', hue='Drug', palette='Set1', ax=ax_scatter)
ax_scatter.axhline(15.0, color='red', linestyle='--', label='Na_to_K Threshold (15)')
ax_scatter.legend()
st.pyplot(fig_scatter)
with col_b:
st.markdown("#### Blood Pressure vs Drug Prevalence")
fig_bp, ax_bp = plt.subplots(figsize=(5, 3.5))
sns.countplot(data=df, x='BP', hue='Drug', palette='Set1', ax=ax_bp)
st.pyplot(fig_bp)
st.markdown("---")
st.caption("Developed by **Muhammad Amarus Salam** | Diabetes Clinical Machine Learning Suite.")