CoolFace
Apppublic

rasmodev/Sepsis_Prediction_App_Streamlit

sourceHugging Facemitupdated 2y agoView on Hugging Face
0likes
app.py169 linesDownload Raw Back to root
1import streamlit as st2import pickle3import pandas as pd4import numpy as np5 6# Page Title with Style7st.markdown(8    f"""9    <div style="text-align: center;">10        <h1 style="color: #800000;">๐Ÿฉธ Sepsis Prediction App</h1>11    </div>12    """,13    unsafe_allow_html=True14)15 16# Welcome Message with Style (Centered)17st.markdown(18    f"""19    <div style="text-align: center;">20        <p>๐Ÿ‘‹ Welcome to the Sepsis Prediction App!</p>21    </div>22    """,23    unsafe_allow_html=True24)25 26# Sepsis Information27st.markdown(28    """29    **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.30    """31)32 33# Link to WHO Fact Sheet on Sepsis34st.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.)**")35 36st.markdown("---")37 38st.image("https://dinizululawgroup.com/wp-content/uploads/2020/07/news.jpg", width=700)39 40# Additional Information for Sample Prediction41st.write("๐Ÿ“Š To make a sample prediction, you can refer to the training dataset information available in the sidebar.")42st.write("๐Ÿ’‰ Enter the medical data in the input fields below, then click 'Predict Sepsis', and get the patient's Sepsis status prediction.")43 44 45# About Section with Style46st.sidebar.title("โ„น๏ธ About")47st.sidebar.info(48    "This app predicts sepsis onset using machine learning on medical data, aiding timely intervention by healthcare professionals. "49    "It utilizes a model trained on a sepsis dataset."50)51 52# Load The Train Dataset53train_df = pd.read_csv("Train.csv", index_col=None)54 55# Training Dataset Information in the sidebar56st.sidebar.markdown("๐Ÿ“Š **Training Dataset Information:**")57st.sidebar.write("The model is trained on a sepsis dataset. Here's an overview of the dataset:")58st.sidebar.write(train_df.head())59 60# Auto-expand sidebar code61st.markdown(62    """63    <style>64        [data-testid="stSidebar"][aria-expanded="false"] > div:first-child {65            width: 100%;66        }67    </style>68    """,69    unsafe_allow_html=True70)71 72# Load the model and key components73with open('model_and_key_components.pkl', 'rb') as file:74    loaded_components = pickle.load(file)75 76loaded_model = loaded_components['model']77loaded_scaler = loaded_components['scaler']78 79# Data Fields80data_fields = {81    "**PRG**": "**Number of Pregnancies (applicable only to females)**\n   - The total number of pregnancies a female patient has experienced.",82    "**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.",83    "**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.",84    "**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.",85    "**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).",86    "**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.",87    "**BD2**": "**Diabetes pedigree function (mu U/ml)**\n   - The function provides information about the patient's family history of diabetes.",88    "**Age**": "**Age of the Patient (years)**\n   - Age is an essential factor in medical assessments and can influence various health outcomes."89}90# Organize input fields into two columns91col1, col2 = st.columns(2)92 93# Initialize input_data dictionary94input_data = {}95 96# Function to preprocess input data97def preprocess_input_data(input_data):98    numerical_cols = ['PRG', 'PL', 'PR', 'SK', 'TS', 'M11', 'BD2', 'Age']99    input_data_scaled = loaded_scaler.transform([list(input_data.values())])100    return pd.DataFrame(input_data_scaled, columns=numerical_cols)101 102# Function to make predictions103def make_predictions(input_data_scaled_df):104    y_pred = loaded_model.predict(input_data_scaled_df)105    sepsis_mapping = {0: 'Negative', 1: 'Positive'}106    return sepsis_mapping[y_pred[0]]107 108# Input Data Fields in two columns109with col1:110    input_data["PRG"] = st.slider("PRG: Number of Pregnancies", 0, 20, 0)111    input_data["PL"] = st.number_input("PL: Plasma Glucose Concentration (mg/dL)", value=0.0)112    input_data["PR"] = st.number_input("PR: Diastolic Blood Pressure (mm Hg)", value=0.0)113    input_data["SK"] = st.number_input("SK: Triceps Skinfold Thickness (mm)", value=0.0)114 115with col2:116    input_data["TS"] = st.number_input("TS: 2-Hour Serum Insulin (mu U/ml)", value=0.0)117    input_data["M11"] = st.number_input("M11: Body Mass Index (BMI)", value=0.0)118    input_data["BD2"] = st.number_input("BD2: Diabetes Pedigree Function (mu U/ml)", value=0.0)119    input_data["Age"] = st.slider("Age: Age of the patient (years)", 0, 100, 0)120 121# Predict Button with Style122if st.button("๐Ÿ”ฎ Predict Sepsis"):123    try:124        input_data_scaled_df = preprocess_input_data(input_data)125        sepsis_status = make_predictions(input_data_scaled_df)126        127        # Display the sepsis prediction and risk128        if sepsis_status == 'Negative':129            st.success(f"The patient is at **low risk** of developing sepsis. The predicted sepsis status is: **{sepsis_status}**")130        elif sepsis_status == 'Positive':131            st.error(f"**The patient is at **high risk** of developing sepsis. The predicted sepsis status is: **{sepsis_status}**")132 133        # Add the sepsis prediction to the input DataFrame134        input_data['Sepsis'] = sepsis_status135 136        # Convert the input data to a pandas DataFrame137        input_df = pd.DataFrame([input_data])138 139        # Display the input DataFrame140        st.markdown(141            f"""142            <div style="text-align: center; font-size: 18px; font-weight: bold;">143                <p>Input Data with Sepsis Prediction</p>144            </div>145            """,146            unsafe_allow_html=True147        )148        st.table(input_df)149 150    except Exception as e:151        st.error(f"An error occurred: {e}")152 153# Display Data Fields and Descriptions154st.sidebar.title("๐Ÿ” Data Fields")155for field, description in data_fields.items():156    st.sidebar.markdown(f"{field}: {description}")157 158# Copyright statement at the bottom159st.markdown(160    """161    <div style="text-align:center">162        Developed by <a href="https://www.linkedin.com/in/rasmo-/" style="font-style:italic">Rasmo Wanyama</a>.163    </div>164    """,165    unsafe_allow_html=True166)167 168st.stop()169