ZeeshanWattoo commited on
Commit
8298808
Β·
verified Β·
1 Parent(s): 01be56f

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +93 -30
src/streamlit_app.py CHANGED
@@ -1,40 +1,103 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
 
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
 
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
 
 
 
15
 
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
 
 
 
 
18
 
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
 
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
 
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
 
 
 
 
 
 
 
31
  })
32
 
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ import pandas as pd
3
+ import joblib
4
+ from datetime import datetime
5
+ from huggingface_hub import hf_hub_download
6
+
7
+ st.set_page_config(page_title="Credit Risk App", page_icon="πŸ’Ό", layout="centered")
8
+
9
+ # βœ… Load model from Hugging Face Hub using huggingface_hub
10
+ @st.cache_resource
11
+ def load_model():
12
+ model_path = hf_hub_download(
13
+ repo_id="ZeeshanWattoo/random-forest-credit-model",
14
+ filename="random_forest_model1.pkl"
15
+ )
16
+ return joblib.load(model_path)
17
+
18
+ model = load_model()
19
+
20
+ # Category mappings
21
+ home_mapping = {"Own": 2, "Mortgage": 1, "Rent": 0}
22
+ intent_mapping = {
23
+ "education": 0, "home_improvement": 1, "medical": 2,
24
+ "personal": 3, "venture": 4
25
+ }
26
+ default_mapping = {"Yes": 1, "No": 0}
27
 
28
+ st.title("πŸ’Ό Credit Risk Prediction App")
29
+ st.markdown("Enter applicant details below to predict the likelihood of loan repayment or default.")
30
 
31
+ st.header("πŸ“ Applicant Information")
32
+ col1, col2 = st.columns(2)
 
33
 
34
+ with col1:
35
+ age = st.number_input("Age", min_value=18, max_value=100, value=30)
36
+ income = st.number_input("Annual Income", min_value=0.0, value=50000.0, step=1000.0)
37
+ emp_length = st.number_input("Employment Length (years)", min_value=0, max_value=50, value=5)
38
+ intent = st.selectbox("Loan Purpose", ["education", "home_improvement", "medical", "personal", "venture"])
39
 
40
+ with col2:
41
+ home = st.selectbox("Home Ownership", ["Own", "Mortgage", "Rent"])
42
+ amount = st.number_input("Loan Amount", min_value=0.0, value=10000.0, step=500.0)
43
+ rate = st.number_input("Interest Rate (%)", min_value=0.0, max_value=100.0, value=10.0, step=0.5)
44
+ default = st.selectbox("Previous Default", ["Yes", "No"])
45
+ cred_length = st.number_input("Credit History Length (years)", min_value=0, max_value=50, value=10)
46
 
47
+ if income == 0:
48
+ st.warning("Annual income must be greater than 0.")
49
+ st.stop()
50
 
51
+ # Derived feature
52
+ percent_income = amount / income
53
 
54
+ # Create input dataframe
55
+ input_df = pd.DataFrame({
56
+ "Age": [age],
57
+ "Income": [income],
58
+ "Home": [home_mapping[home]],
59
+ "Emp_length": [emp_length],
60
+ "Intent": [intent_mapping[intent]],
61
+ "Amount": [amount],
62
+ "Rate": [rate],
63
+ "Percent_income": [percent_income],
64
+ "Default": [default_mapping[default]],
65
+ "Cred_length": [cred_length]
66
  })
67
 
68
+ # Predict and show results
69
+ if st.button("πŸ” Predict Credit Risk"):
70
+ prediction = model.predict(input_df)
71
+ proba = model.predict_proba(input_df)[0]
72
+
73
+ status = "🟒 Fully Paid" if prediction[0] == 0 else "πŸ”΄ Charged Off"
74
+ st.success(f"**Predicted Loan Status:** {status}")
75
+
76
+ # Risk metric
77
+ st.metric(label="Loan Risk Score (Default)", value=f"{proba[1]*100:.1f}%")
78
+
79
+ # Probabilities
80
+ st.subheader("πŸ“Š Prediction Probabilities")
81
+ st.write(f"🟒 Fully Paid: **{proba[0] * 100:.2f}%**")
82
+ st.write(f"πŸ”΄ Charged Off: **{proba[1] * 100:.2f}%**")
83
+
84
+ # Prepare downloadable result
85
+ result_df = input_df.copy()
86
+ result_df["Predicted Status"] = status
87
+ result_df["Fully Paid Probability (%)"] = round(proba[0] * 100, 2)
88
+ result_df["Charged Off Probability (%)"] = round(proba[1] * 100, 2)
89
+
90
+ # Timestamped filename
91
+ filename = f"credit_risk_prediction_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv"
92
+
93
+ # Download button
94
+ st.download_button(
95
+ label="πŸ’Ύ Download Prediction as CSV",
96
+ data=result_df.to_csv(index=False),
97
+ file_name=filename,
98
+ mime="text/csv"
99
+ )
100
+
101
+ # Footer
102
+ st.markdown("---")
103
+ st.caption("Made with ❀️ by Zeeshan Ahmad Wattoo | BS Software Engineering, Semester 6")