selva1909 commited on
Commit
a975b32
·
verified ·
1 Parent(s): 3de3a39

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -89
app.py CHANGED
@@ -1,103 +1,69 @@
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
8
- from sklearn.pipeline import Pipeline
9
- from sklearn.ensemble import RandomForestClassifier
10
- from sklearn.metrics import accuracy_score
11
- import joblib
12
  import os
 
13
 
14
- MODEL_FILE = "brain_tumor_model.pkl"
15
 
 
 
 
16
  if not os.path.exists(MODEL_FILE):
17
- np.random.seed(42)
18
- n_samples = 500
19
-
20
- # Simulated dataset
21
- X = pd.DataFrame({
22
- "tumor_size": np.random.uniform(1, 10, n_samples), # cm
23
- "texture_score": np.random.uniform(0, 1, n_samples), # texture feature
24
- "age": np.random.randint(20, 80, n_samples), # age
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(
37
- X, y, test_size=0.2, random_state=42, stratify=y
38
- )
39
-
40
- pipeline = Pipeline([
41
- ("scaler", StandardScaler()),
42
- ("select", SelectKBest(score_func=f_classif, k=3)),
43
- ("classifier", RandomForestClassifier(n_estimators=200, random_state=42)),
44
  ])
45
-
46
- pipeline.fit(X_train, y_train)
47
-
48
- y_pred = pipeline.predict(X_test)
49
- print("Accuracy:", accuracy_score(y_test, y_pred))
50
-
51
- joblib.dump(pipeline, MODEL_FILE)
52
-
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)")
89
- texture_score = gr.Slider(0, 1, value=0.5, step=0.01, label="Texture Score")
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()
 
 
 
1
  import gradio as gr
2
+ import tensorflow as tf
3
+ from tensorflow.keras import layers, models
4
+ import numpy as np
 
 
 
 
 
5
  import os
6
+ import joblib
7
 
8
+ MODEL_FILE = "brain_tumor_cnn.h5"
9
 
10
+ # ---------------------------
11
+ # 1. Build or Load Model
12
+ # ---------------------------
13
  if not os.path.exists(MODEL_FILE):
14
+ # Simple CNN for demo (not trained on real data here!)
15
+ model = models.Sequential([
16
+ layers.Input(shape=(128, 128, 3)),
17
+ layers.Conv2D(16, (3,3), activation='relu'),
18
+ layers.MaxPooling2D((2,2)),
19
+ layers.Conv2D(32, (3,3), activation='relu'),
20
+ layers.MaxPooling2D((2,2)),
21
+ layers.Flatten(),
22
+ layers.Dense(64, activation='relu'),
23
+ layers.Dense(1, activation='sigmoid') # binary: tumor / no tumor
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  ])
25
+ model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
26
+
27
+ # Fake training with random data (for demo purposes only!)
28
+ X_fake = np.random.rand(50, 128, 128, 3)
29
+ y_fake = np.random.randint(0, 2, 50)
30
+ model.fit(X_fake, y_fake, epochs=1, verbose=1)
31
+
32
+ model.save(MODEL_FILE)
33
+ else:
34
+ model = tf.keras.models.load_model(MODEL_FILE)
35
+
36
+
37
+ # ---------------------------
38
+ # 2. Prediction Function
39
+ # ---------------------------
40
+ def predict_tumor(image):
41
+ # Resize & normalize
42
+ img = image.resize((128, 128))
43
+ img_array = np.array(img) / 255.0
44
+ img_array = np.expand_dims(img_array, axis=0)
45
+
46
+ pred = model.predict(img_array)[0][0]
47
+
48
+ if pred > 0.5:
49
+ return "🧠 Tumor Detected (Probability: {:.2f})".format(pred)
50
+ else:
51
+ return "✅ No Tumor Detected (Probability: {:.2f})".format(1 - pred)
52
+
53
+
54
+ # ---------------------------
55
+ # 3. Gradio UI
56
+ # ---------------------------
 
 
 
 
 
 
57
  with gr.Blocks() as demo:
58
+ gr.Markdown("# 🧠 Brain Tumor Detection from MRI Image")
59
+ gr.Markdown("Upload an MRI scan to predict whether a brain tumor is present (demo with fake training).")
60
 
61
  with gr.Row():
62
+ input_img = gr.Image(type="pil", label="Upload MRI Image")
63
+
 
 
 
64
  output_text = gr.Textbox(label="Prediction")
 
65
 
66
  predict_btn = gr.Button("Predict")
67
+ predict_btn.click(fn=predict_tumor, inputs=input_img, outputs=output_text)
 
 
 
 
68
 
69
  demo.launch()