Bhupen commited on
Commit
2b4c2ee
·
1 Parent(s): 89a8291

Add ML intuitions py file

Browse files
Files changed (2) hide show
  1. app.py +407 -0
  2. requirements.txt +4 -0
app.py ADDED
@@ -0,0 +1,407 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from sklearn.datasets import load_breast_cancer
3
+ from sklearn.linear_model import LogisticRegression
4
+ from sklearn.model_selection import train_test_split
5
+ from sklearn.metrics import accuracy_score, confusion_matrix
6
+ import pandas as pd
7
+ import numpy as np
8
+ import matplotlib.pyplot as plt
9
+ import seaborn as sns
10
+ import pandas as pd
11
+ import time
12
+
13
+ def load_and_train_model():
14
+ data = load_breast_cancer()
15
+ X = pd.DataFrame(data.data, columns=data.feature_names)
16
+ y = pd.Series(data.target)
17
+
18
+ X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, random_state=42)
19
+ model = LogisticRegression(max_iter=10000)
20
+ model.fit(X_train, y_train)
21
+
22
+ y_pred = model.predict(X_test)
23
+ acc = accuracy_score(y_test, y_pred)
24
+ cm = confusion_matrix(y_test, y_pred)
25
+
26
+ return model, X, y, acc, cm, data
27
+
28
+ def main():
29
+ st.set_page_config(page_title="Breast Cancer Classifier", layout="wide")
30
+
31
+ # Load dataset
32
+ data = load_breast_cancer()
33
+ X = pd.DataFrame(data.data, columns=data.feature_names)
34
+ y = pd.Series(data.target)
35
+
36
+ st.subheader("Breast Cancer Classification with Logistic Regression")
37
+
38
+ #st.write(f"**Problem Statement**")
39
+ with st.expander("📌 What we're trying to accomplish..."):
40
+ st.markdown("""
41
+ **Classify whether a tumor is malignant or benign** using medical imaging features.
42
+
43
+ We use **logistic regression** to build a classifier using the Breast Cancer dataset.
44
+
45
+ **Key Objectives**
46
+ 1. Data and `labels` for Machine Learning
47
+ 2. `Discriminative` AI
48
+ 3. Model training and metrics
49
+ 4. `Generate new samples` for prediction
50
+ 5. `Introducing Generative` AI
51
+ """)
52
+
53
+ with st.expander("📘 Why Clean & Labeled Data is Important", expanded=False):
54
+ st.markdown("""
55
+ **The Role of Clean and Labeled Data in Machine Learning**
56
+
57
+ - Machine Learning relies on **historical data to learn** patterns and make predictions. If the data is messy, inconsistent, or poorly labeled, the model’s output can be misleading or even harmful.
58
+
59
+ - **Labels are the foundation.** In supervised learning, we train models using input features and their corresponding correct answers (labels).
60
+ - Example: In medical AI:
61
+ - **Input**: features from a breast scan (mean texture, perimeter, radius...)
62
+ - **Label**: 0 = Malignant, 1 = Benign
63
+ - Without labels, the system cannot learn what patterns lead to which outcomes.
64
+
65
+ - **Labeling requires domain expertise.**
66
+ - Healthcare: A radiologist may label tumors
67
+ - Finance: An analyst marks transactions as fraudulent or not
68
+ - Without expertise, labels may be inconsistent or biased.
69
+
70
+ - **Discriminative features are key.**
71
+ - If malignant tumors tend to have larger mean radius and benign ones have smaller, the model can learn to discriminate effectively.
72
+ - If features overlap across classes, the model struggles to make decisions.
73
+
74
+ - For **Agentic AI systems** — those acting **autonomously on behalf of humans** — poor data quality has real consequences.
75
+ - E.g., An AI assistant triaging patients or approving insurance claims may act unfairly if trained on mislabeled or ambiguous data.
76
+
77
+ - So, **clean, well-labeled, and well-separated data is not just technical hygiene — it’s a leadership mandate** for building trustworthy, safe AI systems.
78
+ """)
79
+
80
+ #st.markdown(f"**Dataset Overview**")
81
+
82
+ feature_descriptions = {
83
+ "radius_mean": "Mean of distances from center to points on the perimeter",
84
+ "texture_mean": "Standard deviation of gray-scale values (texture)",
85
+ "perimeter_mean": "Mean size of the perimeter of the tumor",
86
+ "area_mean": "Mean area of the tumor",
87
+ "smoothness_mean": "Mean of local variation in radius lengths",
88
+ "compactness_mean": "Mean of (perimeter² / area - 1.0)",
89
+ "concavity_mean": "Mean severity of concave portions of the contour",
90
+ "concave points_mean": "Mean number of concave portions of the contour",
91
+ "symmetry_mean": "Mean symmetry of the tumor shape",
92
+ "fractal_dimension_mean": "Mean complexity of the contour (coastline approximation)",
93
+
94
+ "radius_se": "Standard error of radius",
95
+ "texture_se": "Standard error of texture",
96
+ "perimeter_se": "Standard error of perimeter",
97
+ "area_se": "Standard error of area",
98
+ "smoothness_se": "Standard error of smoothness",
99
+ "compactness_se": "Standard error of compactness",
100
+ "concavity_se": "Standard error of concavity",
101
+ "concave points_se": "Standard error of concave points",
102
+ "symmetry_se": "Standard error of symmetry",
103
+ "fractal_dimension_se": "Standard error of fractal dimension",
104
+
105
+ "radius_worst": "Largest radius across all scans",
106
+ "texture_worst": "Largest texture",
107
+ "perimeter_worst": "Largest perimeter",
108
+ "area_worst": "Largest area",
109
+ "smoothness_worst": "Largest smoothness",
110
+ "compactness_worst": "Largest compactness",
111
+ "concavity_worst": "Largest concavity",
112
+ "concave points_worst": "Largest number of concave points",
113
+ "symmetry_worst": "Largest symmetry",
114
+ "fractal_dimension_worst": "Largest fractal dimension"
115
+ }
116
+
117
+ # Convert to DataFrame
118
+ df_features = pd.DataFrame(
119
+ list(feature_descriptions.items()),
120
+ columns=["Feature Name", "Description"]
121
+ )
122
+
123
+ # Display inside an expander
124
+ with st.expander("🧬 Breast Cancer Dataset Features", expanded=False):
125
+ st.dataframe(df_features, use_container_width=True)
126
+
127
+ # Demo the discriminatory abilities of the features
128
+ # Additional expander: Discriminative abilities
129
+ with st.expander("🧠 Discriminative Abilities of Features & How ML Depends on Them", expanded=False):
130
+ st.markdown("""
131
+ **Discriminative features** are those that help distinguish between different classes. ML algorithms learn patterns by identifying such features. If features don't differ across classes, even the best model will struggle to make good predictions.
132
+
133
+ Here are examples from different domains:
134
+
135
+ 1. **Healthcare (Breast Cancer Detection)**
136
+ - *Feature:* `mean radius`, `mean concavity`
137
+ - *Discrimination:* Malignant tumors often have higher mean radius and greater concavity. These differences help separate them from benign ones.
138
+
139
+ 2. **Finance (Fraud Detection)**
140
+ - *Feature:* `transaction amount`, `location mismatch`, `login time`
141
+ - *Discrimination:* Fraudulent transactions are more likely to be high-value, come from unusual locations, or occur at odd hours.
142
+
143
+ 3. **Retail (Customer Churn Prediction)**
144
+ - *Feature:* `number of support tickets`, `monthly usage decline`, `payment delays`
145
+ - *Discrimination:* Customers likely to churn often show reduced usage, frequent issues, or late payments — all useful predictors for ML models.
146
+
147
+ These examples underline the importance of **feature engineering** and **domain knowledge** in building effective ML systems.
148
+ """)
149
+
150
+ # feature discriminatio
151
+ # Load dataset
152
+ data = load_breast_cancer()
153
+ df = pd.DataFrame(data.data, columns=data.feature_names)
154
+ df["target"] = data.target
155
+
156
+ # List of numeric features
157
+ numeric_features = list(df.select_dtypes(include=["float64", "int64"]).columns)
158
+ #numeric_features.remove("target")
159
+
160
+ with st.expander("📊 Explore Feature Discrimination vs Target", expanded=False):
161
+ # 3 column layout
162
+ col1, col2, col3 = st.columns([1, 2, 2])
163
+
164
+ with col1:
165
+ selected_feature = st.selectbox("Select a numeric feature", options=numeric_features)
166
+
167
+ with col2:
168
+ st.write(f"**Distribution of `{selected_feature}` by Target**")
169
+ fig, ax = plt.subplots()
170
+ sns.boxplot(data=df, x="target", y=selected_feature, ax=ax)
171
+ ax.set_xticklabels(["Malignant (0)", "Benign (1)"])
172
+ st.pyplot(fig)
173
+
174
+ with col3:
175
+ mean_diff = df.groupby("target")[selected_feature].mean().diff().abs().iloc[-1]
176
+
177
+ st.markdown(f"""
178
+ **Feature Discrimination Analysis**
179
+ - The feature **`{selected_feature}`** shows how values differ between benign and malignant cases.
180
+ - On average, the difference between classes for this feature is **{mean_diff:.2f}** units.
181
+ - If the box plots show **clear separation** between classes, the feature has high discriminative power.
182
+ - Better separation = better feature = higher ML success.
183
+ - If there's too much overlap, this feature alone may not contribute much to prediction.
184
+ """)
185
+
186
+ with st.expander("🎯 See Class Summary"):
187
+ class_counts = y.value_counts().sort_index()
188
+ st.markdown(f"""
189
+ - **Class 0 (Malignant)**: {class_counts[0]} samples
190
+ - **Class 1 (Benign)**: {class_counts[1]} samples
191
+ """)
192
+
193
+ if st.button("Start the Training"):
194
+ # X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, random_state=42)
195
+ # model = LogisticRegression(max_iter=10000)
196
+ # model.fit(X_train, y_train)
197
+
198
+ # Display a progress bar
199
+ progress_bar = st.progress(0)
200
+ status_text = st.empty() # To update the progress with a message
201
+
202
+ # Split dataset
203
+ X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, random_state=42)
204
+
205
+ # Initialize the Logistic Regression model
206
+ model = LogisticRegression(max_iter=10000)
207
+
208
+ # Simulate training with a progress update
209
+ for i in range(1, 50): # Simulate 100 steps of training
210
+ time.sleep(0.1) # Simulate training time (adjust if needed)
211
+ progress_bar.progress(i) # Update progress bar
212
+ status_text.text(f"Training... {i}% completed")
213
+
214
+ # Fit the model after the progress bar finishes
215
+ model.fit(X_train, y_train)
216
+
217
+ # Display a message when training is completed
218
+ #st.success("Training completed!")
219
+ status_text.text("Training completed!")
220
+
221
+ y_pred = model.predict(X_test)
222
+ accuracy = accuracy_score(y_test, y_pred)
223
+ cm = confusion_matrix(y_test, y_pred)
224
+
225
+ st.success("✅ Training Completed")
226
+
227
+ with st.expander("📊 Model Performance & Interpretation", expanded=True):
228
+
229
+ col1, col2 = st.columns(2)
230
+
231
+ with col1:
232
+ st.write("Confusion Matrix:")
233
+ fig, ax = plt.subplots()
234
+ sns.heatmap(cm, annot=True, fmt="d", cmap="Blues",
235
+ xticklabels=data.target_names,
236
+ yticklabels=data.target_names,
237
+ ax=ax)
238
+ ax.set_xlabel("Predicted")
239
+ ax.set_ylabel("Actual")
240
+ st.pyplot(fig)
241
+
242
+ with col2:
243
+ TP, FN = cm[0]
244
+ FP, TN = cm[1]
245
+
246
+ st.markdown("**🔍 Confusion Matrix Interpretation**")
247
+ st.markdown(f"""
248
+ - **True Positives (TP)** = {TP}: Model correctly predicted **malignant** tumors.
249
+ - **False Negatives (FN)** = {FN}: Model predicted **benign**, but it was actually malignant. ⚠️
250
+ - **False Positives (FP)** = {FP}: Model predicted **malignant**, but it was actually benign.
251
+ - **True Negatives (TN)** = {TN}: Model correctly predicted **benign** tumors.
252
+
253
+ #### 📌 Implications:
254
+ - **FP (False Alarms)** may lead to unnecessary stress and diagnostic procedures.
255
+ - **FN (Missed Diagnoses)** are critical: the model misses malignant tumors — this can delay treatment.
256
+
257
+ > **Clinical Priority:** Minimize **False Negatives**, even if it slightly increases False Positives. This ensures high **recall** and safer patient outcomes.
258
+ """)
259
+
260
+ st.write(f"Accuracy: **{accuracy:.4f}**")
261
+
262
+
263
+ # What variables are the model’s biggest influencers?
264
+ with st.expander("🔍 What variables are the model’s biggest influencers?"):
265
+ n_top = 8
266
+
267
+ st.markdown("""
268
+ The model doesn't just make predictions — it **prioritizes certain variables** that strongly influence whether it flags a tumor as benign or malignant.
269
+
270
+ These are the top {n_top} influential features:
271
+
272
+ """)
273
+
274
+ coef = model.coef_[0]
275
+ feature_importance = pd.Series(np.abs(coef), index=X_train.columns)
276
+
277
+ top_features = feature_importance.sort_values(ascending=False).head(n_top)
278
+ fig, ax = plt.subplots()
279
+ sns.barplot(x=top_features.values, y=top_features.index, palette="viridis", ax=ax)
280
+ ax.set_xlabel("Importance Score")
281
+ ax.set_title("Top Influential Features in Prediction")
282
+ st.pyplot(fig)
283
+
284
+ st.markdown("""
285
+ - **Why this matters :** These features highlight **what the model pays the most attention to**.
286
+ - It helps **domain experts** verify if the model’s focus makes clinical sense.
287
+ - For example, `concavity_worst` and `radius_mean` reflect how irregular or large a tumor appears — both key medical indicators.
288
+
289
+ This kind of **transparency builds trust** in AI decisions.
290
+ """)
291
+
292
+
293
+ st.session_state["model"] = model
294
+ st.session_state["X"] = X
295
+ st.session_state["y"] = y
296
+ st.session_state["target_names"] = data.target_names
297
+
298
+ if "model" in st.session_state:
299
+ st.markdown(f"**Test the model ...**")
300
+ selected_class = st.radio("Generate sample for class:", options=[0, 1],
301
+ format_func=lambda x: st.session_state["target_names"][x])
302
+
303
+
304
+ if st.button("🎲 Generate new Sample (Synthetic) for prediction ..."):
305
+
306
+ # 🔑 Get the trained model first
307
+ model = st.session_state["model"]
308
+
309
+ class_data = st.session_state["X"][st.session_state["y"] == selected_class]
310
+
311
+ # Compute means and stds
312
+ means = class_data.mean()
313
+ stds = class_data.std()
314
+
315
+ # Replace any NaN stds with 0 to avoid generating NaNs
316
+ stds = stds.fillna(0)
317
+
318
+ # Add small random noise (scaled by std dev)
319
+ noise = np.random.normal(loc=0, scale=stds * 0.1)
320
+
321
+ # Generate sample with proper structure
322
+ sample_dict = (means + noise).to_dict()
323
+ sample_df = pd.DataFrame([sample_dict], columns=model.feature_names_in_).astype(float)
324
+
325
+ st.write(f'Generated 1 sample for class : {selected_class}')
326
+
327
+ # Display in 2-column layout
328
+ col1, col2 = st.columns([1, 1])
329
+ with col1:
330
+
331
+ st.markdown("**🧪 How Was This Sample Generated?**")
332
+ st.markdown(f"""
333
+ We used a method called **Class-Conditioned Sampling**, where:
334
+
335
+ - We calculate the **average feature values** (mean) for all training samples belonging to class **`{selected_class}`**.
336
+ - Then we add **small random noise** (proportional to feature-wise standard deviation) to make it realistic.
337
+ """)
338
+ with col2:
339
+
340
+ st.markdown(f"""
341
+ 🔍 **Example with 2 Features:**
342
+
343
+ Suppose for `mean radius` and `mean texture`, we had:
344
+
345
+ - Class `{selected_class}` averages:
346
+ `mean radius` = 14.2, `mean texture` = 20.1
347
+ - Feature std devs:
348
+ `mean radius` = 3.2, `mean texture` = 2.5
349
+ - We generate:
350
+ `mean radius` ≈ 14.2 ± (0.1 × 3.2) → ~14.4
351
+ `mean texture` ≈ 20.1 ± (0.1 × 2.5) → ~20.3
352
+
353
+ ✨ This creates a **new, plausible sample** that belongs to class `{selected_class}`.
354
+ """)
355
+
356
+ # Try to predict
357
+ try:
358
+ prediction = model.predict(sample_df)[0]
359
+ proba = model.predict_proba(sample_df)[0]
360
+
361
+ #st.success(f"🎯 Predicted Class: {prediction} with probability {max(proba):.2f}")
362
+ except Exception as e:
363
+ st.error(f"🔥 Prediction failed: {e}")
364
+
365
+ st.markdown(f"**Prediction:** {prediction} ({st.session_state['target_names'][prediction]})")
366
+ st.markdown(f"**Probability:** Malignant: `{proba[0]:.3f}`, Benign: `{proba[1]:.3f}`")
367
+
368
+ with st.expander("🧠 How This Relates to Generative AI"):
369
+ st.markdown("""
370
+ ##### What We’re Doing Here
371
+
372
+ You're generating **new synthetic samples** that resemble real ones from a particular class by using:
373
+ - The **mean** of real data (signal)
374
+ - A bit of **noise** (variation)
375
+
376
+ This is a basic form of how **Generative AI (GenAI)** works.
377
+
378
+ ---
379
+
380
+ ##### What is Generative AI?
381
+
382
+ > **Generative AI** refers to a class of AI models that can **generate new content** — like text, images, or data samples — that resemble what they’ve seen during training.
383
+
384
+ It does this by:
385
+ - Learning the **distribution** of real data
386
+ - Sampling from that distribution to create **new but realistic** outputs
387
+
388
+ ---
389
+
390
+ ##### Why this Method Counts
391
+
392
+ This "Class-Conditioned Sampling" is like a **simple statistical GenAI**:
393
+ - You use **mean and std dev** to describe the feature distribution for a class.
394
+ - You **generate new samples** by adding random noise to the means.
395
+
396
+ So even without deep learning or neural networks, you're applying the **core idea of GenAI**.
397
+
398
+ ---
399
+
400
+ ##### 🧪 the connection ...
401
+
402
+ > Before diving into large GenAI models like GPT or DALL·E, this gives us a simple, intuitive feel of what it means to "generate" something new based on existing patterns.
403
+ """)
404
+
405
+
406
+ if __name__ == "__main__":
407
+ main()
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ streamlit
2
+ scikit-learn
3
+ pandas
4
+ matplotlib