Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

main_dashboard.py 8.2 KB

You have to be logged in to leave a comment. Sign In
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
170
171
172
173
  1. import streamlit as st
  2. import pandas as pd
  3. import joblib
  4. import plotly.express as px
  5. from pathlib import Path
  6. import matplotlib.image as mpimg
  7. # Importar el adaptador de preprocess
  8. from preprocess_adapter import preprocess_single_record
  9. # Configuración inicial
  10. st.set_page_config(page_title="Intelligent Credit Scoring Pipeline", layout="wide")
  11. BASE_DIR = Path("G:/MLOps Proyecto End_to_End/IntelligentCreditScoringPipeline")
  12. # Título y descripción
  13. st.title("Intelligent Credit Scoring Pipeline Dashboard 🎉")
  14. st.markdown("¡Explora los resultados del modelo de scoring crediticio de Jorge! 🚀 Creado por Jorge, 2025 😄")
  15. # Barra lateral
  16. with st.sidebar:
  17. st.header("Credit Scoring Pipeline")
  18. st.markdown("**Creado por Jorge Luis Garcia**")
  19. if st.button("LinkedIn", use_container_width=True):
  20. st.markdown('<meta http-equiv="refresh" content="0;url=https://www.linkedin.com/in/jorgedatascientistmlops/" target="_blank">', unsafe_allow_html=True)
  21. st.markdown("[Dagshub](https://dagshub.com/JorgeDataScientist)", unsafe_allow_html=True)
  22. st.markdown("[Sitio Web](https://jorgedatascientist.github.io/portafolio/)", unsafe_allow_html=True)
  23. st.markdown("[Docker Hub](https://hub.docker.com/u/jorgedatascientist)", unsafe_allow_html=True)
  24. st.markdown("**Email**: jorgeluisdatascientist@gmail.com")
  25. # Pestañas
  26. tab1, tab2, tab3, tab4, tab5 = st.tabs(["📊 Métricas", "📈 Gráficos", "🗃️ Dataset", "🔍 Informe", "🧮 Predicciones"])
  27. # Pestaña 1: Métricas
  28. with tab1:
  29. st.subheader("Métricas del Modelo (Model_1)")
  30. metrics_path = BASE_DIR / "metrics/model_1/metrics.csv"
  31. if metrics_path.exists():
  32. metrics = pd.read_csv(metrics_path)
  33. st.write("Métricas del modelo:")
  34. st.dataframe(metrics)
  35. numeric_cols = metrics.select_dtypes(include=['float64', 'int64']).columns
  36. if not numeric_cols.empty:
  37. metrics_numeric = metrics[numeric_cols].iloc[0]
  38. fig = px.bar(
  39. x=numeric_cols,
  40. y=metrics_numeric,
  41. title="Comparación de Métricas",
  42. labels={"x": "Métrica", "y": "Valor"},
  43. )
  44. st.plotly_chart(fig)
  45. else:
  46. st.warning("No se encontraron columnas numéricas en metrics.csv para graficar.")
  47. st.markdown("Estas métricas muestran el rendimiento del RandomForestClassifier entrenado en train.csv.")
  48. else:
  49. st.error("No se encontró metrics.csv en metrics/model_1/")
  50. # Pestaña 2: Gráficos
  51. with tab2:
  52. st.subheader("Gráficos de Rendimiento (Model_1)")
  53. graphics_path = BASE_DIR / "graphics/model_1"
  54. for img_name in ["confusion_matrix.png", "metrics_bar.png"]:
  55. img_path = graphics_path / img_name
  56. if img_path.exists():
  57. img = mpimg.imread(img_path)
  58. st.image(img, caption=img_name.replace(".png", "").replace("_", " ").title(), width=675) # 10% menos tamaño
  59. else:
  60. st.error(f"No se encontró {img_name} en graphics/model_1/")
  61. # Pestaña 3: Dataset
  62. with tab3:
  63. st.subheader("Exploración de train.csv")
  64. data_path = BASE_DIR / "data/raw/train.csv"
  65. if data_path.exists():
  66. df = pd.read_csv(data_path)
  67. st.write("Dataset completo:")
  68. st.dataframe(df)
  69. else:
  70. st.error("No se encontró train.csv en data/raw/")
  71. # Pestaña 4: Informe
  72. with tab4:
  73. st.subheader("Reporte de Análisis")
  74. informe_path = BASE_DIR / "informe/model_1/informe.html"
  75. if informe_path.exists():
  76. with open(informe_path, "r", encoding="utf-8") as f:
  77. html_content = f.read()
  78. st.components.v1.html(html_content, height=800, scrolling=True) # Más largo
  79. else:
  80. st.error("No se encontró informe.html en informe/model_1/")
  81. # Pestaña 5: Predicciones
  82. with tab5:
  83. st.subheader("Hacer Predicciones con Model_1")
  84. model_path = BASE_DIR / "models/model_1/rf_model.pkl"
  85. if not model_path.exists():
  86. st.error("No se encontró rf_model.pkl en models/model_1/")
  87. st.stop()
  88. st.markdown("Ingresa los datos del cliente:")
  89. with st.form("prediction_form"):
  90. col1, col2 = st.columns(2)
  91. with col1:
  92. age = st.number_input("Edad", min_value=18, max_value=100, value=30, step=1, help="Edad del cliente")
  93. monthly_salary = st.number_input("Salario Mensual en Mano", min_value=0.0, value=5000.0, step=100.0, help="Salario neto mensual")
  94. num_credit_cards = st.number_input("Número de Tarjetas de Crédito", min_value=0, value=3, step=1)
  95. interest_rate = st.number_input("Tasa de Interés (%)", min_value=0.0, value=5.0, step=0.1)
  96. outstanding_debt = st.number_input("Deuda Pendiente", min_value=0.0, value=2000.0, step=100.0)
  97. num_bank_accounts = st.number_input("Número de Cuentas Bancarias", min_value=0, value=2, step=1)
  98. num_of_loan = st.number_input("Número de Préstamos", min_value=0, value=1, step=1)
  99. with col2:
  100. delay_from_due_date = st.number_input("Días de Retraso desde la Fecha de Vencimiento", min_value=0, value=0, step=1)
  101. num_delayed_payments = st.number_input("Número de Pagos Retrasados", min_value=0, value=0, step=1)
  102. credit_history_age = st.number_input("Edad del Historial Crediticio (en meses)", min_value=0.0, value=24.0, step=1.0)
  103. total_emi_per_month = st.number_input("Total de Cuotas Mensuales", min_value=0.0, value=500.0, step=10.0)
  104. monthly_balance = st.number_input("Saldo Mensual", min_value=0.0, value=3000.0, step=100.0)
  105. amount_invested_monthly = st.number_input("Cantidad Invertida Mensualmente", min_value=0.0, value=100.0, step=10.0)
  106. occupation = st.selectbox(
  107. "Ocupación",
  108. ["Engineer", "Developer", "Doctor", "Entrepreneur", "Journalist", "Lawyer", "Manager", "Mechanic", "Media_Manager", "Musician", "Scientist", "Teacher", "Writer", "Architect"],
  109. index=0,
  110. )
  111. payment_behaviour = st.selectbox(
  112. "Comportamiento de Pago",
  113. [
  114. "High_spent_Large_value_payments",
  115. "High_spent_Medium_value_payments",
  116. "High_spent_Small_value_payments",
  117. "Low_spent_Large_value_payments",
  118. "Low_spent_Medium_value_payments",
  119. "Low_spent_Small_value_payments",
  120. ],
  121. index=0,
  122. )
  123. credit_mix = st.selectbox("Mezcla Crediticia", ["Good", "Standard", "Bad"], index=0)
  124. payment_of_min_amount = st.selectbox("Pago del Monto Mínimo", ["Yes", "No"], index=0)
  125. submitted = st.form_submit_button("Predecir")
  126. if submitted:
  127. input_data = pd.DataFrame(
  128. {
  129. "Age": [age],
  130. "Monthly_Inhand_Salary": [monthly_salary],
  131. "Num_Credit_Card": [num_credit_cards],
  132. "Interest_Rate": [interest_rate],
  133. "Outstanding_Debt": [outstanding_debt],
  134. "Delay_from_due_date": [delay_from_due_date],
  135. "Num_of_Delayed_Payment": [num_delayed_payments],
  136. "Credit_History_Age": [credit_history_age],
  137. "Total_EMI_per_month": [total_emi_per_month],
  138. "Monthly_Balance": [monthly_balance],
  139. "Amount_invested_monthly": [amount_invested_monthly],
  140. "Occupation": [occupation],
  141. "Payment_Behaviour": [payment_behaviour],
  142. "Credit_Mix": [credit_mix],
  143. "Payment_of_Min_Amount": [payment_of_min_amount],
  144. "Num_Bank_Accounts": [num_bank_accounts],
  145. "Num_of_Loan": [num_of_loan],
  146. }
  147. )
  148. try:
  149. processed_data = preprocess_single_record(input_data)
  150. model = joblib.load(model_path)
  151. prediction = model.predict(processed_data)[0]
  152. if prediction == "Good":
  153. st.success(f"Predicción: **Good** 🎉")
  154. elif prediction == "Poor":
  155. st.error(f"Predicción: **Poor** 😟")
  156. else:
  157. st.warning(f"Predicción: **Standard** ⚖️")
  158. except Exception as e:
  159. st.error(f"Error en la predicción: {e}")
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...