selva1909 commited on
Commit
2c9ec12
·
verified ·
1 Parent(s): e3355b2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +32 -13
app.py CHANGED
@@ -1,6 +1,7 @@
1
  import numpy as np
2
  import pandas as pd
3
  import gradio as gr
 
4
  from sklearn.model_selection import train_test_split
5
  from sklearn.feature_selection import SelectKBest, f_classif
6
  from sklearn.preprocessing import StandardScaler
@@ -24,17 +25,12 @@ if not os.path.exists(MODEL_FILE):
24
  "contrast_intensity": np.random.uniform(50, 200, n_samples), # MRI contrast
25
  })
26
 
27
- # Create balanced tumor labels
28
  y = (
29
  (X["tumor_size"] > 5).astype(int) |
30
  (X["contrast_intensity"] > 120).astype(int)
31
  )
32
 
33
- # Force balance: make half tumor, half no tumor
34
- half = n_samples // 2
35
- y[:half] = 0
36
- y[half:] = 1
37
-
38
  print("Class distribution:", np.bincount(y))
39
 
40
  X_train, X_test, y_train, y_test = train_test_split(
@@ -57,14 +53,36 @@ if not os.path.exists(MODEL_FILE):
57
  # Load model
58
  model = joblib.load(MODEL_FILE)
59
 
60
- def predict_brain_tumor(tumor_size, texture_score, age, contrast_intensity):
 
 
 
61
  input_data = np.array([[tumor_size, texture_score, age, contrast_intensity]])
62
  pred = model.predict(input_data)[0]
63
- return "🧠 Tumor Detected" if pred == 1 else "✅ No Tumor Detected"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
 
65
  with gr.Blocks() as demo:
66
- gr.Markdown("# 🧠 Brain Tumor Detection")
67
- gr.Markdown("Predict brain tumor presence using MRI-based features (simulated demo).")
68
 
69
  with gr.Row():
70
  tumor_size = gr.Slider(1, 10, value=4, step=0.1, label="Tumor Size (cm)")
@@ -72,13 +90,14 @@ with gr.Blocks() as demo:
72
  age = gr.Slider(20, 80, value=40, step=1, label="Patient Age")
73
  contrast_intensity = gr.Slider(50, 200, value=100, step=1, label="MRI Contrast Intensity")
74
 
75
- output = gr.Textbox(label="Prediction")
 
76
 
77
  predict_btn = gr.Button("Predict")
78
  predict_btn.click(
79
- fn=predict_brain_tumor,
80
  inputs=[tumor_size, texture_score, age, contrast_intensity],
81
- outputs=output,
82
  )
83
 
84
  demo.launch()
 
1
  import numpy as np
2
  import pandas as pd
3
  import gradio as gr
4
+ import matplotlib.pyplot as plt
5
  from sklearn.model_selection import train_test_split
6
  from sklearn.feature_selection import SelectKBest, f_classif
7
  from sklearn.preprocessing import StandardScaler
 
25
  "contrast_intensity": np.random.uniform(50, 200, n_samples), # MRI contrast
26
  })
27
 
28
+ # Labels: tumor if size > 5cm or contrast > 120
29
  y = (
30
  (X["tumor_size"] > 5).astype(int) |
31
  (X["contrast_intensity"] > 120).astype(int)
32
  )
33
 
 
 
 
 
 
34
  print("Class distribution:", np.bincount(y))
35
 
36
  X_train, X_test, y_train, y_test = train_test_split(
 
53
  # Load model
54
  model = joblib.load(MODEL_FILE)
55
 
56
+ # Feature names (before selection)
57
+ FEATURES = ["tumor_size", "texture_score", "age", "contrast_intensity"]
58
+
59
+ def predict_and_explain(tumor_size, texture_score, age, contrast_intensity):
60
  input_data = np.array([[tumor_size, texture_score, age, contrast_intensity]])
61
  pred = model.predict(input_data)[0]
62
+
63
+ # Get feature importance from RandomForest
64
+ rf = model.named_steps["classifier"]
65
+ selector = model.named_steps["select"]
66
+
67
+ # Selected features
68
+ mask = selector.get_support()
69
+ selected_features = np.array(FEATURES)[mask]
70
+
71
+ importances = rf.feature_importances_
72
+
73
+ # Plot feature importances
74
+ fig, ax = plt.subplots(figsize=(6, 4))
75
+ ax.barh(selected_features, importances, color="royalblue")
76
+ ax.set_xlabel("Importance")
77
+ ax.set_title("Feature Importance for Tumor Detection")
78
+ plt.tight_layout()
79
+
80
+ result = "🧠 Tumor Detected" if pred == 1 else "✅ No Tumor Detected"
81
+ return result, fig
82
 
83
  with gr.Blocks() as demo:
84
+ gr.Markdown("# 🧠 Brain Tumor Detection with Feature Importance")
85
+ gr.Markdown("Predict brain tumor presence and view feature contributions (simulated demo).")
86
 
87
  with gr.Row():
88
  tumor_size = gr.Slider(1, 10, value=4, step=0.1, label="Tumor Size (cm)")
 
90
  age = gr.Slider(20, 80, value=40, step=1, label="Patient Age")
91
  contrast_intensity = gr.Slider(50, 200, value=100, step=1, label="MRI Contrast Intensity")
92
 
93
+ output_text = gr.Textbox(label="Prediction")
94
+ output_plot = gr.Plot(label="Feature Importance")
95
 
96
  predict_btn = gr.Button("Predict")
97
  predict_btn.click(
98
+ fn=predict_and_explain,
99
  inputs=[tumor_size, texture_score, age, contrast_intensity],
100
+ outputs=[output_text, output_plot],
101
  )
102
 
103
  demo.launch()