selva1909 commited on
Commit
d514ed0
·
verified ·
1 Parent(s): 91fe40e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +27 -30
app.py CHANGED
@@ -2,37 +2,37 @@ 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_regression
6
  from sklearn.preprocessing import StandardScaler
7
  from sklearn.pipeline import Pipeline
8
- from sklearn.ensemble import RandomForestRegressor
9
- from sklearn.metrics import mean_squared_error, r2_score
10
  import joblib
11
  import os
12
 
13
  # ---------------------------
14
  # 1. Train or Load Model
15
  # ---------------------------
16
- MODEL_FILE = "turgor_model.pkl"
17
 
18
  if not os.path.exists(MODEL_FILE):
19
  np.random.seed(42)
20
  n_samples = 500
21
 
 
22
  X = pd.DataFrame({
23
- "leaf_thickness": np.random.uniform(0.2, 1.0, n_samples),
24
- "water_content": np.random.uniform(60, 95, n_samples),
25
- "osmotic_pressure": np.random.uniform(0.5, 2.5, n_samples),
26
- "temperature": np.random.uniform(15, 40, n_samples),
27
  })
28
 
 
29
  y = (
30
- 0.3 * X["leaf_thickness"]
31
- + 0.5 * X["water_content"]
32
- - 0.2 * X["temperature"]
33
- + 0.8 * X["osmotic_pressure"]
34
- + np.random.normal(0, 2, n_samples)
35
  )
 
36
 
37
  X_train, X_test, y_train, y_test = train_test_split(
38
  X, y, test_size=0.2, random_state=42
@@ -41,16 +41,15 @@ if not os.path.exists(MODEL_FILE):
41
  pipeline = Pipeline(
42
  [
43
  ("scaler", StandardScaler()),
44
- ("select", SelectKBest(score_func=f_regression, k=3)), # top 3 features
45
- ("regressor", RandomForestRegressor(n_estimators=100, random_state=42)),
46
  ]
47
  )
48
 
49
  pipeline.fit(X_train, y_train)
50
 
51
  y_pred = pipeline.predict(X_test)
52
- print("MSE:", mean_squared_error(y_test, y_pred))
53
- print("R2 Score:", r2_score(y_test, y_pred))
54
 
55
  joblib.dump(pipeline, MODEL_FILE)
56
 
@@ -60,32 +59,30 @@ model = joblib.load(MODEL_FILE)
60
  # ---------------------------
61
  # 2. Prediction Function
62
  # ---------------------------
63
- def predict_turgor(leaf_thickness, water_content, osmotic_pressure, temperature):
64
- input_data = np.array(
65
- [[leaf_thickness, water_content, osmotic_pressure, temperature]]
66
- )
67
  pred = model.predict(input_data)[0]
68
- return f"Predicted Turgor Pressure: {pred:.2f} units"
69
 
70
  # ---------------------------
71
  # 3. Gradio UI
72
  # ---------------------------
73
  with gr.Blocks() as demo:
74
- gr.Markdown("# 🌱 Turgor Pressure Detection")
75
- gr.Markdown("Predict plant turgor pressure using physiological and environmental features.")
76
 
77
  with gr.Row():
78
- leaf_thickness = gr.Slider(0.2, 1.0, value=0.5, step=0.01, label="Leaf Thickness (mm)")
79
- water_content = gr.Slider(60, 95, value=80, step=0.1, label="Water Content (%)")
80
- osmotic_pressure = gr.Slider(0.5, 2.5, value=1.2, step=0.01, label="Osmotic Pressure (MPa)")
81
- temperature = gr.Slider(15, 40, value=25, step=0.5, label="Temperature (°C)")
82
 
83
  output = gr.Textbox(label="Prediction")
84
 
85
  predict_btn = gr.Button("Predict")
86
  predict_btn.click(
87
- fn=predict_turgor,
88
- inputs=[leaf_thickness, water_content, osmotic_pressure, temperature],
89
  outputs=output,
90
  )
91
 
 
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
7
  from sklearn.pipeline import Pipeline
8
+ from sklearn.ensemble import RandomForestClassifier
9
+ from sklearn.metrics import accuracy_score
10
  import joblib
11
  import os
12
 
13
  # ---------------------------
14
  # 1. Train or Load Model
15
  # ---------------------------
16
+ MODEL_FILE = "brain_tumor_model.pkl"
17
 
18
  if not os.path.exists(MODEL_FILE):
19
  np.random.seed(42)
20
  n_samples = 500
21
 
22
+ # Simulated dataset (replace with MRI-extracted features later)
23
  X = pd.DataFrame({
24
+ "tumor_size": np.random.uniform(1, 10, n_samples), # cm
25
+ "texture_score": np.random.uniform(0, 1, n_samples), # extracted from MRI texture
26
+ "age": np.random.randint(20, 80, n_samples), # patient age
27
+ "contrast_intensity": np.random.uniform(50, 200, n_samples), # MRI contrast
28
  })
29
 
30
+ # Simulated binary labels: 1 = Tumor present, 0 = No tumor
31
  y = (
32
+ (X["tumor_size"] > 5).astype(int) |
33
+ (X["contrast_intensity"] > 120).astype(int)
 
 
 
34
  )
35
+ y = np.where(np.random.rand(n_samples) > 0.9, 1 - y, y) # add noise
36
 
37
  X_train, X_test, y_train, y_test = train_test_split(
38
  X, y, test_size=0.2, random_state=42
 
41
  pipeline = Pipeline(
42
  [
43
  ("scaler", StandardScaler()),
44
+ ("select", SelectKBest(score_func=f_classif, k=3)), # select best 3 features
45
+ ("classifier", RandomForestClassifier(n_estimators=100, random_state=42)),
46
  ]
47
  )
48
 
49
  pipeline.fit(X_train, y_train)
50
 
51
  y_pred = pipeline.predict(X_test)
52
+ print("Accuracy:", accuracy_score(y_test, y_pred))
 
53
 
54
  joblib.dump(pipeline, MODEL_FILE)
55
 
 
59
  # ---------------------------
60
  # 2. Prediction Function
61
  # ---------------------------
62
+ def predict_brain_tumor(tumor_size, texture_score, age, contrast_intensity):
63
+ input_data = np.array([[tumor_size, texture_score, age, contrast_intensity]])
 
 
64
  pred = model.predict(input_data)[0]
65
+ return "🧠 Tumor Detected" if pred == 1 else "✅ No Tumor Detected"
66
 
67
  # ---------------------------
68
  # 3. Gradio UI
69
  # ---------------------------
70
  with gr.Blocks() as demo:
71
+ gr.Markdown("# 🧠 Brain Tumor Detection")
72
+ gr.Markdown("Predict brain tumor presence using MRI-based features (simulated demo).")
73
 
74
  with gr.Row():
75
+ tumor_size = gr.Slider(1, 10, value=4, step=0.1, label="Tumor Size (cm)")
76
+ texture_score = gr.Slider(0, 1, value=0.5, step=0.01, label="Texture Score")
77
+ age = gr.Slider(20, 80, value=40, step=1, label="Patient Age")
78
+ contrast_intensity = gr.Slider(50, 200, value=100, step=1, label="MRI Contrast Intensity")
79
 
80
  output = gr.Textbox(label="Prediction")
81
 
82
  predict_btn = gr.Button("Predict")
83
  predict_btn.click(
84
+ fn=predict_brain_tumor,
85
+ inputs=[tumor_size, texture_score, age, contrast_intensity],
86
  outputs=output,
87
  )
88