02ST commited on
Commit
abe72ee
·
verified ·
1 Parent(s): d5980d3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -529
app.py CHANGED
@@ -114,533 +114,4 @@ with gr.Blocks() as demo:
114
  outputs=[status_output, prob_output, model_output]
115
  )
116
 
117
- demo.launch()import numpy as np
118
- import gradio as gr
119
- import joblib
120
- from tensorflow.keras.models import load_model
121
-
122
- # ============================================================
123
- # LOAD MODELS & SCALERS
124
- # ============================================================
125
-
126
- knn_model = joblib.load("knn_model.pkl")
127
- svm_model = joblib.load("rbf_svm_model.pkl")
128
- ann_model = load_model("ann_model.keras")
129
-
130
- scaler_rfe = joblib.load("scaler_rfe.pkl")
131
- selected_features = joblib.load("selected_features.pkl")
132
-
133
- print("Selected features used by the interface:")
134
- print(selected_features)
135
-
136
-
137
- # ============================================================
138
- # 1. ENCODING MAPS
139
- # Must be EXACTLY the same as training
140
- # ============================================================
141
-
142
- # IMPORTANT:
143
- # Training used Female = 0, Male = 1
144
- gender_map = {
145
- "Female": 0,
146
- "Male": 1
147
- }
148
-
149
- binary_map = {
150
- "No": 0,
151
- "Yes": 1
152
- }
153
-
154
- ordinal_map = {
155
- "Low": 0,
156
- "Medium": 1,
157
- "High": 2
158
- }
159
-
160
- # Alcohol:
161
- # None is meaningful = no alcohol consumption
162
- alcohol_map = {
163
- "None": 0,
164
- "Low": 1,
165
- "Medium": 2,
166
- "High": 3
167
- }
168
-
169
-
170
- binary_features = {
171
- 'smoking',
172
- 'family_hd',
173
- 'diabetes',
174
- 'high_bp',
175
- 'low_hdl',
176
- 'high_ldl'
177
- }
178
-
179
- ordinal_features = {
180
- 'exercise',
181
- 'stress',
182
- 'sugar'
183
- }
184
-
185
-
186
- # ============================================================
187
- # 2. ENCODE USER INPUT
188
- # ============================================================
189
-
190
- def encode_input_value(feature, value):
191
-
192
- if feature == 'gender':
193
- return gender_map[value]
194
-
195
- if feature in binary_features:
196
- return binary_map[value]
197
-
198
- if feature == 'alcohol':
199
- return alcohol_map[value]
200
-
201
- if feature in ordinal_features:
202
- return ordinal_map[value]
203
-
204
- # Numeric feature
205
- return float(value)
206
-
207
-
208
- # ============================================================
209
- # 3. PREDICTION FUNCTION
210
- # ============================================================
211
-
212
- def predict_heart_disease(model_choice, *feature_values):
213
-
214
- # Check input count
215
- if len(feature_values) != len(selected_features):
216
- return (
217
- "Input Error",
218
- "Input Error",
219
- model_choice
220
- )
221
-
222
- # ---------------------------------------------
223
- # Encode input using exact selected feature order
224
- # ---------------------------------------------
225
-
226
- encoded_inputs = []
227
-
228
- for feature, value in zip(
229
- selected_features,
230
- feature_values
231
- ):
232
-
233
- encoded_value = encode_input_value(
234
- feature,
235
- value
236
- )
237
-
238
- encoded_inputs.append(
239
- encoded_value
240
- )
241
-
242
-
243
- # ---------------------------------------------
244
- # Convert into 2D array
245
- # ---------------------------------------------
246
-
247
- X_input = np.array(
248
- [encoded_inputs],
249
- dtype=float
250
- )
251
-
252
-
253
- # ---------------------------------------------
254
- # IMPORTANT:
255
- # Use SAME scaler used during model training
256
- # ---------------------------------------------
257
-
258
- X_scaled = scaler_rfe.transform(
259
- X_input
260
- )
261
-
262
-
263
- # ---------------------------------------------
264
- # DEBUG
265
- # You can see whether UI inputs are really changing
266
- # ---------------------------------------------
267
-
268
- print("\n==============================")
269
- print("Model:", model_choice)
270
-
271
- print("\nSelected features:")
272
- print(selected_features)
273
-
274
- print("\nRaw UI values:")
275
- print(feature_values)
276
-
277
- print("\nEncoded values:")
278
- print(encoded_inputs)
279
-
280
- print("\nScaled values:")
281
- print(X_scaled)
282
-
283
- print("==============================")
284
-
285
-
286
- # ========================================================
287
- # KNN
288
- # ========================================================
289
-
290
- if model_choice == "KNN":
291
-
292
- y_pred = knn_model.predict(
293
- X_scaled
294
- )[0]
295
-
296
- y_prob = knn_model.predict_proba(
297
- X_scaled
298
- )[0][1]
299
-
300
-
301
- # ========================================================
302
- # SVM
303
- # ========================================================
304
-
305
- elif model_choice == "SVM":
306
-
307
- y_pred = svm_model.predict(
308
- X_scaled
309
- )[0]
310
-
311
- if hasattr(
312
- svm_model,
313
- "predict_proba"
314
- ):
315
-
316
- y_prob = svm_model.predict_proba(
317
- X_scaled
318
- )[0][1]
319
-
320
- else:
321
-
322
- score = svm_model.decision_function(
323
- X_scaled
324
- )[0]
325
-
326
- # Convert decision score to approximate probability
327
- y_prob = 1 / (
328
- 1 + np.exp(-score)
329
- )
330
-
331
-
332
- # ========================================================
333
- # ANN
334
- # ========================================================
335
-
336
- elif model_choice == "ANN":
337
-
338
- y_prob = float(
339
- ann_model.predict(
340
- X_scaled,
341
- verbose=0
342
- )[0][0]
343
- )
344
-
345
- y_pred = int(
346
- y_prob >= 0.5
347
- )
348
-
349
-
350
- else:
351
-
352
- return (
353
- "Invalid model choice",
354
- "Invalid model choice",
355
- "Invalid model choice"
356
- )
357
-
358
-
359
- # ---------------------------------------------
360
- # Debug prediction
361
- # ---------------------------------------------
362
-
363
- print("\nPrediction:", y_pred)
364
- print("Probability:", y_prob)
365
-
366
-
367
- # ---------------------------------------------
368
- # Convert prediction into readable result
369
- # ---------------------------------------------
370
-
371
- status = (
372
- "Yes"
373
- if int(y_pred) == 1
374
- else "No"
375
- )
376
-
377
-
378
- # Use 4 decimal places so values such as
379
- # 0.004 don't appear as simply 0.00
380
- probability_text = (
381
- f"{y_prob:.4f} "
382
- f"({y_prob * 100:.2f}%)"
383
- )
384
-
385
-
386
- return (
387
- status,
388
- probability_text,
389
- model_choice
390
- )
391
-
392
-
393
- # ============================================================
394
- # 4. MODEL CHOICES
395
- # ============================================================
396
-
397
- model_choices = [
398
- "ANN",
399
- "SVM",
400
- "KNN"
401
- ]
402
-
403
-
404
- # ============================================================
405
- # 5. FEATURE LABELS
406
- # ============================================================
407
-
408
- feature_labels = {
409
-
410
- 'age': 'Age',
411
-
412
- 'gender': 'Gender',
413
-
414
- 'blood_pressure':
415
- 'Blood Pressure',
416
-
417
- 'cholesterol':
418
- 'Cholesterol Level',
419
-
420
- 'exercise':
421
- 'Exercise Habits',
422
-
423
- 'smoking':
424
- 'Smoking',
425
-
426
- 'family_hd':
427
- 'Family Heart Disease',
428
-
429
- 'diabetes':
430
- 'Diabetes',
431
-
432
- 'bmi':
433
- 'BMI',
434
-
435
- 'high_bp':
436
- 'High Blood Pressure',
437
-
438
- 'low_hdl':
439
- 'Low HDL Cholesterol',
440
-
441
- 'high_ldl':
442
- 'High LDL Cholesterol',
443
-
444
- 'alcohol':
445
- 'Alcohol Consumption',
446
-
447
- 'stress':
448
- 'Stress Level',
449
-
450
- 'sleep_hours':
451
- 'Sleep Hours',
452
-
453
- 'sugar':
454
- 'Sugar Consumption',
455
-
456
- 'triglyceride':
457
- 'Triglyceride Level',
458
-
459
- 'fasting_bs':
460
- 'Fasting Blood Sugar',
461
-
462
- 'crp':
463
- 'CRP Level',
464
-
465
- 'homocysteine':
466
- 'Homocysteine Level'
467
- }
468
-
469
-
470
- # ============================================================
471
- # 6. CREATE INPUT COMPONENT
472
- # ============================================================
473
-
474
- def create_feature_input(feature):
475
-
476
- label = feature_labels.get(
477
- feature,
478
- feature
479
- )
480
-
481
-
482
- # Gender
483
- if feature == 'gender':
484
-
485
- return gr.Dropdown(
486
- ["Female", "Male"],
487
- label=label,
488
- value="Female"
489
- )
490
-
491
-
492
- # Yes / No
493
- if feature in binary_features:
494
-
495
- return gr.Dropdown(
496
- ["No", "Yes"],
497
- label=label,
498
- value="No"
499
- )
500
-
501
-
502
- # Alcohol
503
- if feature == 'alcohol':
504
-
505
- return gr.Dropdown(
506
- [
507
- "None",
508
- "Low",
509
- "Medium",
510
- "High"
511
- ],
512
- label=label,
513
- value="None"
514
- )
515
-
516
-
517
- # Ordinal
518
- if feature in ordinal_features:
519
-
520
- return gr.Dropdown(
521
- [
522
- "Low",
523
- "Medium",
524
- "High"
525
- ],
526
- label=label,
527
- value="Medium"
528
- )
529
-
530
-
531
- # Numeric
532
- return gr.Number(
533
- label=label
534
- )
535
-
536
-
537
- # ============================================================
538
- # 7. GRADIO UI
539
- # ============================================================
540
-
541
- with gr.Blocks() as demo:
542
-
543
- gr.Markdown(
544
- """
545
- <h2 style='text-align:center'>
546
- 💓 Heart Disease Prediction 💓
547
- </h2>
548
- """
549
- )
550
-
551
-
552
- # --------------------------------------------------------
553
- # Model selection
554
- # --------------------------------------------------------
555
-
556
- with gr.Row():
557
-
558
- model_input = gr.Dropdown(
559
- model_choices,
560
- label="Choose Model",
561
- value="ANN"
562
- )
563
-
564
-
565
- # --------------------------------------------------------
566
- # Feature inputs
567
- # --------------------------------------------------------
568
-
569
- feature_inputs = []
570
-
571
-
572
- for start in range(
573
- 0,
574
- len(selected_features),
575
- 5
576
- ):
577
-
578
- with gr.Row():
579
-
580
- for feature in selected_features[
581
- start:start + 5
582
- ]:
583
-
584
- component = create_feature_input(
585
- feature
586
- )
587
-
588
- feature_inputs.append(
589
- component
590
- )
591
-
592
-
593
- # --------------------------------------------------------
594
- # Prediction button
595
- # --------------------------------------------------------
596
-
597
- predict_button = gr.Button(
598
- "Predict 💡",
599
- variant="primary"
600
- )
601
-
602
-
603
- # --------------------------------------------------------
604
- # Outputs
605
- # --------------------------------------------------------
606
-
607
- with gr.Row():
608
-
609
- status_output = gr.Textbox(
610
- label="Heart Disease Status"
611
- )
612
-
613
- prob_output = gr.Textbox(
614
- label="Prediction Probability"
615
- )
616
-
617
- model_output = gr.Textbox(
618
- label="Model Selected"
619
- )
620
-
621
-
622
- # --------------------------------------------------------
623
- # Connect button
624
- # --------------------------------------------------------
625
-
626
- predict_button.click(
627
-
628
- fn=predict_heart_disease,
629
-
630
- inputs=[
631
- model_input
632
- ] + feature_inputs,
633
-
634
- outputs=[
635
- status_output,
636
- prob_output,
637
- model_output
638
- ]
639
- )
640
-
641
-
642
- # ============================================================
643
- # 8. LAUNCH
644
- # ============================================================
645
-
646
  demo.launch()
 
114
  outputs=[status_output, prob_output, model_output]
115
  )
116
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 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