N566616's picture
Update app.py
5ad7413 verified
Raw History Blame Contribute Delete
6.43 kB
import numpy as np
import pandas as pd
import gradio as gr
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, LeakyReLU, Input
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, LabelEncoder
from sklearn.utils.class_weight import compute_class_weight
from imblearn.over_sampling import RandomOverSampler
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings("ignore")
def train_and_evaluate(random_state):
# Load dataset
df = pd.read_csv("updated_medical_data.csv")
# Disease-specific expected vital sign ranges
disease_vitals = {
"Macular Degeneration": {"hr": (60, 80), "rr": (12, 20), "temp": (97.5, 98.6)},
"Encephalitis": {"hr": (90, 110), "rr": (18, 24), "temp": (100.4, 103)},
"Prostate Cancer": {"hr": (60, 80), "rr": (12, 18), "temp": (97.5, 99)},
"Malaria": {"hr": (90, 120), "rr": (20, 30), "temp": (100.4, 104)},
"Lymphoma": {"hr": (80, 100), "rr": (16, 22), "temp": (98.6, 100.4)},
"Pneumonia": {"hr": (90, 110), "rr": (20, 30), "temp": (100.4, 103)},
"Tuberculosis": {"hr": (80, 100), "rr": (20, 28), "temp": (99, 101)},
"Asthma": {"hr": (80, 100), "rr": (18, 30), "temp": (97.5, 99)},
"Chronic Bronchitis": {"hr": (70, 90), "rr": (16, 24), "temp": (97.5, 99.5)},
"COPD": {"hr": (80, 100), "rr": (18, 28), "temp": (97.5, 99.5)},
"Rubella": {"hr": (70, 90), "rr": (14, 20), "temp": (99, 101)},
"Multiple Sclerosis": {"hr": (60, 80), "rr": (12, 18), "temp": (97.5, 99)},
"Plague": {"hr": (100, 130), "rr": (20, 30), "temp": (101, 104)},
"Ebola": {"hr": (110, 140), "rr": (22, 32), "temp": (101, 105)},
"Rheumatoid Arthritis": {"hr": (70, 90), "rr": (14, 20), "temp": (98, 100)},
"Obesity": {"hr": (70, 90), "rr": (14, 20), "temp": (97.5, 99)},
"Metabolic Syndrome": {"hr": (70, 90), "rr": (14, 20), "temp": (97.5, 99)},
"Cataracts": {"hr": (60, 80), "rr": (12, 18), "temp": (97.5, 98.6)},
"Tonsillitis": {"hr": (80, 100), "rr": (16, 24), "temp": (99, 101)},
"Pancreatitis": {"hr": (90, 110), "rr": (16, 24), "temp": (99, 102)}
}
# Feature engineering function
def create_vital_flags(row):
disease = row['disease_label']
if disease in disease_vitals:
hr_low, hr_high = disease_vitals[disease]['hr']
rr_low, rr_high = disease_vitals[disease]['rr']
temp_low, temp_high = disease_vitals[disease]['temp']
else:
hr_low, hr_high = (60, 100)
rr_low, rr_high = (12, 20)
temp_low, temp_high = (97.5, 99)
return pd.Series({
'hr_high_flag': int(row['heart_rate'] > hr_high),
'hr_low_flag': int(row['heart_rate'] < hr_low),
'rr_high_flag': int(row['respiratory_rate'] > rr_high),
'rr_low_flag': int(row['respiratory_rate'] < rr_low),
'temp_high_flag': int(row['temperature'] > temp_high),
'temp_low_flag': int(row['temperature'] < temp_low),
'fever_flag': int(row['temperature'] >= 100.4)
})
flags_df = df.apply(create_vital_flags, axis=1)
df = pd.concat([df, flags_df], axis=1)
feature_cols = ['heart_rate', 'respiratory_rate', 'temperature', 'symptom_score',
'hr_high_flag', 'hr_low_flag', 'rr_high_flag', 'rr_low_flag',
'temp_high_flag', 'temp_low_flag', 'fever_flag']
X = df[feature_cols].values
encoder = LabelEncoder()
y = encoder.fit_transform(df['disease_label'])
# Balance dataset with oversampling
ros = RandomOverSampler(random_state=random_state)
X_resampled, y_resampled = ros.fit_resample(X, y)
# Scale features
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X_resampled)
# Split train-test
X_train, X_test, y_train, y_test = train_test_split(
X_scaled, y_resampled, test_size=0.2, random_state=random_state)
# Compute class weights
class_weights = compute_class_weight(class_weight='balanced', classes=np.unique(y_train), y=y_train)
class_weights = dict(enumerate(class_weights))
# Build model
model = Sequential([
Input(shape=(X_train.shape[1],)),
Dense(128),
LeakyReLU(),
Dense(64),
LeakyReLU(),
Dense(len(np.unique(y_train)), activation='softmax')
])
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
# Train model
model.fit(X_train, y_train, epochs=10, batch_size=32, class_weight=class_weights, verbose=0)
# Evaluate model
loss, accuracy = model.evaluate(X_test, y_test, verbose=0)
return accuracy
def search_best_random_state(min_state, max_state):
accuracies = []
states = list(range(int(min_state), int(max_state) + 1))
for rs in states:
acc = train_and_evaluate(rs)
accuracies.append(acc)
best_idx = np.argmax(accuracies)
best_state = states[best_idx]
best_acc = accuracies[best_idx]
# Plot results
plt.figure(figsize=(10,5))
plt.plot(states, accuracies, marker='o', linestyle='-', color='blue')
plt.title("Accuracy vs Random State")
plt.xlabel("Random State")
plt.ylabel("Accuracy")
plt.grid(True)
plt.axvline(x=best_state, color='red', linestyle='--', label=f"Best Random State: {best_state}")
plt.legend()
plt.tight_layout()
plt.savefig("/tmp/accuracy_plot.png")
plt.close()
summary = f"Best Random State: {best_state} with Accuracy: {best_acc:.2%}"
return summary, "/tmp/accuracy_plot.png"
app = gr.Interface(
fn=search_best_random_state,
inputs=[
gr.Number(label="Min Random State (>=1)", value=1, precision=0),
gr.Number(label="Max Random State", value=60, precision=0)
],
outputs=[
gr.Textbox(label="Best Random State Result"),
gr.Image(label="Accuracy Plot")
],
title="Random State Search for Best Accuracy",
description="Enter a range (min and max) for random state seeds (min >= 1). 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. This goes hand-in-hand with The Virtual Stethoscope.",
theme="soft"
)
if __name__ == "__main__":
app.launch()