File size: 5,446 Bytes
fcd727d 8298808 9bbc9ca 8298808 9bbc9ca 8298808 fcd727d 726f622 9bbc9ca 2bcc983 726f622 2bcc983 726f622 2bcc983 fcd727d 8298808 2bcc983 998c62e 9bbc9ca 8298808 fcd727d 8298808 726f622 9bbc9ca fcd727d 8298808 9bbc9ca fcd727d 8298808 9bbc9ca 8298808 fcd727d 8298808 fcd727d 9bbc9ca 8298808 fcd727d 726f622 8298808 9bbc9ca 726f622 9bbc9ca 726f622 9bbc9ca 8298808 9bbc9ca 8298808 9bbc9ca 8298808 726f622 8298808 9bbc9ca 726f622 9bbc9ca |
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 |
import streamlit as st
import pandas as pd
import joblib
from datetime import datetime
from huggingface_hub import hf_hub_download
st.set_page_config(
page_title="Credit Risk App",
page_icon="πΌ",
layout="centered"
)
# Load model
@st.cache_resource
def load_model():
model_path = hf_hub_download(
repo_id="ZeeshanWattoo/random-forest-credit-model",
filename="random_forest_model1.pkl"
)
return joblib.load(model_path)
model = load_model()
# Category mappings
home_mapping = {"Own": 2, "Mortgage": 1, "Rent": 0}
intent_mapping = {
"education": 0, "home_improvement": 1, "medical": 2,
"personal": 3, "venture": 4
}
default_mapping = {"Yes": 1, "No": 0}
st.markdown("<h1 style='color: #007acc;'>πΌ Credit Risk Prediction App</h1>", unsafe_allow_html=True)
st.markdown("<p style='font-size: 16px;'>π <strong>Enter applicant details to predict the likelihood of loan repayment or default.</strong></p>", unsafe_allow_html=True)
with st.sidebar:
st.markdown(
"<h2 style='color: #ff6347;'>βΉοΈ About This App</h2>"
"<p>This app predicts the risk of default for loan applicants using a trained <strong>Random Forest</strong> model.</p>"
"<p><strong>Created By:</strong> Zeeshan Ahmad Wattoo<br>"
"<strong>Framework:</strong> Streamlit<br>"
"<strong>Deployed on:</strong> Hugging Face π€</p>"
"<a href='https://github.com/ZeeshanWattoo2052/credit-risk-analysis' target='_blank' style='color: #4caf50; text-decoration: none;'>π GitHub Repo</a>",
unsafe_allow_html=True
)
st.header("π Applicant Information")
st.markdown(
"<p style='color: #4caf50; font-weight: bold;'>π‘ Tips: Use the sliders and inputs below to enter applicant details.</p>",
unsafe_allow_html=True
)
# Name input with placeholder and persistent state
if "user_name" not in st.session_state:
st.session_state.user_name = ""
user_name = st.text_input(
"π€ Enter Your Name",
value=st.session_state.user_name,
placeholder="Enter your name"
)
st.session_state.user_name = user_name
# Input form
col1, col2 = st.columns(2)
with col1:
age = st.slider("π Age", 18, 100, 30)
income = st.number_input("π° Annual Income ($)", min_value=0.0, value=50000.0, step=1000.0)
emp_length = st.slider("π Employment Length (years)", 0, 50, 5)
intent = st.selectbox("π¦ Loan Purpose", ["education", "home_improvement", "medical", "personal", "venture"])
with col2:
home = st.radio("π Home Ownership", ["Own", "Mortgage", "Rent"])
amount = st.number_input("π΅ Loan Amount ($)", min_value=0.0, value=10000.0, step=500.0)
rate = st.slider("π Interest Rate (%)", 0.0, 100.0, 10.0, 0.5)
default = st.radio("β οΈ Previous Default", ["Yes", "No"])
cred_length = st.slider("π Credit History Length (years)", 0, 50, 10)
if income == 0:
st.warning("β οΈ Annual income must be greater than 0.")
st.stop()
# Derived feature
percent_income = amount / income
# Input DataFrame
input_df = pd.DataFrame({
"Age": [age],
"Income": [income],
"Home": [home_mapping[home]],
"Emp_length": [emp_length],
"Intent": [intent_mapping[intent]],
"Amount": [amount],
"Rate": [rate],
"Percent_income": [percent_income],
"Default": [default_mapping[default]],
"Cred_length": [cred_length]
})
# Prediction button
if st.button("π Predict Credit Risk"):
prediction = model.predict(input_df)
proba = model.predict_proba(input_df)[0]
if prediction[0] == 0:
# Fully Paid
st.balloons()
st.success(f"π **Congratulations, {user_name or 'Applicant'}!** You are eligible to get the loan. π°")
st.markdown("β
**Prediction:** π’ Fully Paid")
st.metric(label="Loan Risk Score (Default)", value=f"{proba[1]*100:.1f}%")
else:
# Charged Off
st.warning(
f"β οΈ **Sorry, {user_name or 'Applicant'}.** Based on our analysis, there is a high risk of default for this application. "
f"Unfortunately, you are currently **not eligible for the loan**."
)
st.markdown("β **Prediction:** π΄ Charged Off")
st.metric(label="Loan Risk Score (Default)", value=f"{proba[1]*100:.1f}%")
# Visualize progress
st.progress(int(proba[1]*100))
# Probability details
st.subheader("π Prediction Probabilities")
st.write(f"π’ Fully Paid: **{proba[0] * 100:.2f}%**")
st.write(f"π΄ Charged Off: **{proba[1] * 100:.2f}%**")
# Show data preview
st.subheader("π Input Data Overview")
st.dataframe(input_df.style.highlight_max(axis=1))
# Prepare downloadable results
result_df = input_df.copy()
status = "Fully Paid" if prediction[0] == 0 else "Charged Off"
result_df["Predicted Status"] = status
result_df["Fully Paid Probability (%)"] = round(proba[0] * 100, 2)
result_df["Charged Off Probability (%)"] = round(proba[1] * 100, 2)
filename = f"credit_risk_prediction_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv"
st.download_button(
label="πΎ Download Prediction as CSV",
data=result_df.to_csv(index=False),
file_name=filename,
mime="text/csv"
)
# Centered Footer
st.markdown("---")
st.markdown(
"<div style='text-align: center; color: #888;'>"
"Made with β€οΈ by Zeeshan Ahmad Wattoo"
"</div>",
unsafe_allow_html=True
)
|