File size: 3,675 Bytes
88371c3
44f737e
 
 
 
30cdb1d
88371c3
44f737e
fe5bd4e
88371c3
44f737e
0e9fd1f
44f737e
 
 
 
 
88371c3
511f8c0
44f737e
88371c3
44f737e
 
88371c3
44f737e
 
 
 
 
88371c3
44f737e
 
 
 
 
30cdb1d
88371c3
44f737e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88371c3
 
44f737e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
import pandas as pd
import joblib
from datetime import datetime

st.set_page_config(page_title="RANDOM FOREST TEST SPACE (NVS AI)", page_icon="💼", layout="centered")

# Loading model
model = joblib.load("src/random_forest_model1.pkl")

# Category mappings (must match training time)
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.title("RANDOM FOREST TEST SPACE (NVS AI)")
st.markdown("Введите данные заявителя, чтобы предсказать вероятность погашения займа.")

st.header("📝 Информация заявителя")
col1, col2 = st.columns(2)

with col1:
    age = st.number_input("Возраст", min_value=18, max_value=100, value=30)
    income = st.number_input("Годовой доход", min_value=0.0, value=50000.0)
    emp_length = st.number_input("Трудовой стаж (лет)", min_value=0, max_value=50, value=5)
    intent = st.selectbox("Назначение займа",  ["education", "home_improvement", "medical", "personal", "venture"])

with col2:
    home = st.selectbox("Недвижимость", ["Own", "Mortgage", "Rent"])
    amount = st.number_input("Размер займа", min_value=0.0, value=10000.0)
    rate = st.number_input("Процентная ставка (%)", min_value=0.0, max_value=100.0, value=10.0)
    default = st.selectbox("Были ли ранее должником", ["Yes", "No"])
    cred_length = st.number_input("Длина кредитной истории (лет)", min_value=0, max_value=50, value=10)

if income == 0:
    st.warning("Годовой доход должен быть больше, чем 0.")
    st.stop()

# Derived feature
percent_income = amount / income

# Create 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]
})

# Predict and show results
if st.button("🔍 Прогнозировать кредитный риск"):
    prediction = model.predict(input_df)
    proba = model.predict_proba(input_df)[0]

    status = "🟢 Выплатить!" if prediction[0] == 0 else "🔴 Должник!"
    st.success(f"**Прогнозируемый статус кредита:** {status}")

    # Risk metric
    st.metric(label="Риск Score (Дефолт)", value=f"{proba[1]*100:.1f}%")

    # Probabilities
    st.subheader("📊 Вероятности прогнозирования.")
    st.write(f"🟢 Полная выплата: **{proba[0] * 100:.2f}%**")
    st.write(f"🔴 Должник: **{proba[1] * 100:.2f}%**")

    # Prepare downloadable result
    result_df = input_df.copy()
    result_df["Статус предсказания"] = status
    result_df["Вероятность возврата (%)"] = round(proba[0] * 100, 2)
    result_df["Вероятность долга (%)"] = round(proba[1] * 100, 2)

    # Timestamped filename
    filename = f"analyt_risk_predict_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv"
    
    # Download button
    st.download_button(
        label="💾 Загрузить как CSV",
        data=result_df.to_csv(index=False),
        file_name=filename,
        mime="text/csv"
    )

# Footer
st.markdown("---")
st.caption("Minsk 2025 | Created by Kamenev A.I.")