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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import torch.optim as optim
|
| 4 |
+
import pickle
|
| 5 |
+
import numpy as np
|
| 6 |
+
from torch.utils.data import Dataset, DataLoader
|
| 7 |
+
from sklearn.utils.class_weight import compute_class_weight
|
| 8 |
+
from sklearn.metrics import classification_report, confusion_matrix
|
| 9 |
+
from huggingface_hub import HfApi
|
| 10 |
+
import matplotlib.pyplot as plt
|
| 11 |
+
import seaborn as sns
|
| 12 |
+
|
| 13 |
+
api = HfApi()
|
| 14 |
+
|
| 15 |
+
EMOTIONS = ["neutral", "happy", "sad", "angry", "fear", "surprise"]
|
| 16 |
+
INPUT_DIM = 1280
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class EmotionDataset(Dataset):
|
| 20 |
+
def __init__(self, records):
|
| 21 |
+
self.features = torch.tensor(
|
| 22 |
+
np.stack([r["features"] for r in records]), dtype=torch.float32
|
| 23 |
+
)
|
| 24 |
+
self.labels = torch.tensor([r["label"] for r in records], dtype=torch.long)
|
| 25 |
+
|
| 26 |
+
def __len__(self):
|
| 27 |
+
return len(self.labels)
|
| 28 |
+
|
| 29 |
+
def __getitem__(self, i):
|
| 30 |
+
return self.features[i], self.labels[i]
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class EmotionHead(nn.Module):
|
| 34 |
+
def __init__(self, input_dim=INPUT_DIM, hidden=512, num_classes=6, dropout=0.3):
|
| 35 |
+
super().__init__()
|
| 36 |
+
self.net = nn.Sequential(
|
| 37 |
+
nn.Linear(input_dim, hidden),
|
| 38 |
+
nn.BatchNorm1d(hidden),
|
| 39 |
+
nn.ReLU(),
|
| 40 |
+
nn.Dropout(dropout),
|
| 41 |
+
nn.Linear(hidden, hidden // 2),
|
| 42 |
+
nn.BatchNorm1d(hidden // 2),
|
| 43 |
+
nn.ReLU(),
|
| 44 |
+
nn.Dropout(dropout),
|
| 45 |
+
nn.Linear(hidden // 2, num_classes),
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
def forward(self, x):
|
| 49 |
+
return self.net(x)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
print("Cargando features...")
|
| 53 |
+
with open("features.pkl", "rb") as f:
|
| 54 |
+
records = pickle.load(f)
|
| 55 |
+
|
| 56 |
+
train_r = [r for r in records if r.get("split", "train") == "train"]
|
| 57 |
+
val_r = [r for r in records if r.get("split", "train") == "validation"]
|
| 58 |
+
test_r = [r for r in records if r.get("split", "train") == "test"]
|
| 59 |
+
|
| 60 |
+
if not val_r:
|
| 61 |
+
np.random.shuffle(records)
|
| 62 |
+
n = len(records)
|
| 63 |
+
train_r = records[: int(n * 0.70)]
|
| 64 |
+
val_r = records[int(n * 0.70) : int(n * 0.85)]
|
| 65 |
+
test_r = records[int(n * 0.85) :]
|
| 66 |
+
|
| 67 |
+
print(f"Train: {len(train_r)} | Val: {len(val_r)} | Test: {len(test_r)}")
|
| 68 |
+
|
| 69 |
+
train_ds = EmotionDataset(train_r)
|
| 70 |
+
val_ds = EmotionDataset(val_r)
|
| 71 |
+
test_ds = EmotionDataset(test_r)
|
| 72 |
+
|
| 73 |
+
train_loader = DataLoader(train_ds, batch_size=32, shuffle=True)
|
| 74 |
+
val_loader = DataLoader(val_ds, batch_size=32)
|
| 75 |
+
test_loader = DataLoader(test_ds, batch_size=32)
|
| 76 |
+
|
| 77 |
+
labels_array = np.array([r["label"] for r in train_r])
|
| 78 |
+
class_weights = compute_class_weight("balanced", classes=np.arange(6), y=labels_array)
|
| 79 |
+
weights_tensor = torch.FloatTensor(class_weights).to("cuda")
|
| 80 |
+
|
| 81 |
+
device = torch.device("cuda")
|
| 82 |
+
model = EmotionHead().to(device)
|
| 83 |
+
criterion = nn.CrossEntropyLoss(weight=weights_tensor)
|
| 84 |
+
optimizer = optim.AdamW(model.parameters(), lr=1e-3, weight_decay=1e-4)
|
| 85 |
+
scheduler = optim.lr_scheduler.ReduceLROnPlateau(
|
| 86 |
+
optimizer, patience=8, factor=0.5, verbose=True
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
best_val_f1 = 0
|
| 90 |
+
history = {"train_loss": [], "val_loss": [], "val_acc": []}
|
| 91 |
+
|
| 92 |
+
print("\nTraining...")
|
| 93 |
+
for epoch in range(150):
|
| 94 |
+
model.train()
|
| 95 |
+
train_loss = 0
|
| 96 |
+
for features, labels in train_loader:
|
| 97 |
+
features, labels = features.to(device), labels.to(device)
|
| 98 |
+
optimizer.zero_grad()
|
| 99 |
+
loss = criterion(model(features), labels)
|
| 100 |
+
loss.backward()
|
| 101 |
+
optimizer.step()
|
| 102 |
+
train_loss += loss.item()
|
| 103 |
+
train_loss /= len(train_loader)
|
| 104 |
+
|
| 105 |
+
model.eval()
|
| 106 |
+
val_loss, correct, total = 0, 0, 0
|
| 107 |
+
with torch.no_grad():
|
| 108 |
+
for features, labels in val_loader:
|
| 109 |
+
features, labels = features.to(device), labels.to(device)
|
| 110 |
+
logits = model(features)
|
| 111 |
+
val_loss += criterion(logits, labels).item()
|
| 112 |
+
correct += (logits.argmax(1) == labels).sum().item()
|
| 113 |
+
total += len(labels)
|
| 114 |
+
val_loss /= len(val_loader)
|
| 115 |
+
val_acc = correct / total
|
| 116 |
+
|
| 117 |
+
scheduler.step(val_loss)
|
| 118 |
+
history["train_loss"].append(train_loss)
|
| 119 |
+
history["val_loss"].append(val_loss)
|
| 120 |
+
history["val_acc"].append(val_acc)
|
| 121 |
+
|
| 122 |
+
if epoch % 20 == 0 or epoch == 149:
|
| 123 |
+
print(
|
| 124 |
+
f"Epoch {epoch:3d} | train={train_loss:.3f} | val={val_loss:.3f} | acc={val_acc:.2%}"
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
if val_acc > best_val_f1:
|
| 128 |
+
best_val_f1 = val_acc
|
| 129 |
+
torch.save(model.state_dict(), "emotion_head_best.pt")
|
| 130 |
+
|
| 131 |
+
print(f"\nMejor val acc: {best_val_f1:.2%}")
|
| 132 |
+
|
| 133 |
+
model.load_state_dict(torch.load("emotion_head_best.pt"))
|
| 134 |
+
model.eval()
|
| 135 |
+
all_preds, all_labels = [], []
|
| 136 |
+
with torch.no_grad():
|
| 137 |
+
for features, labels in test_loader:
|
| 138 |
+
preds = model(features.to(device)).argmax(1).cpu()
|
| 139 |
+
all_preds.extend(preds.numpy())
|
| 140 |
+
all_labels.extend(labels.numpy())
|
| 141 |
+
|
| 142 |
+
print("\n=== RESULTADOS EN TEST SET ===")
|
| 143 |
+
print(classification_report(all_labels, all_preds, target_names=EMOTIONS))
|
| 144 |
+
|
| 145 |
+
cm = confusion_matrix(all_labels, all_preds)
|
| 146 |
+
plt.figure(figsize=(8, 6))
|
| 147 |
+
sns.heatmap(
|
| 148 |
+
cm, annot=True, fmt="d", xticklabels=EMOTIONS, yticklabels=EMOTIONS, cmap="Blues"
|
| 149 |
+
)
|
| 150 |
+
plt.title("Confusion matrix — EmotionHead")
|
| 151 |
+
plt.tight_layout()
|
| 152 |
+
plt.savefig("confusion_matrix.png", dpi=150)
|
| 153 |
+
print("Saved: confusion_matrix.png")
|
| 154 |
+
|
| 155 |
+
plt.figure(figsize=(8, 4))
|
| 156 |
+
plt.plot(history["train_loss"], label="train loss")
|
| 157 |
+
plt.plot(history["val_loss"], label="val loss")
|
| 158 |
+
plt.legend()
|
| 159 |
+
plt.title("Training curve")
|
| 160 |
+
plt.savefig("training_curve.png", dpi=150)
|
| 161 |
+
print("Saved: training_curve.png")
|
| 162 |
+
|
| 163 |
+
print("\nUploading emotion_head_best.pt to HuggingFace...")
|
| 164 |
+
api.upload_file(
|
| 165 |
+
path_or_fileobj="emotion_head_best.pt",
|
| 166 |
+
path_in_repo="emotion_head_best.pt",
|
| 167 |
+
repo_id="MrlolDev/voxtral-emotion-speech",
|
| 168 |
+
repo_type="dataset",
|
| 169 |
+
)
|
| 170 |
+
print("✅ emotion_head_best.pt uploaded")
|
| 171 |
+
|
| 172 |
+
print("\nUploading confusion_matrix.png to HuggingFace...")
|
| 173 |
+
api.upload_file(
|
| 174 |
+
path_or_fileobj="confusion_matrix.png",
|
| 175 |
+
path_in_repo="confusion_matrix.png",
|
| 176 |
+
repo_id="MrlolDev/voxtral-emotion-speech",
|
| 177 |
+
repo_type="dataset",
|
| 178 |
+
)
|
| 179 |
+
print("✅ confusion_matrix.png uploaded")
|
| 180 |
+
|
| 181 |
+
print("\nUploading training_curve.png to HuggingFace...")
|
| 182 |
+
api.upload_file(
|
| 183 |
+
path_or_fileobj="training_curve.png",
|
| 184 |
+
path_in_repo="training_curve.png",
|
| 185 |
+
repo_id="MrlolDev/voxtral-emotion-speech",
|
| 186 |
+
repo_type="dataset",
|
| 187 |
+
)
|
| 188 |
+
print("✅ training_curve.png subido")
|