File size: 6,965 Bytes
a562d9d
 
 
 
 
dd8cdb5
988a745
 
 
 
 
 
 
 
3d9e875
bab442a
 
 
 
 
 
 
 
 
37401bd
3d9e875
 
 
08b59fb
3d9e875
 
37401bd
3d9e875
 
37401bd
dd8cdb5
8a5bdef
ea42492
399bafe
2052bf2
ab0a89f
 
 
 
dd8cdb5
 
 
8debddb
 
dd8cdb5
 
c317fae
d47c95d
c317fae
35ba659
 
f756bc2
 
c317fae
3ae0d57
 
 
 
 
 
 
 
 
 
 
 
a562d9d
 
 
 
 
 
 
 
 
a9cdfb1
4610943
 
 
 
 
 
 
d2322c7
318b7fb
c64d12f
a562d9d
ed34a12
 
 
a562d9d
 
 
 
 
 
 
 
 
 
 
 
318b7fb
 
776bed5
ea4062c
 
 
318b7fb
 
ea4062c
 
 
 
318b7fb
8a5bdef
0b12140
a562d9d
 
 
7001efb
aa5f48f
7001efb
3220865
7001efb
3220865
72b51a5
 
 
 
126c621
 
72b51a5
7001efb
9c20e70
 
b05a8b1
32c6712
9c20e70
 
 
 
126c621
72b51a5
a562d9d
 
 
 
8a5bdef
a562d9d
78b2f8d
 
66a35a9
 
 
d0fd4bc
 
 
66a35a9
 
 
e659ca5
9eab577
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
import streamlit as st
import pickle
import pandas as pd
import numpy as np

# Page Title with Style
st.markdown(
    f"""
    <div style="text-align: center;">
        <h1 style="color: #800000;">๐Ÿฉธ Sepsis Prediction App</h1>
    </div>
    """,
    unsafe_allow_html=True
)

# Welcome Message with Style (Centered)
st.markdown(
    f"""
    <div style="text-align: center;">
        <p>๐Ÿ‘‹ Welcome to the Sepsis Prediction App!</p>
    </div>
    """,
    unsafe_allow_html=True
)

# Sepsis Information
st.markdown(
    """
    **Sepsis** is a critical medical condition triggered by the body's extreme response to an infection. It can lead to organ failure and, if not detected early, poses a serious threat to life.
    """
)

# Link to WHO Fact Sheet on Sepsis
st.markdown("๐Ÿ”— **Learn more about sepsis from [World Health Organization (WHO)](https://www.who.int/news-room/fact-sheets/detail/sepsis#:~:text=Overview,problems%20are%20at%20higher%20risk.)**")

st.markdown("---")

st.image("https://dinizululawgroup.com/wp-content/uploads/2020/07/news.jpg", width=700)

# Additional Information for Sample Prediction
st.write("๐Ÿ“Š To make a sample prediction, you can refer to the training dataset information available in the sidebar.")
st.write("๐Ÿ’‰ Enter the medical data in the input fields below, then click 'Predict Sepsis', and get the patient's Sepsis status prediction.")


# About Section with Style
st.sidebar.title("โ„น๏ธ About")
st.sidebar.info(
    "This app predicts sepsis onset using machine learning on medical data, aiding timely intervention by healthcare professionals. "
    "It utilizes a model trained on a sepsis dataset."
)

# Load The Train Dataset
train_df = pd.read_csv("Train.csv", index_col=None)

# Training Dataset Information in the sidebar
st.sidebar.markdown("๐Ÿ“Š **Training Dataset Information:**")
st.sidebar.write("The model is trained on a sepsis dataset. Here's an overview of the dataset:")
st.sidebar.write(train_df.head())

# Auto-expand sidebar code
st.markdown(
    """
    <style>
        [data-testid="stSidebar"][aria-expanded="false"] > div:first-child {
            width: 100%;
        }
    </style>
    """,
    unsafe_allow_html=True
)

# Load the model and key components
with open('model_and_key_components.pkl', 'rb') as file:
    loaded_components = pickle.load(file)

loaded_model = loaded_components['model']
loaded_scaler = loaded_components['scaler']

# Data Fields
data_fields = {
    "**PRG**": "**Number of Pregnancies (applicable only to females)**\n   - The total number of pregnancies a female patient has experienced.",
    "**PL**": "**Plasma Glucose Concentration (mg/dL)**\n   - The concentration of glucose in the patient's blood). It provides insights into the patient's blood sugar levels.",
    "**PR**": "**Diastolic Blood Pressure (mm Hg)**\n   - The diastolic blood pressure, representing the pressure in the arteries when the heart is at rest between beats.",
    "**SK**": "**Triceps Skinfold Thickness (mm)**\n   - The thickness of the skinfold on the triceps, measured in millimeters (mm). This measurement is often used to assess body fat percentage.",
    "**TS**": "**2-hour Serum Insulin (mu U/ml)**\n   - The level of insulin in the patient's blood two hours after a meal, measured in micro international units per milliliter (mu U/ml).",
    "**M11**": "**Body Mass Index (BMI) (weight in kg / {(height in m)}^2)**\n   - BMI provides a standardized measure that helps assess the degree of body fat and categorizes individuals into different weight status categories, such as underweight, normal weight, overweight, and obesity.",
    "**BD2**": "**Diabetes pedigree function (mu U/ml)**\n   - The function provides information about the patient's family history of diabetes.",
    "**Age**": "**Age of the Patient (years)**\n   - Age is an essential factor in medical assessments and can influence various health outcomes."
}
# Organize input fields into two columns
col1, col2 = st.columns(2)

# Initialize input_data dictionary
input_data = {}

# Function to preprocess input data
def preprocess_input_data(input_data):
    numerical_cols = ['PRG', 'PL', 'PR', 'SK', 'TS', 'M11', 'BD2', 'Age']
    input_data_scaled = loaded_scaler.transform([list(input_data.values())])
    return pd.DataFrame(input_data_scaled, columns=numerical_cols)

# Function to make predictions
def make_predictions(input_data_scaled_df):
    y_pred = loaded_model.predict(input_data_scaled_df)
    sepsis_mapping = {0: 'Negative', 1: 'Positive'}
    return sepsis_mapping[y_pred[0]]

# Input Data Fields in two columns
with col1:
    input_data["PRG"] = st.slider("PRG: Number of Pregnancies", 0, 20, 0)
    input_data["PL"] = st.number_input("PL: Plasma Glucose Concentration (mg/dL)", value=0.0)
    input_data["PR"] = st.number_input("PR: Diastolic Blood Pressure (mm Hg)", value=0.0)
    input_data["SK"] = st.number_input("SK: Triceps Skinfold Thickness (mm)", value=0.0)

with col2:
    input_data["TS"] = st.number_input("TS: 2-Hour Serum Insulin (mu U/ml)", value=0.0)
    input_data["M11"] = st.number_input("M11: Body Mass Index (BMI)", value=0.0)
    input_data["BD2"] = st.number_input("BD2: Diabetes Pedigree Function (mu U/ml)", value=0.0)
    input_data["Age"] = st.slider("Age: Age of the patient (years)", 0, 100, 0)

# Predict Button with Style
if st.button("๐Ÿ”ฎ Predict Sepsis"):
    try:
        input_data_scaled_df = preprocess_input_data(input_data)
        sepsis_status = make_predictions(input_data_scaled_df)
        
        # Display the sepsis prediction and risk
        if sepsis_status == 'Negative':
            st.success(f"The patient is at **low risk** of developing sepsis. The predicted sepsis status is: **{sepsis_status}**")
        elif sepsis_status == 'Positive':
            st.error(f"**The patient is at **high risk** of developing sepsis. The predicted sepsis status is: **{sepsis_status}**")

        # Add the sepsis prediction to the input DataFrame
        input_data['Sepsis'] = sepsis_status

        # Convert the input data to a pandas DataFrame
        input_df = pd.DataFrame([input_data])

        # Display the input DataFrame
        st.markdown(
            f"""
            <div style="text-align: center; font-size: 18px; font-weight: bold;">
                <p>Input Data with Sepsis Prediction</p>
            </div>
            """,
            unsafe_allow_html=True
        )
        st.table(input_df)

    except Exception as e:
        st.error(f"An error occurred: {e}")

# Display Data Fields and Descriptions
st.sidebar.title("๐Ÿ” Data Fields")
for field, description in data_fields.items():
    st.sidebar.markdown(f"{field}: {description}")

# Copyright statement at the bottom
st.markdown(
    """
    <div style="text-align:center">
        Developed by <a href="https://www.linkedin.com/in/rasmo-/" style="font-style:italic">Rasmo Wanyama</a>.
    </div>
    """,
    unsafe_allow_html=True
)

st.stop()