-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathprueba.py
More file actions
232 lines (184 loc) · 8.6 KB
/
Copy pathprueba.py
File metadata and controls
232 lines (184 loc) · 8.6 KB
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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
import cv2
import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow.keras.applications import MobileNetV2
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Dense, GlobalAveragePooling2D
from tensorflow.keras.preprocessing.image import img_to_array, load_img
from tensorflow.keras.optimizers import Adam
from sklearn.decomposition import PCA
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA
from sklearn.pipeline import Pipeline
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report
import os
import matplotlib.pyplot as plt
import seaborn as sns
# --- CONFIGURACIÓN ---
BASE_DIR = 'Synthetic_DB_CAS'
CLASSES = ['confused', 'distracted', 'fatigued', 'joyful', 'neutral']
NUM_CLASSES = len(CLASSES)
# REQUISITO 1: Limite de imagenes para evitar fallos de memoria
MAX_IMAGES_PER_CLASS = 100
# Rutas a los splits
TRAIN_DIR = os.path.join(BASE_DIR, 'train')
VAL_DIR = os.path.join(BASE_DIR, 'val')
TEST_DIR = os.path.join(BASE_DIR, 'test')
# --- PREPROCESAMIENTO ---
def preprocess_fisherfaces(img_array):
"""Escala de grises, 100x100, estandarizacion."""
standardized_img = (img_array - np.mean(img_array)) / (np.std(img_array) + 1e-6)
return standardized_img.flatten()
def preprocess_mobilenet(img_array):
"""Normalizacion para MobileNet [0, 1]."""
return img_array / 255.0
# --- CARGA DE DATOS (CON LIMITE) ---
def load_images_from_directory(directory, target_size, is_rgb, model_type):
"""Carga imagenes limitando la cantidad a MAX_IMAGES_PER_CLASS."""
X = []
y = []
label_map = {cls: i for i, cls in enumerate(CLASSES)}
print(f"--- Cargando {directory} ({model_type}) ---")
if not os.path.exists(directory):
print(f"ERROR: No existe {directory}")
return np.array([]), np.array([])
for class_name in CLASSES:
class_path = os.path.join(directory, class_name)
if not os.path.isdir(class_path): continue
label_index = label_map[class_name]
files = os.listdir(class_path)
count = 0
for filename in files:
if count >= MAX_IMAGES_PER_CLASS:
break # DETENER SI SE ALCANZA EL LIMITE
img_path = os.path.join(class_path, filename)
try:
color_mode = 'rgb' if is_rgb else 'grayscale'
img = load_img(img_path, color_mode=color_mode, target_size=target_size)
img_array = img_to_array(img)
if model_type == 'mobilenet':
processed = preprocess_mobilenet(img_array)
else:
img_np = np.squeeze(img_array)
processed = preprocess_fisherfaces(img_np)
X.append(processed)
y.append(label_index)
count += 1
except Exception as e: pass
print(f" Clase '{class_name}': {count} imagenes.")
return np.array(X), np.array(y)
# --- VISUALIZACIÓN AVANZADA ---
def plot_history(history, model_name):
"""Curvas de aprendizaje."""
acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs_range = range(len(acc))
plt.figure(figsize=(12, 5))
plt.subplot(1, 2, 1)
plt.plot(epochs_range, acc, label='Train Acc')
plt.plot(epochs_range, val_acc, label='Val Acc')
plt.title(f'{model_name} - Accuracy')
plt.legend()
plt.grid(True)
plt.subplot(1, 2, 2)
plt.plot(epochs_range, loss, label='Train Loss')
plt.plot(epochs_range, val_loss, label='Val Loss')
plt.title(f'{model_name} - Loss')
plt.legend()
plt.grid(True)
plt.show()
def plot_confusion_matrix_heatmap(y_true, y_pred, title):
"""REQUISITO: Mapa de calor de la matriz de confusión."""
cm = confusion_matrix(y_true, y_pred)
plt.figure(figsize=(8, 6))
sns.heatmap(cm, annot=True, fmt='d', cmap='YlGnBu',
xticklabels=CLASSES, yticklabels=CLASSES)
plt.xlabel('Predicción')
plt.ylabel('Verdad (Ground Truth)')
plt.title(f'Mapa de Calor: {title}')
plt.show()
def plot_confidence_boxplot(y_true, y_probs, title):
"""
REQUISITO: Diagrama de Caja y Bigotes.
Muestra la distribución de la probabilidad predicha para la clase CORRECTA.
Ayuda a ver qué tan "seguro" está el modelo en cada clase.
"""
# Obtener la probabilidad asignada a la clase verdadera para cada ejemplo
# y_probs es shape (N, 5), y_true es (N,)
# Seleccionamos la probabilidad correspondiente a la columna de la clase real
true_class_probs = y_probs[np.arange(len(y_true)), y_true]
# Crear DataFrame para Seaborn
data = pd.DataFrame({
'Clase Real': [CLASSES[i] for i in y_true],
'Confianza (Probabilidad)': true_class_probs
})
plt.figure(figsize=(10, 6))
sns.boxplot(x='Clase Real', y='Confianza (Probabilidad)', data=data, palette="Set2")
plt.title(f'Distribución de Confianza (Boxplot): {title}')
plt.grid(True, linestyle='--', alpha=0.7)
plt.show()
print(f"\n--- Estadísticas de Confianza ({title}) ---")
print(data.groupby('Clase Real')['Confianza (Probabilidad)'].describe())
# =============================================================================
# BLOQUE 1: ENTRENAMIENTO MOBILENET
# =============================================================================
print("\n=== 1. MODELO MOBILENET ===")
X_train_mb, y_train_mb = load_images_from_directory(TRAIN_DIR, (224, 224), True, 'mobilenet')
X_val_mb, y_val_mb = load_images_from_directory(VAL_DIR, (224, 224), True, 'mobilenet')
X_test_mb, y_test_mb = load_images_from_directory(TEST_DIR, (224, 224), True, 'mobilenet')
if len(X_train_mb) > 0:
y_train_cat = tf.keras.utils.to_categorical(y_train_mb, NUM_CLASSES)
y_val_cat = tf.keras.utils.to_categorical(y_val_mb, NUM_CLASSES)
base_model = MobileNetV2(weights='imagenet', include_top=False, input_shape=(224, 224, 3))
base_model.trainable = False
x = base_model.output
x = GlobalAveragePooling2D()(x)
x = Dense(128, activation='relu')(x)
predictions = Dense(NUM_CLASSES, activation='softmax')(x)
model_mb = Model(inputs=base_model.input, outputs=predictions)
print("Entrenando...")
model_mb.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
history_mb = model_mb.fit(X_train_mb, y_train_cat, epochs=10,
validation_data=(X_val_mb, y_val_cat), verbose=1)
# GRAFICAS
plot_history(history_mb, 'MobileNetV2')
print("\n--- Resultados Test Set (MobileNet) ---")
y_pred_probs_mb = model_mb.predict(X_test_mb)
y_pred_mb = np.argmax(y_pred_probs_mb, axis=1)
print(classification_report(y_test_mb, y_pred_mb, target_names=CLASSES))
# MAPA DE CALOR
plot_confusion_matrix_heatmap(y_test_mb, y_pred_mb, 'MobileNetV2')
# CAJA Y BIGOTES
plot_confidence_boxplot(y_test_mb, y_pred_probs_mb, 'MobileNetV2')
else:
print("ERROR: No hay datos para MobileNet.")
# =============================================================================
# BLOQUE 2: ENTRENAMIENTO FISHERFACES
# =============================================================================
print("\n=== 2. MODELO FISHERFACES ===")
X_train_ff, y_train_ff = load_images_from_directory(TRAIN_DIR, (100, 100), False, 'fisherfaces')
X_test_ff, y_test_ff = load_images_from_directory(TEST_DIR, (100, 100), False, 'fisherfaces')
if len(X_train_ff) > 0:
n_components_pca = min(150, X_train_ff.shape[0] - 1)
# IMPORTANTE: SVC necesita probability=True para el boxplot
fisher_pipeline = Pipeline([
('pca', PCA(n_components=n_components_pca, whiten=True)),
('lda', LDA(n_components=NUM_CLASSES - 1)),
('clf', SVC(kernel='linear', class_weight='balanced', probability=True))
])
print("Entrenando Fisherfaces...")
fisher_pipeline.fit(X_train_ff, y_train_ff)
print("\n--- Resultados Test Set (Fisherfaces) ---")
y_pred_ff = fisher_pipeline.predict(X_test_ff)
y_pred_probs_ff = fisher_pipeline.predict_proba(X_test_ff) # Probabilidades para boxplot
print(classification_report(y_test_ff, y_pred_ff, target_names=CLASSES))
# MAPA DE CALOR
plot_confusion_matrix_heatmap(y_test_ff, y_pred_ff, 'Fisherfaces')
# CAJA Y BIGOTES
plot_confidence_boxplot(y_test_ff, y_pred_probs_ff, 'Fisherfaces')
else:
print("ERROR: No hay datos para Fisherfaces.")
print("\n=== ENTRENAMIENTO Y ANÁLISIS FINALIZADO ===")