Pre_Desease / app.py
thanhcong2001's picture
Update app.py
9ce2566 verified
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder,StandardScaler
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras import Input
from sklearn.metrics import classification_report
from tensorflow.keras.callbacks import EarlyStopping
import keras_tuner as kt
df = pd.read_csv('Disease_symptom_and_patient_profile_dataset.csv',dtype={'Outcome Variable':str})
df['Outcome Variable'] = df['Outcome Variable'].map({'Positive':1,'Negative':0})
num_features = df.select_dtypes(include=['int64']).columns.drop('Outcome Variable').to_list()
cat_features = df.select_dtypes(include=['object']).columns.to_list()
preprocess = ColumnTransformer(transformers=[
('num',StandardScaler(),num_features),
('cat',OneHotEncoder(handle_unknown='ignore',drop='first'),cat_features)
])
from sklearn.model_selection import train_test_split
x= df.drop(columns=['Outcome Variable'])
y= df['Outcome Variable']
x_train,x_test,y_train,y_test = train_test_split(x,y,test_size=0.3,random_state= 42)
x_train_scaled = preprocess.fit_transform(x_train)
x_test_scaled = preprocess.transform(x_test)
def build_model(hp):
model = Sequential([
Input(shape=(x_test_scaled.shape[1],)),
Dense(units=hp.Int('u1',32,256,step=32),activation='relu'),
Dense(units=hp.Int('u2',16,128,step=16),activation='relu'),
Dense(units=hp.Int('u3',8,64,step=8),activation='relu'),
Dense(1,activation='sigmoid')])
model.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])
return model
tuner = kt.RandomSearch(build_model,objective='val_loss',max_trials=20)
early_stop = EarlyStopping(monitor='val_loss',patience=20,restore_best_weights=True)
tuner.search(x_train_scaled,y_train,epochs=400,batch_size=32,callbacks=[early_stop],validation_split=0.4,verbose=1)
best_model = tuner.get_best_models(1)[0]
y_pred = (best_model.predict(x_test_scaled).flatten()>=0.5).astype(int)
for pre,ac in zip(y_pred[:5],y_test[:5]):
print(f'Predict: {pre} - Actual: {ac}')
print(f'Report: {classification_report(y_test,y_pred)}')
def pre_desease(Disease,Fever,Cough,Fatigue,Breathing,Age,Gender,Blood,Cholesterol):
cols = x.columns
vals = [Disease,Fever,Cough,Fatigue,Breathing,Age,Gender,Blood,Cholesterol]
user = pd.DataFrame([dict(zip(cols,vals))])
prediction = best_model.predict(preprocess.transform(user)).item()
decision = 'POSITIVE' if prediction >=0.5 else 'NEGATIVE'
return f'Result: {decision}'
import gradio as gr
inputs = [
gr.Text(label='Disease'),
gr.Radio(choices=['Yes', 'No'],label='Fever'),
gr.Radio(choices=['Yes', 'No'],label='Cough'),
gr.Radio(choices=['Yes', 'No'],label='Fatigue'),
gr.Radio(choices=['Yes', 'No'],label='Difficulty Breathing'),
gr.Number(label='Age'),
gr.Radio(choices=['Female', 'Male'],label='Gender'),
gr.Radio(choices=['Low', 'Normal', 'High'],label='Blood Pressure'),
gr.Radio(choices=['Normal', 'Low', 'High'],label='Cholesterol Level'),
]
demo = gr.Interface(fn=pre_desease,inputs=inputs,outputs='text',title='Predict Desease')
demo.launch()