N566616 commited on
Commit
08d5af0
·
verified ·
1 Parent(s): cfcf6e1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +44 -49
app.py CHANGED
@@ -10,13 +10,14 @@ from sklearn.utils.class_weight import compute_class_weight
10
  from imblearn.over_sampling import RandomOverSampler
11
  import matplotlib.pyplot as plt
12
  import warnings
 
13
  warnings.filterwarnings("ignore")
14
 
15
  def train_and_evaluate(random_state):
16
- # --- Load dataset ---
17
  df = pd.read_csv("updated_medical_data.csv")
18
 
19
- # --- Disease-specific expected vital sign ranges ---
20
  disease_vitals = {
21
  "Macular Degeneration": {"hr": (60, 80), "rr": (12, 20), "temp": (97.5, 98.6)},
22
  "Encephalitis": {"hr": (90, 110), "rr": (18, 24), "temp": (100.4, 103)},
@@ -40,7 +41,7 @@ def train_and_evaluate(random_state):
40
  "Pancreatitis": {"hr": (90, 110), "rr": (16, 24), "temp": (99, 102)}
41
  }
42
 
43
- # --- Feature engineering ---
44
  def create_vital_flags(row):
45
  disease = row['disease_label']
46
  if disease in disease_vitals:
@@ -64,7 +65,6 @@ def train_and_evaluate(random_state):
64
  flags_df = df.apply(create_vital_flags, axis=1)
65
  df = pd.concat([df, flags_df], axis=1)
66
 
67
- # --- Prepare features and labels ---
68
  feature_cols = ['heart_rate', 'respiratory_rate', 'temperature', 'symptom_score',
69
  'hr_high_flag', 'hr_low_flag', 'rr_high_flag', 'rr_low_flag',
70
  'temp_high_flag', 'temp_low_flag', 'fever_flag']
@@ -73,23 +73,23 @@ def train_and_evaluate(random_state):
73
  encoder = LabelEncoder()
74
  y = encoder.fit_transform(df['disease_label'])
75
 
76
- # --- Balance the dataset ---
77
  ros = RandomOverSampler(random_state=random_state)
78
  X_resampled, y_resampled = ros.fit_resample(X, y)
79
 
80
- # --- Scale features ---
81
  scaler = StandardScaler()
82
  X_scaled = scaler.fit_transform(X_resampled)
83
 
84
- # --- Split data ---
85
  X_train, X_test, y_train, y_test = train_test_split(
86
  X_scaled, y_resampled, test_size=0.2, random_state=random_state)
87
 
88
- # --- Class weights ---
89
  class_weights = compute_class_weight(class_weight='balanced', classes=np.unique(y_train), y=y_train)
90
  class_weights = dict(enumerate(class_weights))
91
 
92
- # --- Build model ---
93
  model = Sequential([
94
  Input(shape=(X_train.shape[1],)),
95
  Dense(128),
@@ -100,59 +100,54 @@ def train_and_evaluate(random_state):
100
  ])
101
  model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
102
 
103
- # --- Train model ---
104
  model.fit(X_train, y_train, epochs=10, batch_size=32, class_weight=class_weights, verbose=0)
105
 
106
- # --- Evaluate model ---
107
  loss, accuracy = model.evaluate(X_test, y_test, verbose=0)
108
  return accuracy
109
 
110
-
111
- def find_best_random_state_with_plot(range_pair):
112
- min_rs, max_rs = int(range_pair[0]), int(range_pair[1])
113
-
114
- if min_rs >= max_rs:
115
- return "Invalid range: min should be less than max.", None
116
-
117
- best_accuracy = 0
118
- best_rs = min_rs
119
  accuracies = []
 
120
 
121
- for rs in range(min_rs, max_rs + 1):
122
  acc = train_and_evaluate(rs)
123
- accuracies.append((rs, acc))
124
- if acc > best_accuracy:
125
- best_accuracy = acc
126
- best_rs = rs
127
-
128
- # Create a matplotlib figure
129
- plt.figure(figsize=(10, 6))
130
- rs_values = [x[0] for x in accuracies]
131
- acc_values = [x[1] for x in accuracies]
132
- plt.plot(rs_values, acc_values, marker='o')
133
- plt.title('Model Accuracy vs Random State')
134
- plt.xlabel('Random State')
135
- plt.ylabel('Accuracy')
136
  plt.grid(True)
137
- plt.tight_layout()
138
-
139
- # Build report string
140
- report = f"Best random_state: {best_rs} with accuracy: {best_accuracy:.2%}\n\nAll accuracies:\n"
141
- for rs, acc in accuracies:
142
- report += f"random_state={rs}: Accuracy={acc:.2%}\n"
143
 
144
- return report, plt
 
 
145
 
 
 
146
 
147
- # Gradio Interface with text and plot output
148
  app = gr.Interface(
149
- fn=find_best_random_state_with_plot,
150
- inputs=gr.Tuple([gr.Number(label="Min Random State", value=50, precision=0),
151
- gr.Number(label="Max Random State", value=60, precision=0)]),
152
- outputs=[gr.Textbox(label="Search Results"), gr.Plot(label="Accuracy vs Random State")],
153
- title="Find Best Random State for Model Training with Accuracy Plot",
154
- description="Input a range (min, max) of random_state values (integers). The model will train and evaluate for each random_state, returning the best one and a plot of accuracy vs random_state.",
155
-
 
 
 
 
156
  theme="soft"
157
  )
158
 
 
10
  from imblearn.over_sampling import RandomOverSampler
11
  import matplotlib.pyplot as plt
12
  import warnings
13
+
14
  warnings.filterwarnings("ignore")
15
 
16
  def train_and_evaluate(random_state):
17
+ # Load dataset
18
  df = pd.read_csv("updated_medical_data.csv")
19
 
20
+ # Disease-specific expected vital sign ranges
21
  disease_vitals = {
22
  "Macular Degeneration": {"hr": (60, 80), "rr": (12, 20), "temp": (97.5, 98.6)},
23
  "Encephalitis": {"hr": (90, 110), "rr": (18, 24), "temp": (100.4, 103)},
 
41
  "Pancreatitis": {"hr": (90, 110), "rr": (16, 24), "temp": (99, 102)}
42
  }
43
 
44
+ # Feature engineering function
45
  def create_vital_flags(row):
46
  disease = row['disease_label']
47
  if disease in disease_vitals:
 
65
  flags_df = df.apply(create_vital_flags, axis=1)
66
  df = pd.concat([df, flags_df], axis=1)
67
 
 
68
  feature_cols = ['heart_rate', 'respiratory_rate', 'temperature', 'symptom_score',
69
  'hr_high_flag', 'hr_low_flag', 'rr_high_flag', 'rr_low_flag',
70
  'temp_high_flag', 'temp_low_flag', 'fever_flag']
 
73
  encoder = LabelEncoder()
74
  y = encoder.fit_transform(df['disease_label'])
75
 
76
+ # Balance dataset with oversampling
77
  ros = RandomOverSampler(random_state=random_state)
78
  X_resampled, y_resampled = ros.fit_resample(X, y)
79
 
80
+ # Scale features
81
  scaler = StandardScaler()
82
  X_scaled = scaler.fit_transform(X_resampled)
83
 
84
+ # Split train-test
85
  X_train, X_test, y_train, y_test = train_test_split(
86
  X_scaled, y_resampled, test_size=0.2, random_state=random_state)
87
 
88
+ # Compute class weights
89
  class_weights = compute_class_weight(class_weight='balanced', classes=np.unique(y_train), y=y_train)
90
  class_weights = dict(enumerate(class_weights))
91
 
92
+ # Build model
93
  model = Sequential([
94
  Input(shape=(X_train.shape[1],)),
95
  Dense(128),
 
100
  ])
101
  model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
102
 
103
+ # Train model
104
  model.fit(X_train, y_train, epochs=10, batch_size=32, class_weight=class_weights, verbose=0)
105
 
106
+ # Evaluate model
107
  loss, accuracy = model.evaluate(X_test, y_test, verbose=0)
108
  return accuracy
109
 
110
+ def search_best_random_state(min_state, max_state):
 
 
 
 
 
 
 
 
111
  accuracies = []
112
+ states = list(range(int(min_state), int(max_state) + 1))
113
 
114
+ for rs in states:
115
  acc = train_and_evaluate(rs)
116
+ accuracies.append(acc)
117
+
118
+ best_idx = np.argmax(accuracies)
119
+ best_state = states[best_idx]
120
+ best_acc = accuracies[best_idx]
121
+
122
+ # Plot results
123
+ plt.figure(figsize=(10,5))
124
+ plt.plot(states, accuracies, marker='o', linestyle='-', color='blue')
125
+ plt.title("Accuracy vs Random State")
126
+ plt.xlabel("Random State")
127
+ plt.ylabel("Accuracy")
 
128
  plt.grid(True)
129
+ plt.axvline(x=best_state, color='red', linestyle='--', label=f"Best Random State: {best_state}")
130
+ plt.legend()
 
 
 
 
131
 
132
+ plt.tight_layout()
133
+ plt.savefig("/tmp/accuracy_plot.png")
134
+ plt.close()
135
 
136
+ summary = f"Best Random State: {best_state} with Accuracy: {best_acc:.2%}"
137
+ return summary, "/tmp/accuracy_plot.png"
138
 
 
139
  app = gr.Interface(
140
+ fn=search_best_random_state,
141
+ inputs=[
142
+ gr.Number(label="Min Random State (>=50)", value=50, precision=0),
143
+ gr.Number(label="Max Random State", value=60, precision=0)
144
+ ],
145
+ outputs=[
146
+ gr.Textbox(label="Best Random State Result"),
147
+ gr.Image(label="Accuracy Plot")
148
+ ],
149
+ title="Random State Search for Best Accuracy",
150
+ description="Enter a range (min and max) for random state seeds (min >= 50). The model will train and evaluate for each random state in the range, then show the best performing random state and accuracy with a plot.",
151
  theme="soft"
152
  )
153