File size: 2,590 Bytes
e84179b
 
 
 
 
 
2e3fa3c
e84179b
 
 
 
 
 
 
2e3fa3c
 
 
 
 
 
 
e84179b
 
 
2e3fa3c
e84179b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import gradio as gr
import joblib
import pandas as pd
import numpy as np

# Load your dataset here
file_path_gr = 'heart.dat'
df = pd.read_csv(file_path_gr, header=None, sep='\s+')

# Define the X variable with the feature columns
X = df.drop(df.columns[-1], axis=1)

# Load the saved models
best_models = [
    ("Logistic Regression", joblib.load('Logistic Regression_best_model.pkl')),
    ("Support Vector Machine", joblib.load('Support Vector Machine_best_model.pkl')),
    ("Decision Trees", joblib.load('Decision Trees_best_model.pkl')),
    ("Random Forests", joblib.load('Random Forests_best_model.pkl')),
    ("MLPClassifier", joblib.load('MLPClassifier_best_model.pkl')),
    ("K-Nearest Neighbors", joblib.load('K-Nearest Neighbors_best_model.pkl')),
    ("Linear Discriminant Analysis",joblib.load('Linear Discriminant Analysis_best_model.pkl'))
]

# Load the saved scaler
scaler = joblib.load('scaler.pkl')

attribute_names = [
    "age", "sex", "chest pain type", "resting blood pressure",
    "serum cholesterol", "fasting blood sugar > 120 mg/dl",
    "resting ECG results", "maximum heart rate achieved",
    "exercise induced angina", "oldpeak", "slope of peak exercise ST segment",
    "number of major vessels", "thal"
]

def predict(*args):
    user_features = list(args[:-1])
    model_name = args[-1]
    model = dict(best_models)[model_name]
    input_data = np.array(user_features).reshape(1, -1)
    input_data_scaled = scaler.transform(input_data)
    probs = model.predict_proba(input_data_scaled)
    return {f"Absence of heart disease" if i == 0 else "Presence of heart disease": p for i, p in enumerate(probs[0])}

# List of model names for the dropdown menu
model_names = [name for name, _ in best_models]

# Define inputs
user_features = [gr.inputs.Number(label=col_name) for col_name in attribute_names]
model_name = gr.inputs.Dropdown(choices=model_names, label="Model")

# Define output
output = gr.outputs.Label(num_top_classes=len(np.unique(df[df.columns[-1]])), label="Predicted Class Probabilities")

# Define examples
examples = [
    [70.0, 1.0, 4.0, 130.0, 322.0, 0.0, 2.0, 109.0, 0.0, 2.4, 2.0, 3.0, 3.0, "Logistic Regression"],
    [67.0, 0.0, 3.0, 115.0, 564.0, 0.0, 2.0, 160.0, 0.0, 1.6, 2.0, 0.0, 7.0, "Logistic Regression"]
]

# Create the Gradio interface
iface = gr.Interface(
    fn=predict,
    inputs=user_features + [model_name],
    outputs=output,
    title="Machine Learning Model",
    description="Select a model and enter user features to predict class probabilities.",
    examples=examples
).launch(debug=True)

iface.launch()