import gradio as gr import numpy as np from sklearn.preprocessing import StandardScaler import joblib # Load the trained model model = joblib.load('model.pkl') # Define the function to preprocess user inputs def preprocess_input(age, sex, cp_type, resting_bp, cholesterol, fasting_bs, ecg, max_hr, exercise_angina, oldpeak, st_slope): # Convert categorical features to one-hot encoding sex_mapping = {'F': [0, 1], 'M': [1, 0]} sex_encoded = sex_mapping.get(sex, [0, 0]) cp_mapping = {'ASY': [1, 0, 0, 0], 'ATA': [0, 1, 0, 0], 'NAP': [0, 0, 1, 0], 'TA': [0, 0, 0, 1]} cp_encoded = cp_mapping.get(cp_type, [0, 0, 0, 0]) ecg_mapping = {'Normal': [1, 0, 0], 'ST': [0, 1, 0], 'LVH': [0, 0, 1]} ecg_encoded = ecg_mapping.get(ecg, [0, 0, 0]) # Normalize numerical features numerical_features = [age, resting_bp, cholesterol, max_hr, oldpeak] numerical_features = np.array(numerical_features).reshape(1, -1) scaler = StandardScaler() numerical_features_scaled = scaler.fit_transform(numerical_features) # Combine all features processed_input = np.concatenate([numerical_features_scaled, [fasting_bs], sex_encoded, cp_encoded, ecg_encoded, [exercise_angina], [st_slope]], axis=1) return processed_input # Define the function to make predictions def predict_heart_disease(age, sex, cp_type, resting_bp, cholesterol, fasting_bs, ecg, max_hr, exercise_angina, oldpeak, st_slope): processed_input = preprocess_input(age, sex, cp_type, resting_bp, cholesterol, fasting_bs, ecg, max_hr, exercise_angina, oldpeak, st_slope) prediction = model.predict(processed_input)[0] return "Heart Disease Likely" if prediction == 1 else "No Heart Disease" # Create Gradio interface inputs = [ gr.Interface.Slider(0, 100, default=50, label="Age"), gr.Interface.Radio(['F', 'M'], label="Sex"), gr.Interface.Dropdown(['TA', 'ATA', 'NAP', 'ASY'], label="Chest Pain Type"), gr.Interface.Slider(80, 200, default=120, label="Resting Blood Pressure"), gr.Interface.Slider(100, 600, default=200, label="Cholesterol"), gr.Interface.Checkbox(label="Fasting Blood Sugar > 120 mg/dl"), gr.Interface.Dropdown(['Normal', 'ST', 'LVH'], label="Resting ECG"), gr.Interface.Slider(60, 202, default=100, label="Maximum Heart Rate Achieved"), gr.Interface.Radio(['Y', 'N'], label="Exercise-induced Angina"), gr.Interface.Slider(0, 10, default=5, label="Oldpeak"), gr.Interface.Dropdown(['Up', 'Flat', 'Down'], label="ST Slope") ] output = gr.outputs.Textbox(label="Heart Disease Prediction") gr.Interface(predict_heart_disease, inputs, output, title="Heart Disease Prediction", description="Enter patient information to predict likelihood of heart disease.").launch()