Allisona commited on
Commit
08112b3
·
verified ·
1 Parent(s): 931b9f3

Upload app (1).py

Browse files
Files changed (1) hide show
  1. app (1).py +148 -0
app (1).py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import pickle
3
+ import numpy as np
4
+ import pandas as pd
5
+ import json
6
+
7
+ print("🚀 Cargando modelo UFC Predictor...")
8
+
9
+ # Cargar modelo y preprocesadores
10
+ try:
11
+ with open("ufc_best_model.pkl", "rb") as f:
12
+ model = pickle.load(f)
13
+
14
+ with open("ufc_scaler.pkl", "rb") as f:
15
+ scaler = pickle.load(f)
16
+
17
+ with open("ufc_imputer.pkl", "rb") as f:
18
+ imputer = pickle.load(f)
19
+
20
+ with open("ufc_model_metadata.json", "r") as f:
21
+ metadata = json.load(f)
22
+
23
+ with open("ufc_feature_ranges.json", "r") as f:
24
+ ranges = json.load(f)
25
+
26
+ print("✅ Modelo y archivos cargados correctamente")
27
+ print(f"🏆 Modelo: {metadata['best_model_name']}")
28
+ print(f"📊 Accuracy: {metadata['best_accuracy']:.4f}")
29
+
30
+ except Exception as e:
31
+ print(f"❌ Error cargando archivos: {e}")
32
+ raise e
33
+
34
+ def predict_ufc_fight(
35
+ fighter_1_kd, fighter_1_str, fighter_1_td, fighter_1_sub,
36
+ fighter_2_kd, fighter_2_str, fighter_2_td, fighter_2_sub,
37
+ round_num, weight_class, method_encoded
38
+ ):
39
+ """
40
+ Predice el resultado de una pelea UFC basado en las estadísticas
41
+ """
42
+ try:
43
+ # Calcular diferencias
44
+ kd_diff = fighter_1_kd - fighter_2_kd
45
+ str_diff = fighter_1_str - fighter_2_str
46
+ td_diff = fighter_1_td - fighter_2_td
47
+ sub_diff = fighter_1_sub - fighter_2_sub
48
+
49
+ # Calcular precisiones
50
+ fighter_1_accuracy = fighter_1_str / (fighter_1_str + 10)
51
+ fighter_2_accuracy = fighter_2_str / (fighter_2_str + 10)
52
+
53
+ # Crear array de entrada en el orden CORRECTO
54
+ input_features = [
55
+ kd_diff, str_diff, td_diff, sub_diff, # Diferencias
56
+ fighter_1_kd, fighter_2_kd, # KDs individuales
57
+ fighter_1_str, fighter_2_str, # Golpes
58
+ fighter_1_td, fighter_2_td, # Takedowns
59
+ fighter_1_sub, fighter_2_sub, # Submissions
60
+ fighter_1_accuracy, fighter_2_accuracy, # Precisiones
61
+ round_num, # Round
62
+ method_encoded # Método codificado
63
+ ]
64
+
65
+ # Añadir one-hot encoding para weight_class
66
+ weight_classes = [
67
+ 'weight_class_Bantamweight', 'weight_class_Catch Weight',
68
+ 'weight_class_Featherweight', 'weight_class_Flyweight',
69
+ 'weight_class_Heavyweight', 'weight_class_Light Heavyweight',
70
+ 'weight_class_Lightweight', 'weight_class_Middleweight',
71
+ 'weight_class_Welterweight'
72
+ ]
73
+
74
+ for wc in weight_classes:
75
+ input_features.append(1 if wc == f"weight_class_{weight_class}" else 0)
76
+
77
+ # Convertir a numpy array
78
+ input_array = np.array([input_features])
79
+
80
+ # Aplicar preprocesamiento
81
+ input_imputed = imputer.transform(input_array)
82
+ input_scaled = scaler.transform(input_imputed)
83
+
84
+ # Hacer predicción
85
+ prediction = model.predict(input_scaled)[0]
86
+ probability = model.predict_proba(input_scaled)[0]
87
+
88
+ # Interpretar resultados
89
+ if prediction == 1:
90
+ winner = "Fighter 1"
91
+ confidence = probability[1]
92
+ explanation = f"Fighter 1 tiene {confidence:.1%} de probabilidad de ganar"
93
+ else:
94
+ winner = "Fighter 2"
95
+ confidence = probability[0]
96
+ explanation = f"Fighter 2 tiene {confidence:.1%} de probabilidad de ganar"
97
+
98
+ return {
99
+ "Ganador predicho": winner,
100
+ "Confianza": f"{confidence:.1%}",
101
+ "Probabilidad Fighter 1": f"{probability[1]:.1%}",
102
+ "Probabilidad Fighter 2": f"{probability[0]:.1%}",
103
+ "Analisis": explanation
104
+ }
105
+
106
+ except Exception as e:
107
+ return {"Error": f"Error en predicción: {str(e)}"}
108
+
109
+ # Crear interfaz Gradio
110
+ print("🎨 Creando interfaz Gradio...")
111
+
112
+ # Definir inputs
113
+ inputs = [
114
+ gr.Number(label="Fighter 1 - Knockdowns", value=0, minimum=0, maximum=10),
115
+ gr.Number(label="Fighter 1 - Golpes significativos", value=50, minimum=0, maximum=500),
116
+ gr.Number(label="Fighter 1 - Takedowns", value=1, minimum=0, maximum=20),
117
+ gr.Number(label="Fighter 1 - Intentos de sumisión", value=0, minimum=0, maximum=10),
118
+ gr.Number(label="Fighter 2 - Knockdowns", value=0, minimum=0, maximum=10),
119
+ gr.Number(label="Fighter 2 - Golpes significativos", value=45, minimum=0, maximum=500),
120
+ gr.Number(label="Fighter 2 - Takedowns", value=2, minimum=0, maximum=20),
121
+ gr.Number(label="Fighter 2 - Intentos de sumisión", value=1, minimum=0, maximum=10),
122
+ gr.Slider(1, 5, value=3, step=1, label="Round"),
123
+ gr.Dropdown(
124
+ choices=[
125
+ "Bantamweight", "Catch Weight", "Featherweight", "Flyweight",
126
+ "Heavyweight", "Light Heavyweight", "Lightweight", "Middleweight", "Welterweight"
127
+ ],
128
+ value="Lightweight",
129
+ label="Categoría de Peso"
130
+ ),
131
+ gr.Slider(0, 10, value=5, step=1, label="Método (encoded) - 0-10 scale")
132
+ ]
133
+
134
+ # Crear la aplicación
135
+ demo = gr.Interface(
136
+ fn=predict_ufc_fight,
137
+ inputs=inputs,
138
+ outputs="json",
139
+ title="UFC Fight Predictor",
140
+ description="Predice el resultado de peleas UFC basado en estadísticas de los peleadores. Modelo entrenado con accuracy del 99%",
141
+ examples=[
142
+ [2, 120, 3, 1, 0, 80, 1, 0, 3, "Lightweight", 5],
143
+ [0, 80, 1, 0, 3, 150, 4, 2, 2, "Welterweight", 5]
144
+ ]
145
+ )
146
+
147
+ if __name__ == "__main__":
148
+ demo.launch()