juliogu81 commited on
Commit
a513460
·
1 Parent(s): 03733b2

algunas correcciones en el preprocesamiento, hay que usar el _fixed

Browse files
examples_cross_entropy.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from keras.models import Sequential
3
+ from keras.layers import Dense
4
+ from keras.utils import to_categorical
5
+
6
+ print("🔥 EJEMPLOS: Binary vs Categorical Cross-Entropy")
7
+ print("=" * 60)
8
+
9
+ # ================================
10
+ # EJEMPLO 1: BINARY CROSS-ENTROPY
11
+ # ================================
12
+ print("\n1️⃣ BINARY CROSS-ENTROPY (Configuración correcta)")
13
+ print("-" * 50)
14
+
15
+ # Datos binarios simples
16
+ y_binary = np.array([0, 1, 0, 1, 0]) # Etiquetas simples
17
+ print(f"Etiquetas binarias: {y_binary}")
18
+
19
+ # Modelo binario
20
+ model_binary = Sequential([
21
+ Dense(10, activation='relu', input_shape=(5,)),
22
+ Dense(1, activation='sigmoid') # ← 1 neurona con sigmoid
23
+ ])
24
+
25
+ model_binary.compile(
26
+ optimizer='adam',
27
+ loss='binary_crossentropy', # ← Binary loss
28
+ metrics=['accuracy']
29
+ )
30
+
31
+ print("✅ Arquitectura binaria:")
32
+ print(f" • Salida: {model_binary.layers[-1].units} neurona")
33
+ print(f" • Activación: {model_binary.layers[-1].activation.__name__}")
34
+ print(f" • Etiquetas: valores simples [0, 1]")
35
+
36
+ # ================================
37
+ # EJEMPLO 2: CATEGORICAL CROSS-ENTROPY
38
+ # ================================
39
+ print("\n2️⃣ CATEGORICAL CROSS-ENTROPY (Configuración correcta)")
40
+ print("-" * 50)
41
+
42
+ # Convertir a one-hot
43
+ y_categorical = to_categorical(y_binary, num_classes=2)
44
+ print(f"Etiquetas categóricas (one-hot):")
45
+ for i, label in enumerate(y_categorical):
46
+ print(f" {y_binary[i]} → {label}")
47
+
48
+ # Modelo categórico
49
+ model_categorical = Sequential([
50
+ Dense(10, activation='relu', input_shape=(5,)),
51
+ Dense(2, activation='softmax') # ← 2 neuronas con softmax
52
+ ])
53
+
54
+ model_categorical.compile(
55
+ optimizer='adam',
56
+ loss='categorical_crossentropy', # ← Categorical loss
57
+ metrics=['accuracy']
58
+ )
59
+
60
+ print("✅ Arquitectura categórica:")
61
+ print(f" • Salida: {model_categorical.layers[-1].units} neuronas")
62
+ print(f" • Activación: {model_categorical.layers[-1].activation.__name__}")
63
+ print(f" • Etiquetas: one-hot vectors [[1,0], [0,1]]")
64
+
65
+ # ================================
66
+ # EJEMPLO 3: ❌ CONFIGURACIÓN INCORRECTA (tu problema original)
67
+ # ================================
68
+ print("\n❌ CONFIGURACIÓN INCORRECTA (tu problema original)")
69
+ print("-" * 50)
70
+
71
+ print("🚨 PROBLEMA: binary_crossentropy + to_categorical() + 2 neuronas")
72
+ print(" • Loss: binary_crossentropy")
73
+ print(" • Etiquetas: [[1,0], [0,1]] (one-hot)")
74
+ print(" • Salida: 2 neuronas con softmax")
75
+ print(" • RESULTADO: ❌ No puede aprender correctamente")
76
+
77
+ # ================================
78
+ # COMPARACIÓN DE SALIDAS
79
+ # ================================
80
+ print("\n📊 COMPARACIÓN DE SALIDAS")
81
+ print("-" * 50)
82
+
83
+ # Datos dummy para ejemplo
84
+ X_dummy = np.random.random((5, 5))
85
+
86
+ # Predicciones binarias
87
+ pred_binary = model_binary.predict(X_dummy, verbose=0)
88
+ print("Predicciones binarias:")
89
+ for i, pred in enumerate(pred_binary):
90
+ print(f" Muestra {i}: {pred[0]:.4f} (probabilidad clase 1)")
91
+
92
+ # Predicciones categóricas
93
+ pred_categorical = model_categorical.predict(X_dummy, verbose=0)
94
+ print("\nPredicciones categóricas:")
95
+ for i, pred in enumerate(pred_categorical):
96
+ print(f" Muestra {i}: [{pred[0]:.4f}, {pred[1]:.4f}] (prob clase 0, prob clase 1)")
97
+
98
+ # ================================
99
+ # RECOMENDACIONES PARA TU PROYECTO
100
+ # ================================
101
+ print("\n🎯 RECOMENDACIONES PARA TU PROYECTO DE COTORRAS")
102
+ print("-" * 50)
103
+
104
+ print("Tienes 2 opciones correctas:")
105
+ print()
106
+ print("OPCIÓN A - Categorical (RECOMENDADA):")
107
+ print("✅ model.add(Dense(2, activation='softmax'))")
108
+ print("✅ model.compile(loss='categorical_crossentropy')")
109
+ print("✅ y_labels = to_categorical([0,1,0,1])")
110
+ print(" • Más fácil de extender a más clases")
111
+ print(" • Mejor para análisis de confianza")
112
+ print()
113
+ print("OPCIÓN B - Binary:")
114
+ print("✅ model.add(Dense(1, activation='sigmoid'))")
115
+ print("✅ model.compile(loss='binary_crossentropy')")
116
+ print("✅ y_labels = [0,1,0,1] # SIN to_categorical()")
117
+ print(" • Más simple para solo 2 clases")
118
+ print(" • Menos parámetros")
119
+
120
+ print("\n🚀 Para tu caso: Usa OPCIÓN A (categorical) porque ya tienes to_categorical()")
src/data/{processed_features_240x320/features.npy → processed_features_224x224_fixed/x_test.npy} RENAMED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:4f0f2f88134457c6d8c63354bfc8343b1449986178a1d5a9b352a1e90a919ee2
3
- size 2351001728
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:08eef84e6c87b234ee3c7a3df47d0de0f9d24dddd2d6b92de9c2620243c31d16
3
+ size 461217920
src/data/processed_features_224x224_fixed/x_train.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:95dac06126ed9f970fa30d2da49743a73dcd2dcacc1da86f39559f960f59ee69
3
+ size 1074770048
src/data/{processed_features_240x320/labels.npy → processed_features_224x224_fixed/y_test.npy} RENAMED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:806b5650eccffed1041d38a9a63dff31bad6cbe406d00da7bb6a8ae64fd7b08e
3
- size 20536
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d817be612c7b496ceb841e693d282f33b1f39b3ca9b2e14677b83cf986d6b23e
3
+ size 6256
src/data/processed_features_224x224_fixed/y_train.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:968ce25d915ec3be11c0137d0a389c2b9d66a4da377e3a14cefa55e832ab69a5
3
+ size 14408
src/training/parakeets_cnn_training.ipynb CHANGED
The diff for this file is too large to render. See raw diff
 
src/training/parakeets_cnn_training_fixed.ipynb ADDED
@@ -0,0 +1,757 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "raw",
5
+ "metadata": {
6
+ "vscode": {
7
+ "languageId": "raw"
8
+ }
9
+ },
10
+ "source": [
11
+ "# Parakeet CNN Training - VERSIÓN BINARIA OPTIMIZADA\n",
12
+ "\n",
13
+ "## 🎯 **Configuración BINARIA (más eficiente para tu caso)**\n",
14
+ "\n",
15
+ "### Principales correcciones:\n",
16
+ "1. **🔥 Binary Cross-Entropy**: Más eficiente para clasificación binaria (cotorra vs no-cotorra)\n",
17
+ "2. **🚀 1 neurona de salida**: En lugar de 2 (menos parámetros, más rápido)\n",
18
+ "3. **📊 Sin to_categorical()**: Etiquetas directas [0,1] en lugar de [[1,0],[0,1]]\n",
19
+ "4. **⚡ Normalización Min-Max**: Mejor para spectrogramas [0,1]\n",
20
+ "5. **🏗️ Arquitectura optimizada**: BatchNormalization, Dropout\n",
21
+ "\n",
22
+ "### ✅ **Por qué Binary es mejor para tu caso:**\n",
23
+ "- Solo 2 clases: cotorra vs no-cotorra\n",
24
+ "- Más eficiente: menos parámetros y memoria\n",
25
+ "- Salida intuitiva: probabilidad directa de ser cotorra\n"
26
+ ]
27
+ },
28
+ {
29
+ "cell_type": "code",
30
+ "execution_count": 1,
31
+ "metadata": {},
32
+ "outputs": [],
33
+ "source": [
34
+ "import numpy as np\n",
35
+ "import librosa\n",
36
+ "import os\n",
37
+ "from sklearn.model_selection import train_test_split\n",
38
+ "# from keras.utils import to_categorical # ← NO NECESARIO para binary classification\n",
39
+ "import matplotlib.pyplot as plt\n",
40
+ "from scipy.ndimage import zoom\n",
41
+ "import warnings\n",
42
+ "warnings.filterwarnings('ignore')\n",
43
+ "\n",
44
+ "print(\"🎯 Configuración BINARIA cargada:\")\n",
45
+ "print(\" • SIN to_categorical() - etiquetas directas [0,1]\")\n",
46
+ "print(\" • Para: binary_crossentropy + 1 neurona sigmoid\")\n"
47
+ ]
48
+ },
49
+ {
50
+ "cell_type": "code",
51
+ "execution_count": 29,
52
+ "metadata": {},
53
+ "outputs": [],
54
+ "source": [
55
+ "def extract_spectrogram_features(audio_file, target_size=(224, 224)):\n",
56
+ " \"\"\"\n",
57
+ " Extrae características del espectrograma con parámetros optimizados\n",
58
+ " \"\"\"\n",
59
+ " # Parámetros optimizados del espectrograma\n",
60
+ " sr = 32000 # Frecuencia estándar para audio\n",
61
+ " n_fft = 340 # Ventana más grande para mejor resolución\n",
62
+ " hop_length = 85 # Hop length proporcional\n",
63
+ " \n",
64
+ " # Cargar audio\n",
65
+ " y, sr = librosa.load(audio_file, sr=sr)\n",
66
+ " \n",
67
+ " # Generar mel-espectrograma con parámetros compatibles\n",
68
+ " mel_spec = librosa.feature.melspectrogram(\n",
69
+ " y=y, \n",
70
+ " sr=sr, \n",
71
+ " n_fft=n_fft, \n",
72
+ " hop_length=hop_length,\n",
73
+ " )\n",
74
+ " \n",
75
+ " # Convertir a dB\n",
76
+ " log_mel_spec = librosa.power_to_db(mel_spec, ref=np.max)\n",
77
+ " \n",
78
+ " # Redimensionar al tamaño objetivo\n",
79
+ " zoom_factors = (target_size[0] / log_mel_spec.shape[0], \n",
80
+ " target_size[1] / log_mel_spec.shape[1])\n",
81
+ " resized_spec = zoom(log_mel_spec, zoom_factors, order=1)\n",
82
+ " \n",
83
+ " spec_3channel = np.stack([resized_spec] * 3, axis=-1)\n",
84
+ " \n",
85
+ " return spec_3channel\n"
86
+ ]
87
+ },
88
+ {
89
+ "cell_type": "code",
90
+ "execution_count": 30,
91
+ "metadata": {},
92
+ "outputs": [],
93
+ "source": [
94
+ "def load_audio_features_from_path(path, label, target_size=(224, 224)):\n",
95
+ " \"\"\"\n",
96
+ " Carga características de audio con validación mejorada\n",
97
+ " \"\"\"\n",
98
+ " features = []\n",
99
+ " labels = []\n",
100
+ " \n",
101
+ " print(f\"Procesando: {path}\")\n",
102
+ " files = [f for f in os.listdir(path) if f.endswith(('.wav', '.WAV'))]\n",
103
+ " print(f\"Archivos encontrados: {len(files)}\")\n",
104
+ " \n",
105
+ " for i, file in enumerate(files):\n",
106
+ " if i % 100 == 0:\n",
107
+ " print(f\"Procesando archivo {i+1}/{len(files)}\")\n",
108
+ " \n",
109
+ " audio_file = os.path.join(path, file)\n",
110
+ " try:\n",
111
+ " feature = extract_spectrogram_features(audio_file, target_size)\n",
112
+ " features.append(feature)\n",
113
+ " labels.append(label)\n",
114
+ " except Exception as e:\n",
115
+ " print(f\"Error procesando {file}: {e}\")\n",
116
+ " \n",
117
+ " print(f\"Características extraídas: {len(features)}\")\n",
118
+ " return features, labels\n"
119
+ ]
120
+ },
121
+ {
122
+ "cell_type": "code",
123
+ "execution_count": 31,
124
+ "metadata": {},
125
+ "outputs": [],
126
+ "source": [
127
+ "def normalize_features_globally(features, method='minmax'):\n",
128
+ " \"\"\"\n",
129
+ " Normalización global consistente de todas las características\n",
130
+ " CRÍTICO: Normaliza todo el dataset con las mismas estadísticas\n",
131
+ " \n",
132
+ " Args:\n",
133
+ " features: Lista de características extraídas\n",
134
+ " method: 'minmax' (recomendado para spectrogramas) o 'zscore'\n",
135
+ " \"\"\"\n",
136
+ " features_array = np.array(features)\n",
137
+ " \n",
138
+ " if method == 'minmax':\n",
139
+ " # Min-Max Scaling: [0, 1] - RECOMENDADO para spectrogramas\n",
140
+ " global_min = np.min(features_array)\n",
141
+ " global_max = np.max(features_array)\n",
142
+ " \n",
143
+ " # Evitar división por cero\n",
144
+ " if global_max == global_min:\n",
145
+ " print(\"⚠️ Todos los valores son iguales. Usando valores por defecto.\")\n",
146
+ " return features_array\n",
147
+ " \n",
148
+ " normalized_features = (features_array - global_min) / (global_max - global_min)\n",
149
+ " print(f\"✅ Min-Max Normalización aplicada:\")\n",
150
+ " print(f\" Min global: {global_min:.4f} → 0\")\n",
151
+ " print(f\" Max global: {global_max:.4f} → 1\")\n",
152
+ " print(f\" Rango: [0, 1] - Perfecto para CNNs\")\n",
153
+ " \n",
154
+ " elif method == 'zscore':\n",
155
+ " # Z-Score Scaling: media=0, std=1\n",
156
+ " global_mean = np.mean(features_array)\n",
157
+ " global_std = np.std(features_array)\n",
158
+ " \n",
159
+ " normalized_features = (features_array - global_mean) / (global_std + 1e-8)\n",
160
+ " print(f\"✅ Z-Score Normalización aplicada:\")\n",
161
+ " print(f\" Media global: {global_mean:.4f} → 0\")\n",
162
+ " print(f\" Std global: {global_std:.4f} → 1\")\n",
163
+ " \n",
164
+ " else:\n",
165
+ " raise ValueError(\"method debe ser 'minmax' o 'zscore'\")\n",
166
+ " \n",
167
+ " # Verificar rango final\n",
168
+ " final_min, final_max = np.min(normalized_features), np.max(normalized_features)\n",
169
+ " print(f\" Verificación - Rango final: [{final_min:.4f}, {final_max:.4f}]\")\n",
170
+ " \n",
171
+ " return normalized_features\n"
172
+ ]
173
+ },
174
+ {
175
+ "cell_type": "code",
176
+ "execution_count": 34,
177
+ "metadata": {},
178
+ "outputs": [
179
+ {
180
+ "name": "stdout",
181
+ "output_type": "stream",
182
+ "text": [
183
+ "=== EXTRAYENDO CARACTERÍSTICAS DE COTORRAS ===\n",
184
+ "Procesando: ../../data/crudo/clips/cotorra_1500\n",
185
+ "Archivos encontrados: 1500\n",
186
+ "Procesando archivo 1/1500\n",
187
+ "Procesando archivo 101/1500\n",
188
+ "Procesando archivo 201/1500\n",
189
+ "Procesando archivo 301/1500\n",
190
+ "Procesando archivo 401/1500\n",
191
+ "Procesando archivo 501/1500\n",
192
+ "Procesando archivo 601/1500\n",
193
+ "Procesando archivo 701/1500\n",
194
+ "Procesando archivo 801/1500\n",
195
+ "Procesando archivo 901/1500\n",
196
+ "Procesando archivo 1001/1500\n",
197
+ "Procesando archivo 1101/1500\n",
198
+ "Procesando archivo 1201/1500\n",
199
+ "Procesando archivo 1301/1500\n",
200
+ "Procesando archivo 1401/1500\n",
201
+ "Características extraídas: 1500\n",
202
+ "\n",
203
+ "=== EXTRAYENDO CARACTERÍSTICAS DE NO-COTORRAS ===\n",
204
+ "Procesando: ../../data/crudo/clips/no_cotorra\n",
205
+ "Archivos encontrados: 464\n",
206
+ "Procesando archivo 1/464\n",
207
+ "Procesando archivo 101/464\n",
208
+ "Procesando archivo 201/464\n",
209
+ "Procesando archivo 301/464\n",
210
+ "Procesando archivo 401/464\n",
211
+ "Características extraídas: 464\n",
212
+ "Procesando: ../../data/crudo/clips/no_cotorra/aves\n",
213
+ "Archivos encontrados: 587\n",
214
+ "Procesando archivo 1/587\n",
215
+ "Procesando archivo 101/587\n",
216
+ "Procesando archivo 201/587\n",
217
+ "Procesando archivo 301/587\n",
218
+ "Procesando archivo 401/587\n",
219
+ "Procesando archivo 501/587\n",
220
+ "Características extraídas: 587\n",
221
+ "\n",
222
+ "=== RESUMEN DE DATOS ===\n",
223
+ "Total de muestras: 2551\n",
224
+ "Cotorras: 1500 (58.8%)\n",
225
+ "No-cotorras: 1051 (41.2%)\n"
226
+ ]
227
+ }
228
+ ],
229
+ "source": [
230
+ "# CORRECCIÓN: Flujo de procesamiento mejorado\n",
231
+ "# Rutas de datos\n",
232
+ "cotorra_path = \"../../data/crudo/clips/cotorra_1500\"\n",
233
+ "no_cotorra_path_1 = \"../../data/crudo/clips/no_cotorra\"\n",
234
+ "no_cotorra_path_2 = \"../../data/crudo/clips/no_cotorra/aves\"\n",
235
+ "output_path = \"../data/processed_features_224x224_fixed\"\n",
236
+ "\n",
237
+ "# Crear directorio de salida\n",
238
+ "os.makedirs(output_path, exist_ok=True)\n",
239
+ "\n",
240
+ "# Extraer características SIN normalización individual\n",
241
+ "print(\"=== EXTRAYENDO CARACTERÍSTICAS DE COTORRAS ===\")\n",
242
+ "cotorra_features, cotorra_labels = load_audio_features_from_path(cotorra_path, 1)\n",
243
+ "\n",
244
+ "print(\"\\n=== EXTRAYENDO CARACTERÍSTICAS DE NO-COTORRAS ===\")\n",
245
+ "no_cotorra_features, no_cotorra_labels = load_audio_features_from_path(no_cotorra_path_1, 0)\n",
246
+ "no_cotorra_features_2, no_cotorra_labels_2 = load_audio_features_from_path(no_cotorra_path_2, 0)\n",
247
+ "\n",
248
+ "# Combinar datos\n",
249
+ "all_features = cotorra_features + no_cotorra_features + no_cotorra_features_2\n",
250
+ "all_labels = cotorra_labels + no_cotorra_labels + no_cotorra_labels_2\n",
251
+ "\n",
252
+ "print(f\"\\n=== RESUMEN DE DATOS ===\")\n",
253
+ "print(f\"Total de muestras: {len(all_features)}\")\n",
254
+ "print(f\"Cotorras: {sum(all_labels)} ({sum(all_labels)/len(all_labels)*100:.1f}%)\")\n",
255
+ "print(f\"No-cotorras: {len(all_labels) - sum(all_labels)} ({(len(all_labels) - sum(all_labels))/len(all_labels)*100:.1f}%)\")\n"
256
+ ]
257
+ },
258
+ {
259
+ "cell_type": "code",
260
+ "execution_count": 35,
261
+ "metadata": {},
262
+ "outputs": [
263
+ {
264
+ "name": "stdout",
265
+ "output_type": "stream",
266
+ "text": [
267
+ "\n",
268
+ "=== APLICANDO NORMALIZACIÓN GLOBAL ===\n",
269
+ "✅ Min-Max Normalización aplicada:\n",
270
+ " Min global: -80.0000 → 0\n",
271
+ " Max global: 0.0000 → 1\n",
272
+ " Rango: [0, 1] - Perfecto para CNNs\n",
273
+ " Verificación - Rango final: [0.0000, 1.0000]\n",
274
+ "\n",
275
+ "Forma de entrenamiento: (1785, 224, 224, 3)\n",
276
+ "Forma de test: (766, 224, 224, 3)\n",
277
+ "Distribución train - Cotorras: 1050 / No-cotorras: 735\n",
278
+ "Distribución test - Cotorras: 450 / No-cotorras: 316\n",
279
+ "\n",
280
+ "Ejemplo y_train_encoded: [[0. 1.]\n",
281
+ " [1. 0.]\n",
282
+ " [1. 0.]\n",
283
+ " [0. 1.]\n",
284
+ " [1. 0.]]\n",
285
+ "Forma y_train_encoded: (1785, 2)\n",
286
+ "Datos guardados exitosamente!\n"
287
+ ]
288
+ }
289
+ ],
290
+ "source": [
291
+ "# 🔥 CORRECCIÓN BINARIA: Normalización global ANTES de split\n",
292
+ "print(\"\\n=== APLICANDO NORMALIZACIÓN GLOBAL ===\")\n",
293
+ "\n",
294
+ "# Min-Max [0, 1] - PERFECTO para spectrogramas\n",
295
+ "all_features_normalized = normalize_features_globally(all_features, method='minmax')\n",
296
+ "all_labels_array = np.array(all_labels)\n",
297
+ "\n",
298
+ "# División estratificada\n",
299
+ "x_train, x_test, y_train, y_test = train_test_split(\n",
300
+ " all_features_normalized, all_labels_array, \n",
301
+ " test_size=0.3, \n",
302
+ " random_state=42, \n",
303
+ " stratify=all_labels_array\n",
304
+ ")\n",
305
+ "\n",
306
+ "# 🎯 CONFIGURACIÓN BINARIA: SIN to_categorical()\n",
307
+ "# Para binary_crossentropy usamos etiquetas directas [0, 1]\n",
308
+ "# NO CONVERTIMOS a one-hot [[1,0], [0,1]]\n",
309
+ "\n",
310
+ "print(f\"\\n✅ CONFIGURACIÓN BINARIA:\")\n",
311
+ "print(f\" • Etiquetas: valores directos [0, 1] (SIN one-hot)\")\n",
312
+ "print(f\" • y_train shape: {y_train.shape} - valores simples\")\n",
313
+ "print(f\" • y_test shape: {y_test.shape} - valores simples\")\n",
314
+ "\n",
315
+ "print(f\"\\n📊 DISTRIBUCIÓN:\")\n",
316
+ "print(f\" • Train - Cotorras: {np.sum(y_train)} / No-cotorras: {len(y_train) - np.sum(y_train)}\")\n",
317
+ "print(f\" • Test - Cotorras: {np.sum(y_test)} / No-cotorras: {len(y_test) - np.sum(y_test)}\")\n",
318
+ "\n",
319
+ "# Verificar etiquetas binarias\n",
320
+ "print(f\"\\n🔍 EJEMPLO ETIQUETAS:\")\n",
321
+ "print(f\" • y_train[:10]: {y_train[:10]} (0=no-cotorra, 1=cotorra)\")\n",
322
+ "print(f\" • Rango: [{y_train.min()}, {y_train.max()}] ✅\")\n",
323
+ "\n",
324
+ "# Guardar datos procesados (SIN _encoded porque son binarios directos)\n",
325
+ "np.save(os.path.join(output_path, 'x_train.npy'), x_train)\n",
326
+ "np.save(os.path.join(output_path, 'x_test.npy'), x_test)\n",
327
+ "np.save(os.path.join(output_path, 'y_train.npy'), y_train) # ← Sin encoded\n",
328
+ "np.save(os.path.join(output_path, 'y_test.npy'), y_test) # ← Sin encoded\n",
329
+ "\n",
330
+ "print(\"💾 Datos binarios guardados exitosamente!\")\n",
331
+ "print(\"🚀 Listos para binary_crossentropy + 1 neurona sigmoid\")\n"
332
+ ]
333
+ },
334
+ {
335
+ "cell_type": "code",
336
+ "execution_count": 36,
337
+ "metadata": {},
338
+ "outputs": [],
339
+ "source": [
340
+ "from keras.models import Sequential\n",
341
+ "from keras.layers import Conv2D, MaxPooling2D, Dropout, Flatten, Dense, BatchNormalization\n",
342
+ "from keras.optimizers import Adam # Automáticamente usa legacy en M1/M2 Macs\n",
343
+ "from keras.callbacks import EarlyStopping, ReduceLROnPlateau\n",
344
+ "import keras\n"
345
+ ]
346
+ },
347
+ {
348
+ "cell_type": "code",
349
+ "execution_count": 37,
350
+ "metadata": {},
351
+ "outputs": [
352
+ {
353
+ "name": "stdout",
354
+ "output_type": "stream",
355
+ "text": [
356
+ "Model: \"sequential_4\"\n",
357
+ "_________________________________________________________________\n",
358
+ " Layer (type) Output Shape Param # \n",
359
+ "=================================================================\n",
360
+ " conv2d_16 (Conv2D) (None, 222, 222, 32) 896 \n",
361
+ " \n",
362
+ " batch_normalization_16 (Ba (None, 222, 222, 32) 128 \n",
363
+ " tchNormalization) \n",
364
+ " \n",
365
+ " max_pooling2d_16 (MaxPooli (None, 111, 111, 32) 0 \n",
366
+ " ng2D) \n",
367
+ " \n",
368
+ " conv2d_17 (Conv2D) (None, 109, 109, 64) 18496 \n",
369
+ " \n",
370
+ " batch_normalization_17 (Ba (None, 109, 109, 64) 256 \n",
371
+ " tchNormalization) \n",
372
+ " \n",
373
+ " max_pooling2d_17 (MaxPooli (None, 54, 54, 64) 0 \n",
374
+ " ng2D) \n",
375
+ " \n",
376
+ " conv2d_18 (Conv2D) (None, 52, 52, 128) 73856 \n",
377
+ " \n",
378
+ " batch_normalization_18 (Ba (None, 52, 52, 128) 512 \n",
379
+ " tchNormalization) \n",
380
+ " \n",
381
+ " max_pooling2d_18 (MaxPooli (None, 26, 26, 128) 0 \n",
382
+ " ng2D) \n",
383
+ " \n",
384
+ " conv2d_19 (Conv2D) (None, 24, 24, 256) 295168 \n",
385
+ " \n",
386
+ " batch_normalization_19 (Ba (None, 24, 24, 256) 1024 \n",
387
+ " tchNormalization) \n",
388
+ " \n",
389
+ " max_pooling2d_19 (MaxPooli (None, 12, 12, 256) 0 \n",
390
+ " ng2D) \n",
391
+ " \n",
392
+ " flatten_4 (Flatten) (None, 36864) 0 \n",
393
+ " \n",
394
+ " dense_12 (Dense) (None, 512) 18874880 \n",
395
+ " \n",
396
+ " dropout_8 (Dropout) (None, 512) 0 \n",
397
+ " \n",
398
+ " dense_13 (Dense) (None, 128) 65664 \n",
399
+ " \n",
400
+ " dropout_9 (Dropout) (None, 128) 0 \n",
401
+ " \n",
402
+ " dense_14 (Dense) (None, 2) 258 \n",
403
+ " \n",
404
+ "=================================================================\n",
405
+ "Total params: 19331138 (73.74 MB)\n",
406
+ "Trainable params: 19330178 (73.74 MB)\n",
407
+ "Non-trainable params: 960 (3.75 KB)\n",
408
+ "_________________________________________________________________\n"
409
+ ]
410
+ }
411
+ ],
412
+ "source": [
413
+ "# CORRECCIÓN PRINCIPAL: Modelo con loss function compatible (estilo original)\n",
414
+ "model = Sequential()\n",
415
+ "model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(224, 224, 3)))\n",
416
+ "model.add(BatchNormalization())\n",
417
+ "model.add(MaxPooling2D(2, 2))\n",
418
+ "\n",
419
+ "model.add(Conv2D(64, (3, 3), activation='relu'))\n",
420
+ "model.add(BatchNormalization())\n",
421
+ "model.add(MaxPooling2D(2, 2))\n",
422
+ "\n",
423
+ "model.add(Conv2D(128, (3, 3), activation='relu'))\n",
424
+ "model.add(BatchNormalization())\n",
425
+ "model.add(MaxPooling2D(2, 2))\n",
426
+ "\n",
427
+ "model.add(Conv2D(256, (3, 3), activation='relu'))\n",
428
+ "model.add(BatchNormalization())\n",
429
+ "model.add(MaxPooling2D(2, 2))\n",
430
+ "\n",
431
+ "model.add(Flatten())\n",
432
+ "model.add(Dense(512, activation='relu'))\n",
433
+ "model.add(Dropout(0.5))\n",
434
+ "model.add(Dense(128, activation='relu'))\n",
435
+ "model.add(Dropout(0.3))\n",
436
+ "\n",
437
+ "# 🔥 SALIDA BINARIA: 1 neurona con sigmoid (más eficiente)\n",
438
+ "model.add(Dense(1, activation='sigmoid'))\n",
439
+ "\n",
440
+ "# 🎯 CONFIGURACIÓN BINARIA: binary_crossentropy + etiquetas directas [0,1]\n",
441
+ "model.compile(\n",
442
+ " optimizer='adam', # Keras automáticamente usa legacy Adam en M1/M2\n",
443
+ " loss='binary_crossentropy', # ← CORRECCIÓN BINARIA PRINCIPAL\n",
444
+ " metrics=['accuracy']\n",
445
+ ")\n",
446
+ "\n",
447
+ "model.summary()\n"
448
+ ]
449
+ },
450
+ {
451
+ "cell_type": "code",
452
+ "execution_count": null,
453
+ "metadata": {},
454
+ "outputs": [],
455
+ "source": [
456
+ "# 🚀 ENTRENAMIENTO BINARIO OPTIMIZADO\n",
457
+ "print(\"🎯 Iniciando entrenamiento con configuración binaria...\")\n",
458
+ "\n",
459
+ "# Callbacks opcionales (puedes comentar si prefieres entrenamiento simple)\n",
460
+ "from keras.callbacks import EarlyStopping, ReduceLROnPlateau\n",
461
+ "\n",
462
+ "early_stopping = EarlyStopping(\n",
463
+ " monitor='val_loss',\n",
464
+ " patience=5,\n",
465
+ " restore_best_weights=True\n",
466
+ ")\n",
467
+ "\n",
468
+ "reduce_lr = ReduceLROnPlateau(\n",
469
+ " monitor='val_loss',\n",
470
+ " factor=0.2,\n",
471
+ " patience=3,\n",
472
+ " min_lr=1e-7\n",
473
+ ")\n",
474
+ "\n",
475
+ "# 🔥 ENTRENAMIENTO BINARIO: usando y_train/y_test directos (SIN _encoded)\n",
476
+ "history = model.fit(\n",
477
+ " x_train, y_train, # ← Etiquetas binarias directas [0,1]\n",
478
+ " validation_data=(x_test, y_test), # ← Sin _encoded\n",
479
+ " batch_size=32, # Batch size eficiente\n",
480
+ " epochs=25,\n",
481
+ " callbacks=[early_stopping, reduce_lr],\n",
482
+ " verbose=1\n",
483
+ ")\n",
484
+ "\n",
485
+ "print(\"✅ Entrenamiento completado!\")\n",
486
+ "print(\"📊 Configuración usada:\")\n",
487
+ "print(f\" • Loss: binary_crossentropy\")\n",
488
+ "print(f\" • Salida: 1 neurona sigmoid\")\n",
489
+ "print(f\" • Etiquetas: valores directos [0,1]\")\n",
490
+ "print(f\" • Batch size: 32\")\n",
491
+ "\n",
492
+ "# Entrenamiento simple alternativo (sin callbacks):\n",
493
+ "# history = model.fit(x_train, y_train, validation_data=(x_test, y_test), batch_size=32, epochs=25)\n"
494
+ ]
495
+ },
496
+ {
497
+ "cell_type": "code",
498
+ "execution_count": 38,
499
+ "metadata": {},
500
+ "outputs": [
501
+ {
502
+ "name": "stdout",
503
+ "output_type": "stream",
504
+ "text": [
505
+ "Epoch 1/25\n",
506
+ "112/112 [==============================] - 44s 389ms/step - loss: 9.1723 - accuracy: 0.6275 - val_loss: 1.3144 - val_accuracy: 0.6789 - lr: 0.0010\n",
507
+ "Epoch 2/25\n",
508
+ "112/112 [==============================] - 46s 414ms/step - loss: 3.0741 - accuracy: 0.6599 - val_loss: 2.6101 - val_accuracy: 0.4452 - lr: 0.0010\n",
509
+ "Epoch 3/25\n",
510
+ "112/112 [==============================] - 77s 690ms/step - loss: 1.1167 - accuracy: 0.7277 - val_loss: 0.6525 - val_accuracy: 0.7833 - lr: 0.0010\n",
511
+ "Epoch 4/25\n",
512
+ "112/112 [==============================] - 71s 634ms/step - loss: 0.7091 - accuracy: 0.7630 - val_loss: 0.7093 - val_accuracy: 0.6854 - lr: 0.0010\n",
513
+ "Epoch 5/25\n",
514
+ "112/112 [==============================] - 72s 642ms/step - loss: 0.5801 - accuracy: 0.7748 - val_loss: 1.2357 - val_accuracy: 0.6540 - lr: 0.0010\n",
515
+ "Epoch 6/25\n",
516
+ "112/112 [==============================] - 69s 621ms/step - loss: 0.5239 - accuracy: 0.7854 - val_loss: 0.4493 - val_accuracy: 0.7755 - lr: 0.0010\n",
517
+ "Epoch 7/25\n",
518
+ "112/112 [==============================] - 68s 603ms/step - loss: 0.4193 - accuracy: 0.8331 - val_loss: 0.8670 - val_accuracy: 0.4517 - lr: 0.0010\n",
519
+ "Epoch 8/25\n",
520
+ "112/112 [==============================] - 69s 616ms/step - loss: 0.3989 - accuracy: 0.8364 - val_loss: 1.8077 - val_accuracy: 0.6619 - lr: 0.0010\n",
521
+ "Epoch 9/25\n",
522
+ "112/112 [==============================] - 66s 592ms/step - loss: 0.4061 - accuracy: 0.8308 - val_loss: 0.8780 - val_accuracy: 0.4452 - lr: 0.0010\n",
523
+ "Epoch 10/25\n",
524
+ "112/112 [==============================] - 68s 610ms/step - loss: 0.3163 - accuracy: 0.8784 - val_loss: 0.4764 - val_accuracy: 0.7441 - lr: 2.0000e-04\n",
525
+ "Epoch 11/25\n",
526
+ "112/112 [==============================] - 70s 623ms/step - loss: 0.2915 - accuracy: 0.8835 - val_loss: 0.3256 - val_accuracy: 0.8695 - lr: 2.0000e-04\n",
527
+ "Epoch 12/25\n",
528
+ "112/112 [==============================] - 67s 595ms/step - loss: 0.2836 - accuracy: 0.8913 - val_loss: 0.3999 - val_accuracy: 0.7990 - lr: 2.0000e-04\n",
529
+ "Epoch 13/25\n",
530
+ "112/112 [==============================] - 67s 595ms/step - loss: 0.2710 - accuracy: 0.8947 - val_loss: 0.2704 - val_accuracy: 0.8969 - lr: 2.0000e-04\n",
531
+ "Epoch 14/25\n",
532
+ "112/112 [==============================] - 74s 664ms/step - loss: 0.2442 - accuracy: 0.9064 - val_loss: 1.3001 - val_accuracy: 0.6619 - lr: 2.0000e-04\n",
533
+ "Epoch 15/25\n",
534
+ "112/112 [==============================] - 62s 557ms/step - loss: 0.2551 - accuracy: 0.9014 - val_loss: 0.7644 - val_accuracy: 0.5300 - lr: 2.0000e-04\n",
535
+ "Epoch 16/25\n",
536
+ "112/112 [==============================] - 75s 665ms/step - loss: 0.2464 - accuracy: 0.9092 - val_loss: 0.6758 - val_accuracy: 0.6345 - lr: 2.0000e-04\n",
537
+ "Epoch 17/25\n",
538
+ "112/112 [==============================] - 70s 627ms/step - loss: 0.2136 - accuracy: 0.9176 - val_loss: 0.2612 - val_accuracy: 0.9021 - lr: 4.0000e-05\n",
539
+ "Epoch 18/25\n",
540
+ "112/112 [==============================] - 67s 597ms/step - loss: 0.1968 - accuracy: 0.9182 - val_loss: 0.2603 - val_accuracy: 0.9073 - lr: 4.0000e-05\n",
541
+ "Epoch 19/25\n",
542
+ " 81/112 [====================>.........] - ETA: 17s - loss: 0.2041 - accuracy: 0.9236"
543
+ ]
544
+ },
545
+ {
546
+ "ename": "KeyboardInterrupt",
547
+ "evalue": "",
548
+ "output_type": "error",
549
+ "traceback": [
550
+ "\u001b[31m---------------------------------------------------------------------------\u001b[39m",
551
+ "\u001b[31mKeyboardInterrupt\u001b[39m Traceback (most recent call last)",
552
+ "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[38]\u001b[39m\u001b[32m, line 16\u001b[39m\n\u001b[32m 8\u001b[39m reduce_lr = ReduceLROnPlateau(\n\u001b[32m 9\u001b[39m monitor=\u001b[33m'\u001b[39m\u001b[33mval_loss\u001b[39m\u001b[33m'\u001b[39m,\n\u001b[32m 10\u001b[39m factor=\u001b[32m0.2\u001b[39m,\n\u001b[32m 11\u001b[39m patience=\u001b[32m3\u001b[39m,\n\u001b[32m 12\u001b[39m min_lr=\u001b[32m1e-7\u001b[39m\n\u001b[32m 13\u001b[39m )\n\u001b[32m 15\u001b[39m \u001b[38;5;66;03m# Entrenamiento - puedes usar con o sin callbacks\u001b[39;00m\n\u001b[32m---> \u001b[39m\u001b[32m16\u001b[39m history = \u001b[43mmodel\u001b[49m\u001b[43m.\u001b[49m\u001b[43mfit\u001b[49m\u001b[43m(\u001b[49m\n\u001b[32m 17\u001b[39m \u001b[43m \u001b[49m\u001b[43mx_train\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43my_train_encoded\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 18\u001b[39m \u001b[43m \u001b[49m\u001b[43mvalidation_data\u001b[49m\u001b[43m=\u001b[49m\u001b[43m(\u001b[49m\u001b[43mx_test\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43my_test_encoded\u001b[49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 19\u001b[39m \u001b[43m \u001b[49m\u001b[43mbatch_size\u001b[49m\u001b[43m=\u001b[49m\u001b[32;43m16\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;66;43;03m# Como tenías originalmente\u001b[39;49;00m\n\u001b[32m 20\u001b[39m \u001b[43m \u001b[49m\u001b[43mepochs\u001b[49m\u001b[43m=\u001b[49m\u001b[32;43m25\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;66;43;03m# Como tenías originalmente\u001b[39;49;00m\n\u001b[32m 21\u001b[39m \u001b[43m \u001b[49m\u001b[43mcallbacks\u001b[49m\u001b[43m=\u001b[49m\u001b[43m[\u001b[49m\u001b[43mearly_stopping\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mreduce_lr\u001b[49m\u001b[43m]\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;66;43;03m# Comenta esta línea si prefieres simple\u001b[39;49;00m\n\u001b[32m 22\u001b[39m \u001b[43m \u001b[49m\u001b[43mverbose\u001b[49m\u001b[43m=\u001b[49m\u001b[32;43m1\u001b[39;49m\n\u001b[32m 23\u001b[39m \u001b[43m)\u001b[49m\n\u001b[32m 25\u001b[39m \u001b[38;5;66;03m# Versión simple (como tu código original):\u001b[39;00m\n\u001b[32m 26\u001b[39m \u001b[38;5;66;03m# history = model.fit(x_train, y_train_encoded, validation_data=(x_test, y_test_encoded), batch_size=16, epochs=25)\u001b[39;00m\n",
553
+ "\u001b[36mFile \u001b[39m\u001b[32m~/Documentos/myiopsitta-monachus-audios/.venv/lib/python3.11/site-packages/keras/src/utils/traceback_utils.py:65\u001b[39m, in \u001b[36mfilter_traceback.<locals>.error_handler\u001b[39m\u001b[34m(*args, **kwargs)\u001b[39m\n\u001b[32m 63\u001b[39m filtered_tb = \u001b[38;5;28;01mNone\u001b[39;00m\n\u001b[32m 64\u001b[39m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[32m---> \u001b[39m\u001b[32m65\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43mfn\u001b[49m\u001b[43m(\u001b[49m\u001b[43m*\u001b[49m\u001b[43margs\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43m*\u001b[49m\u001b[43m*\u001b[49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m 66\u001b[39m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mException\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m e:\n\u001b[32m 67\u001b[39m filtered_tb = _process_traceback_frames(e.__traceback__)\n",
554
+ "\u001b[36mFile \u001b[39m\u001b[32m~/Documentos/myiopsitta-monachus-audios/.venv/lib/python3.11/site-packages/keras/src/engine/training.py:1807\u001b[39m, in \u001b[36mModel.fit\u001b[39m\u001b[34m(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_batch_size, validation_freq, max_queue_size, workers, use_multiprocessing)\u001b[39m\n\u001b[32m 1799\u001b[39m \u001b[38;5;28;01mwith\u001b[39;00m tf.profiler.experimental.Trace(\n\u001b[32m 1800\u001b[39m \u001b[33m\"\u001b[39m\u001b[33mtrain\u001b[39m\u001b[33m\"\u001b[39m,\n\u001b[32m 1801\u001b[39m epoch_num=epoch,\n\u001b[32m (...)\u001b[39m\u001b[32m 1804\u001b[39m _r=\u001b[32m1\u001b[39m,\n\u001b[32m 1805\u001b[39m ):\n\u001b[32m 1806\u001b[39m callbacks.on_train_batch_begin(step)\n\u001b[32m-> \u001b[39m\u001b[32m1807\u001b[39m tmp_logs = \u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43mtrain_function\u001b[49m\u001b[43m(\u001b[49m\u001b[43miterator\u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m 1808\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m data_handler.should_sync:\n\u001b[32m 1809\u001b[39m context.async_wait()\n",
555
+ "\u001b[36mFile \u001b[39m\u001b[32m~/Documentos/myiopsitta-monachus-audios/.venv/lib/python3.11/site-packages/tensorflow/python/util/traceback_utils.py:150\u001b[39m, in \u001b[36mfilter_traceback.<locals>.error_handler\u001b[39m\u001b[34m(*args, **kwargs)\u001b[39m\n\u001b[32m 148\u001b[39m filtered_tb = \u001b[38;5;28;01mNone\u001b[39;00m\n\u001b[32m 149\u001b[39m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[32m--> \u001b[39m\u001b[32m150\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43mfn\u001b[49m\u001b[43m(\u001b[49m\u001b[43m*\u001b[49m\u001b[43margs\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43m*\u001b[49m\u001b[43m*\u001b[49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m 151\u001b[39m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mException\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m e:\n\u001b[32m 152\u001b[39m filtered_tb = _process_traceback_frames(e.__traceback__)\n",
556
+ "\u001b[36mFile \u001b[39m\u001b[32m~/Documentos/myiopsitta-monachus-audios/.venv/lib/python3.11/site-packages/tensorflow/python/eager/polymorphic_function/polymorphic_function.py:832\u001b[39m, in \u001b[36mFunction.__call__\u001b[39m\u001b[34m(self, *args, **kwds)\u001b[39m\n\u001b[32m 829\u001b[39m compiler = \u001b[33m\"\u001b[39m\u001b[33mxla\u001b[39m\u001b[33m\"\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mself\u001b[39m._jit_compile \u001b[38;5;28;01melse\u001b[39;00m \u001b[33m\"\u001b[39m\u001b[33mnonXla\u001b[39m\u001b[33m\"\u001b[39m\n\u001b[32m 831\u001b[39m \u001b[38;5;28;01mwith\u001b[39;00m OptionalXlaContext(\u001b[38;5;28mself\u001b[39m._jit_compile):\n\u001b[32m--> \u001b[39m\u001b[32m832\u001b[39m result = \u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43m_call\u001b[49m\u001b[43m(\u001b[49m\u001b[43m*\u001b[49m\u001b[43margs\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43m*\u001b[49m\u001b[43m*\u001b[49m\u001b[43mkwds\u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m 834\u001b[39m new_tracing_count = \u001b[38;5;28mself\u001b[39m.experimental_get_tracing_count()\n\u001b[32m 835\u001b[39m without_tracing = (tracing_count == new_tracing_count)\n",
557
+ "\u001b[36mFile \u001b[39m\u001b[32m~/Documentos/myiopsitta-monachus-audios/.venv/lib/python3.11/site-packages/tensorflow/python/eager/polymorphic_function/polymorphic_function.py:868\u001b[39m, in \u001b[36mFunction._call\u001b[39m\u001b[34m(self, *args, **kwds)\u001b[39m\n\u001b[32m 865\u001b[39m \u001b[38;5;28mself\u001b[39m._lock.release()\n\u001b[32m 866\u001b[39m \u001b[38;5;66;03m# In this case we have created variables on the first call, so we run the\u001b[39;00m\n\u001b[32m 867\u001b[39m \u001b[38;5;66;03m# defunned version which is guaranteed to never create variables.\u001b[39;00m\n\u001b[32m--> \u001b[39m\u001b[32m868\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43mtracing_compilation\u001b[49m\u001b[43m.\u001b[49m\u001b[43mcall_function\u001b[49m\u001b[43m(\u001b[49m\n\u001b[32m 869\u001b[39m \u001b[43m \u001b[49m\u001b[43margs\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mkwds\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43m_no_variable_creation_config\u001b[49m\n\u001b[32m 870\u001b[39m \u001b[43m \u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m 871\u001b[39m \u001b[38;5;28;01melif\u001b[39;00m \u001b[38;5;28mself\u001b[39m._variable_creation_config \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m:\n\u001b[32m 872\u001b[39m \u001b[38;5;66;03m# Release the lock early so that multiple threads can perform the call\u001b[39;00m\n\u001b[32m 873\u001b[39m \u001b[38;5;66;03m# in parallel.\u001b[39;00m\n\u001b[32m 874\u001b[39m \u001b[38;5;28mself\u001b[39m._lock.release()\n",
558
+ "\u001b[36mFile \u001b[39m\u001b[32m~/Documentos/myiopsitta-monachus-audios/.venv/lib/python3.11/site-packages/tensorflow/python/eager/polymorphic_function/tracing_compilation.py:139\u001b[39m, in \u001b[36mcall_function\u001b[39m\u001b[34m(args, kwargs, tracing_options)\u001b[39m\n\u001b[32m 137\u001b[39m bound_args = function.function_type.bind(*args, **kwargs)\n\u001b[32m 138\u001b[39m flat_inputs = function.function_type.unpack_inputs(bound_args)\n\u001b[32m--> \u001b[39m\u001b[32m139\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43mfunction\u001b[49m\u001b[43m.\u001b[49m\u001b[43m_call_flat\u001b[49m\u001b[43m(\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;66;43;03m# pylint: disable=protected-access\u001b[39;49;00m\n\u001b[32m 140\u001b[39m \u001b[43m \u001b[49m\u001b[43mflat_inputs\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mcaptured_inputs\u001b[49m\u001b[43m=\u001b[49m\u001b[43mfunction\u001b[49m\u001b[43m.\u001b[49m\u001b[43mcaptured_inputs\u001b[49m\n\u001b[32m 141\u001b[39m \u001b[43m\u001b[49m\u001b[43m)\u001b[49m\n",
559
+ "\u001b[36mFile \u001b[39m\u001b[32m~/Documentos/myiopsitta-monachus-audios/.venv/lib/python3.11/site-packages/tensorflow/python/eager/polymorphic_function/concrete_function.py:1323\u001b[39m, in \u001b[36mConcreteFunction._call_flat\u001b[39m\u001b[34m(self, tensor_inputs, captured_inputs)\u001b[39m\n\u001b[32m 1319\u001b[39m possible_gradient_type = gradients_util.PossibleTapeGradientTypes(args)\n\u001b[32m 1320\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m (possible_gradient_type == gradients_util.POSSIBLE_GRADIENT_TYPES_NONE\n\u001b[32m 1321\u001b[39m \u001b[38;5;129;01mand\u001b[39;00m executing_eagerly):\n\u001b[32m 1322\u001b[39m \u001b[38;5;66;03m# No tape is watching; skip to running the function.\u001b[39;00m\n\u001b[32m-> \u001b[39m\u001b[32m1323\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43m_inference_function\u001b[49m\u001b[43m.\u001b[49m\u001b[43mcall_preflattened\u001b[49m\u001b[43m(\u001b[49m\u001b[43margs\u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m 1324\u001b[39m forward_backward = \u001b[38;5;28mself\u001b[39m._select_forward_and_backward_functions(\n\u001b[32m 1325\u001b[39m args,\n\u001b[32m 1326\u001b[39m possible_gradient_type,\n\u001b[32m 1327\u001b[39m executing_eagerly)\n\u001b[32m 1328\u001b[39m forward_function, args_with_tangents = forward_backward.forward()\n",
560
+ "\u001b[36mFile \u001b[39m\u001b[32m~/Documentos/myiopsitta-monachus-audios/.venv/lib/python3.11/site-packages/tensorflow/python/eager/polymorphic_function/atomic_function.py:216\u001b[39m, in \u001b[36mAtomicFunction.call_preflattened\u001b[39m\u001b[34m(self, args)\u001b[39m\n\u001b[32m 214\u001b[39m \u001b[38;5;28;01mdef\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34mcall_preflattened\u001b[39m(\u001b[38;5;28mself\u001b[39m, args: Sequence[core.Tensor]) -> Any:\n\u001b[32m 215\u001b[39m \u001b[38;5;250m \u001b[39m\u001b[33;03m\"\"\"Calls with flattened tensor inputs and returns the structured output.\"\"\"\u001b[39;00m\n\u001b[32m--> \u001b[39m\u001b[32m216\u001b[39m flat_outputs = \u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43mcall_flat\u001b[49m\u001b[43m(\u001b[49m\u001b[43m*\u001b[49m\u001b[43margs\u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m 217\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28mself\u001b[39m.function_type.pack_output(flat_outputs)\n",
561
+ "\u001b[36mFile \u001b[39m\u001b[32m~/Documentos/myiopsitta-monachus-audios/.venv/lib/python3.11/site-packages/tensorflow/python/eager/polymorphic_function/atomic_function.py:251\u001b[39m, in \u001b[36mAtomicFunction.call_flat\u001b[39m\u001b[34m(self, *args)\u001b[39m\n\u001b[32m 249\u001b[39m \u001b[38;5;28;01mwith\u001b[39;00m record.stop_recording():\n\u001b[32m 250\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mself\u001b[39m._bound_context.executing_eagerly():\n\u001b[32m--> \u001b[39m\u001b[32m251\u001b[39m outputs = \u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43m_bound_context\u001b[49m\u001b[43m.\u001b[49m\u001b[43mcall_function\u001b[49m\u001b[43m(\u001b[49m\n\u001b[32m 252\u001b[39m \u001b[43m \u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43mname\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 253\u001b[39m \u001b[43m \u001b[49m\u001b[38;5;28;43mlist\u001b[39;49m\u001b[43m(\u001b[49m\u001b[43margs\u001b[49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 254\u001b[39m \u001b[43m \u001b[49m\u001b[38;5;28;43mlen\u001b[39;49m\u001b[43m(\u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43mfunction_type\u001b[49m\u001b[43m.\u001b[49m\u001b[43mflat_outputs\u001b[49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 255\u001b[39m \u001b[43m \u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m 256\u001b[39m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[32m 257\u001b[39m outputs = make_call_op_in_graph(\n\u001b[32m 258\u001b[39m \u001b[38;5;28mself\u001b[39m,\n\u001b[32m 259\u001b[39m \u001b[38;5;28mlist\u001b[39m(args),\n\u001b[32m 260\u001b[39m \u001b[38;5;28mself\u001b[39m._bound_context.function_call_options.as_attrs(),\n\u001b[32m 261\u001b[39m )\n",
562
+ "\u001b[36mFile \u001b[39m\u001b[32m~/Documentos/myiopsitta-monachus-audios/.venv/lib/python3.11/site-packages/tensorflow/python/eager/context.py:1486\u001b[39m, in \u001b[36mContext.call_function\u001b[39m\u001b[34m(self, name, tensor_inputs, num_outputs)\u001b[39m\n\u001b[32m 1484\u001b[39m cancellation_context = cancellation.context()\n\u001b[32m 1485\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m cancellation_context \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m:\n\u001b[32m-> \u001b[39m\u001b[32m1486\u001b[39m outputs = \u001b[43mexecute\u001b[49m\u001b[43m.\u001b[49m\u001b[43mexecute\u001b[49m\u001b[43m(\u001b[49m\n\u001b[32m 1487\u001b[39m \u001b[43m \u001b[49m\u001b[43mname\u001b[49m\u001b[43m.\u001b[49m\u001b[43mdecode\u001b[49m\u001b[43m(\u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mutf-8\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 1488\u001b[39m \u001b[43m \u001b[49m\u001b[43mnum_outputs\u001b[49m\u001b[43m=\u001b[49m\u001b[43mnum_outputs\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 1489\u001b[39m \u001b[43m \u001b[49m\u001b[43minputs\u001b[49m\u001b[43m=\u001b[49m\u001b[43mtensor_inputs\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 1490\u001b[39m \u001b[43m \u001b[49m\u001b[43mattrs\u001b[49m\u001b[43m=\u001b[49m\u001b[43mattrs\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 1491\u001b[39m \u001b[43m \u001b[49m\u001b[43mctx\u001b[49m\u001b[43m=\u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[43m,\u001b[49m\n\u001b[32m 1492\u001b[39m \u001b[43m \u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m 1493\u001b[39m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[32m 1494\u001b[39m outputs = execute.execute_with_cancellation(\n\u001b[32m 1495\u001b[39m name.decode(\u001b[33m\"\u001b[39m\u001b[33mutf-8\u001b[39m\u001b[33m\"\u001b[39m),\n\u001b[32m 1496\u001b[39m num_outputs=num_outputs,\n\u001b[32m (...)\u001b[39m\u001b[32m 1500\u001b[39m cancellation_manager=cancellation_context,\n\u001b[32m 1501\u001b[39m )\n",
563
+ "\u001b[36mFile \u001b[39m\u001b[32m~/Documentos/myiopsitta-monachus-audios/.venv/lib/python3.11/site-packages/tensorflow/python/eager/execute.py:53\u001b[39m, in \u001b[36mquick_execute\u001b[39m\u001b[34m(op_name, num_outputs, inputs, attrs, ctx, name)\u001b[39m\n\u001b[32m 51\u001b[39m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[32m 52\u001b[39m ctx.ensure_initialized()\n\u001b[32m---> \u001b[39m\u001b[32m53\u001b[39m tensors = \u001b[43mpywrap_tfe\u001b[49m\u001b[43m.\u001b[49m\u001b[43mTFE_Py_Execute\u001b[49m\u001b[43m(\u001b[49m\u001b[43mctx\u001b[49m\u001b[43m.\u001b[49m\u001b[43m_handle\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mdevice_name\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mop_name\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 54\u001b[39m \u001b[43m \u001b[49m\u001b[43minputs\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mattrs\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mnum_outputs\u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m 55\u001b[39m \u001b[38;5;28;01mexcept\u001b[39;00m core._NotOkStatusException \u001b[38;5;28;01mas\u001b[39;00m e:\n\u001b[32m 56\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m name \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m:\n",
564
+ "\u001b[31mKeyboardInterrupt\u001b[39m: "
565
+ ]
566
+ }
567
+ ],
568
+ "source": [
569
+ "# Callbacks para entrenamiento robusto (opcional - puedes comentar si prefieres simple)\n",
570
+ "early_stopping = EarlyStopping(\n",
571
+ " monitor='val_loss',\n",
572
+ " patience=5,\n",
573
+ " restore_best_weights=True\n",
574
+ ")\n",
575
+ "\n",
576
+ "reduce_lr = ReduceLROnPlateau(\n",
577
+ " monitor='val_loss',\n",
578
+ " factor=0.2,\n",
579
+ " patience=3,\n",
580
+ " min_lr=1e-7\n",
581
+ ")\n",
582
+ "\n",
583
+ "# Entrenamiento - puedes usar con o sin callbacks\n",
584
+ "history = model.fit(\n",
585
+ " x_train, y_train_encoded,\n",
586
+ " validation_data=(x_test, y_test_encoded),\n",
587
+ " batch_size=16, # Como tenías originalmente\n",
588
+ " epochs=25, # Como tenías originalmente\n",
589
+ " callbacks=[early_stopping, reduce_lr], # Comenta esta línea si prefieres simple\n",
590
+ " verbose=1\n",
591
+ ")\n",
592
+ "\n",
593
+ "# Versión simple (como tu código original):\n",
594
+ "# history = model.fit(x_train, y_train_encoded, validation_data=(x_test, y_test_encoded), batch_size=16, epochs=25)\n"
595
+ ]
596
+ },
597
+ {
598
+ "cell_type": "code",
599
+ "execution_count": null,
600
+ "metadata": {},
601
+ "outputs": [],
602
+ "source": [
603
+ "# 📊 EVALUACIÓN BINARIA COMPLETA\n",
604
+ "import matplotlib.pyplot as plt\n",
605
+ "from sklearn.metrics import confusion_matrix, classification_report\n",
606
+ "import seaborn as sns\n",
607
+ "\n",
608
+ "# Gráficos de entrenamiento\n",
609
+ "fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 5))\n",
610
+ "\n",
611
+ "# Accuracy\n",
612
+ "ax1.plot(history.history['accuracy'], label='Training Accuracy')\n",
613
+ "ax1.plot(history.history['val_accuracy'], label='Validation Accuracy')\n",
614
+ "ax1.set_title('Model Accuracy (Binary)')\n",
615
+ "ax1.set_xlabel('Epoch')\n",
616
+ "ax1.set_ylabel('Accuracy')\n",
617
+ "ax1.legend()\n",
618
+ "\n",
619
+ "# Loss\n",
620
+ "ax2.plot(history.history['loss'], label='Training Loss')\n",
621
+ "ax2.plot(history.history['val_loss'], label='Validation Loss')\n",
622
+ "ax2.set_title('Model Loss (Binary)')\n",
623
+ "ax2.set_xlabel('Epoch')\n",
624
+ "ax2.set_ylabel('Loss')\n",
625
+ "ax2.legend()\n",
626
+ "\n",
627
+ "plt.tight_layout()\n",
628
+ "plt.show()\n",
629
+ "\n",
630
+ "# 🎯 PREDICCIONES BINARIAS (diferentes a categorical)\n",
631
+ "y_pred_probs = model.predict(x_test) # Probabilidades de ser cotorra [0-1]\n",
632
+ "y_pred_classes = (y_pred_probs > 0.5).astype(int).flatten() # Convertir a clases [0,1]\n",
633
+ "\n",
634
+ "print(\"🔍 EJEMPLOS DE PREDICCIÓN BINARIA:\")\n",
635
+ "print(f\"Probabilidades: {y_pred_probs[:5].flatten()}\")\n",
636
+ "print(f\"Clases predichas: {y_pred_classes[:5]}\")\n",
637
+ "print(f\"Clases reales: {y_test[:5]}\")\n",
638
+ "\n",
639
+ "# Matriz de confusión BINARIA\n",
640
+ "cm = confusion_matrix(y_test, y_pred_classes) # ← Usando y_test directo (no _encoded)\n",
641
+ "plt.figure(figsize=(8, 6))\n",
642
+ "sns.heatmap(cm, annot=True, fmt='d', cmap='Blues',\n",
643
+ " xticklabels=['No Cotorra', 'Cotorra'],\n",
644
+ " yticklabels=['No Cotorra', 'Cotorra'])\n",
645
+ "plt.title('Confusion Matrix (Binary)')\n",
646
+ "plt.ylabel('True Label')\n",
647
+ "plt.xlabel('Predicted Label')\n",
648
+ "plt.show()\n",
649
+ "\n",
650
+ "# Reporte de clasificación BINARIA\n",
651
+ "print(\"\\n📋 CLASSIFICATION REPORT (BINARY):\")\n",
652
+ "print(classification_report(y_test, y_pred_classes, target_names=['No Cotorra', 'Cotorra']))\n",
653
+ "\n",
654
+ "# Estadísticas adicionales\n",
655
+ "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n",
656
+ "\n",
657
+ "accuracy = accuracy_score(y_test, y_pred_classes)\n",
658
+ "precision = precision_score(y_test, y_pred_classes)\n",
659
+ "recall = recall_score(y_test, y_pred_classes)\n",
660
+ "f1 = f1_score(y_test, y_pred_classes)\n",
661
+ "\n",
662
+ "print(f\"\\n🎯 MÉTRICAS BINARIAS:\")\n",
663
+ "print(f\" • Accuracy: {accuracy:.4f}\")\n",
664
+ "print(f\" • Precision: {precision:.4f}\")\n",
665
+ "print(f\" • Recall: {recall:.4f}\")\n",
666
+ "print(f\" • F1-Score: {f1:.4f}\")\n",
667
+ "\n",
668
+ "# Guardar modelo binario\n",
669
+ "model.save('modelo_cotorra_binario_optimizado.h5')\n",
670
+ "print(\"\\n💾 Modelo guardado como 'modelo_cotorra_binario_optimizado.h5'\")\n",
671
+ "print(\"🚀 Configuración: binary_crossentropy + 1 neurona sigmoid + etiquetas [0,1]\")\n"
672
+ ]
673
+ },
674
+ {
675
+ "cell_type": "raw",
676
+ "metadata": {
677
+ "vscode": {
678
+ "languageId": "raw"
679
+ }
680
+ },
681
+ "source": [
682
+ "## 📋 **RESUMEN: Binary vs Categorical Cross-Entropy**\n",
683
+ "\n",
684
+ "### ✅ **CONFIGURACIÓN BINARIA (actual - MÁS EFICIENTE)**\n",
685
+ "\n",
686
+ "| Aspecto | Configuración |\n",
687
+ "|---------|---------------|\n",
688
+ "| **Problema** | 2 clases: cotorra vs no-cotorra |\n",
689
+ "| **Neuronas salida** | `Dense(1, activation='sigmoid')` |\n",
690
+ "| **Loss function** | `binary_crossentropy` |\n",
691
+ "| **Etiquetas** | `[0, 1, 0, 1, ...]` (valores directos) |\n",
692
+ "| **Predicción** | `model.predict()` → `[0.23, 0.87, ...]` (probabilidades) |\n",
693
+ "| **Ventajas** | ✅ Más eficiente, menos parámetros, más natural |\n",
694
+ "\n",
695
+ "### 🔄 **CONFIGURACIÓN CATEGORICAL (alternativa)**\n",
696
+ "\n",
697
+ "| Aspecto | Configuración |\n",
698
+ "|---------|---------------|\n",
699
+ "| **Problema** | 2+ clases (extensible) |\n",
700
+ "| **Neuronas salida** | `Dense(2, activation='softmax')` |\n",
701
+ "| **Loss function** | `categorical_crossentropy` |\n",
702
+ "| **Etiquetas** | `[[1,0], [0,1], [1,0], ...]` (one-hot) |\n",
703
+ "| **Predicción** | `model.predict()` → `[[0.77,0.23], [0.13,0.87], ...]` |\n",
704
+ "| **Ventajas** | ✅ Extensible a más clases, probabilidades explícitas |\n",
705
+ "\n",
706
+ "### 🎯 **¿CUÁL USAR PARA COTORRAS?**\n",
707
+ "\n",
708
+ "**Para tu caso (cotorra vs no-cotorra): BINARY es mejor porque:**\n",
709
+ "\n",
710
+ "1. **Más eficiente**: 1 neurona vs 2 neuronas = menos parámetros\n",
711
+ "2. **Más natural**: Solo 2 clases, no necesitas extensibilidad \n",
712
+ "3. **Más rápido**: Menos cómputo y memoria\n",
713
+ "4. **Salida intuitiva**: Probabilidad directa de ser cotorra\n",
714
+ "5. **Más simple**: Sin `to_categorical()`, etiquetas directas\n",
715
+ "\n",
716
+ "### ❌ **TU PROBLEMA ORIGINAL**\n",
717
+ "```python\n",
718
+ "# INCOMPATIBLE: binary loss + categorical data\n",
719
+ "model.add(Dense(2, activation='softmax'))\n",
720
+ "model.compile(loss='binary_crossentropy') # ← Binary loss\n",
721
+ "y_train = to_categorical(y_train) # ← Categorical data\n",
722
+ "# RESULTADO: No puede aprender correctamente\n",
723
+ "```\n",
724
+ "\n",
725
+ "### ✅ **SOLUCIÓN APLICADA**\n",
726
+ "```python\n",
727
+ "# COMPATIBLE: binary loss + binary data\n",
728
+ "model.add(Dense(1, activation='sigmoid')) # ← 1 neurona\n",
729
+ "model.compile(loss='binary_crossentropy') # ← Binary loss \n",
730
+ "y_train = [0, 1, 0, 1, ...] # ← Binary data\n",
731
+ "# RESULTADO: ¡Aprende correctamente!\n",
732
+ "```\n"
733
+ ]
734
+ }
735
+ ],
736
+ "metadata": {
737
+ "kernelspec": {
738
+ "display_name": ".venv",
739
+ "language": "python",
740
+ "name": "python3"
741
+ },
742
+ "language_info": {
743
+ "codemirror_mode": {
744
+ "name": "ipython",
745
+ "version": 3
746
+ },
747
+ "file_extension": ".py",
748
+ "mimetype": "text/x-python",
749
+ "name": "python",
750
+ "nbconvert_exporter": "python",
751
+ "pygments_lexer": "ipython3",
752
+ "version": "3.11.13"
753
+ }
754
+ },
755
+ "nbformat": 4,
756
+ "nbformat_minor": 2
757
+ }
src/training/src/parakeets_cnn_training (1).ipynb DELETED
The diff for this file is too large to render. See raw diff