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 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
| import os import csv import torch import torch.nn as nn import torch.optim as optim from torch.utils.data import Dataset, DataLoader, SubsetRandomSampler import numpy as np from tqdm import tqdm from sklearn.model_selection import KFold import multiprocessing import copy from datetime import datetime import matplotlib.pyplot as plt
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
MFCC_DIR = "/home/shan/workplace/24fall/Homework/AIAA-2205/hkustgz-aiaa-2205-hw-1-fall-2024/mfcc.tgz/mfcc" TRAINVAL_LABEL = "/home/shan/workplace/24fall/Homework/AIAA-2205/hkustgz-aiaa-2205-hw-1-fall-2024/labels/trainval.csv" TEST_LABEL = "/home/shan/workplace/24fall/Homework/AIAA-2205/hkustgz-aiaa-2205-hw-1-fall-2024/labels/test_for_student.label" MODEL_DIR = "/home/shan/workplace/24fall/Homework/AIAA-2205/hkustgz-aiaa-2205-hw-1-fall-2024/models" MAX_SEQ_LENGTH = 999 NUM_FOLDS = 10
class GRUClassifier(nn.Module): def __init__(self, input_size, hidden_size, num_layers, num_classes, dropout=0.5): super(GRUClassifier, self).__init__() self.hidden_size = hidden_size self.num_layers = num_layers self.gru = nn.GRU(input_size, hidden_size, num_layers, batch_first=True, dropout=dropout) self.fc = nn.Linear(hidden_size, num_classes)
def forward(self, x): h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device) out, _ = self.gru(x, h0) out = self.fc(out[:, -1, :]) return out
class MFCCDataset(Dataset): def __init__(self, label_file, mfcc_dir, is_test=False): self.mfcc_dir = mfcc_dir self.data = [] self.labels = []
with open(label_file, 'r') as f: if is_test: for line in f: video_id = line.strip().split('.')[0] self.data.append(video_id) else: reader = csv.reader(f) next(reader) for row in reader: video_id, label = row self.data.append(video_id) self.labels.append(int(label))
def __len__(self): return len(self.data)
def __getitem__(self, idx): video_id = self.data[idx] mfcc_file = os.path.join(self.mfcc_dir, f"{video_id}.mfcc.csv")
if not os.path.exists(mfcc_file): return None
with open(mfcc_file, 'r') as f: mfcc = np.array([list(map(float, line.strip().split(';'))) for line in f])
if mfcc.shape[0] < MAX_SEQ_LENGTH: pad_length = MAX_SEQ_LENGTH - mfcc.shape[0] mfcc = np.pad(mfcc, ((0, pad_length), (0, 0)), mode='constant') elif mfcc.shape[0] > MAX_SEQ_LENGTH: mfcc = mfcc[:MAX_SEQ_LENGTH, :]
mfcc_tensor = torch.FloatTensor(mfcc)
if len(self.labels) > 0: label = self.labels[idx] return mfcc_tensor, label else: return mfcc_tensor, video_id
def collate_fn(batch): batch = list(filter(lambda x: x is not None, batch)) return torch.utils.data.dataloader.default_collate(batch)
def train(model, train_loader, criterion, optimizer, epoch): model.train() total_loss = 0 correct = 0 total = 0
progress_bar = tqdm(train_loader, desc=f'Epoch {epoch}') for batch_idx, (inputs, targets) in enumerate(progress_bar): inputs, targets = inputs.to(device), targets.to(device) optimizer.zero_grad() outputs = model(inputs) loss = criterion(outputs, targets) loss.backward() optimizer.step()
total_loss += loss.item() _, predicted = outputs.max(1) total += targets.size(0) correct += predicted.eq(targets).sum().item()
progress_bar.set_postfix({ 'Loss': f'{total_loss/(batch_idx+1):.3f}', 'Acc': f'{100.*correct/total:.2f}%' })
return total_loss / len(train_loader), 100. * correct / total
def validate(model, val_loader, criterion): model.eval() total_loss = 0 correct = 0 total = 0
with torch.no_grad(): for inputs, targets in val_loader: inputs, targets = inputs.to(device), targets.to(device) outputs = model(inputs) loss = criterion(outputs, targets)
total_loss += loss.item() _, predicted = outputs.max(1) total += targets.size(0) correct += predicted.eq(targets).sum().item()
accuracy = 100. * correct / total average_loss = total_loss / len(val_loader) return average_loss, accuracy
def inference(model, test_loader): model.eval() predictions = {}
with torch.no_grad(): for inputs, video_ids in tqdm(test_loader, desc='Inference'): inputs = inputs.to(device) outputs = model(inputs) _, predicted = outputs.max(1)
for video_id, pred in zip(video_ids, predicted.cpu().numpy()): predictions[video_id] = int(pred)
return predictions
def plot_learning_curves(train_losses, val_losses, train_accs, val_accs, fold): plt.figure(figsize=(12, 5)) plt.subplot(1, 2, 1) plt.plot(train_losses, label='Train Loss') plt.plot(val_losses, label='Validation Loss') plt.title(f'Learning Curves - Loss (Fold {fold})') plt.xlabel('Epoch') plt.ylabel('Loss') plt.legend()
plt.subplot(1, 2, 2) plt.plot(train_accs, label='Train Accuracy') plt.plot(val_accs, label='Validation Accuracy') plt.title(f'Learning Curves - Accuracy (Fold {fold})') plt.xlabel('Epoch') plt.ylabel('Accuracy') plt.legend()
plt.tight_layout() plt.savefig(os.path.join(MODEL_DIR, f'learning_curves_fold{fold}.png')) plt.close()
def train_and_validate(fold, train_ids, val_ids, full_dataset, input_size, hidden_size, num_layers, num_classes): print(f'FOLD {fold}') print('--------------------------------')
train_subsampler = SubsetRandomSampler(train_ids) val_subsampler = SubsetRandomSampler(val_ids)
train_loader = DataLoader(full_dataset, batch_size=32, sampler=train_subsampler, collate_fn=collate_fn) val_loader = DataLoader(full_dataset, batch_size=32, sampler=val_subsampler, collate_fn=collate_fn)
model = GRUClassifier(input_size, hidden_size, num_layers, num_classes, dropout=0.5).to(device) criterion = nn.CrossEntropyLoss() optimizer = optim.Adam(model.parameters(), lr=0.001, weight_decay=1e-5)
num_epochs = 60 best_val_acc = 0 best_model = None patience = 20 no_improve = 0
train_losses, val_losses, train_accs, val_accs = [], [], [], []
start_saving = False
for epoch in range(1, num_epochs + 1): train_loss, train_acc = train(model, train_loader, criterion, optimizer, epoch) val_loss, val_acc = validate(model, val_loader, criterion)
train_losses.append(train_loss) val_losses.append(val_loss) train_accs.append(train_acc) val_accs.append(val_acc)
print(f'Epoch {epoch}: ' f'Train Loss: {train_loss:.4f}, Train Acc: {train_acc:.2f}%, ' f'Val Loss: {val_loss:.4f}, Val Acc: {val_acc:.2f}%' f'Fold {fold}')
if train_loss < 0.5: start_saving = True
if start_saving: if val_acc > best_val_acc: best_val_acc = val_acc best_model = copy.deepcopy(model) print('Model updated on fold {fold}, validation accuracy rises to {best_val_acc:.2f}%') no_improve = 0 else: no_improve += 1 if no_improve >= patience: print(f"Early stopping at epoch {epoch}") break
torch.save(best_model.state_dict(), os.path.join(MODEL_DIR, f'gru_model_fold{fold}.pth'))
plot_learning_curves(train_losses, val_losses, train_accs, val_accs, fold)
print(f'Best validation accuracy for fold {fold}: {best_val_acc:.2f}%') print('--------------------------------')
return best_val_acc, train_accs[-1], val_losses[-1], train_losses[-1]
def main(): full_dataset = MFCCDataset(TRAINVAL_LABEL, MFCC_DIR)
kfold = KFold(n_splits=NUM_FOLDS, shuffle=True, random_state=42)
input_size = 39 hidden_size = 256 num_layers = 2 num_classes = 10
with multiprocessing.Pool(processes=5) as pool: results = [] for fold, (train_ids, val_ids) in enumerate(kfold.split(full_dataset), 1): result = pool.apply_async(train_and_validate, (fold, train_ids, val_ids, full_dataset, input_size, hidden_size, num_layers, num_classes)) results.append(result)
best_models = [] for result in results: val_acc, train_acc, val_loss, train_loss = result.get() best_models.append((fold, val_acc, train_acc, val_loss, train_loss))
best_model = max(best_models, key=lambda x: x[1] - abs(x[1] - x[2]) - x[3]) print(f"Selected model from fold {best_model[0]} with val_acc {best_model[1]:.2f}%")
test_dataset = MFCCDataset(TEST_LABEL, MFCC_DIR, is_test=True) test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False, collate_fn=collate_fn)
ensemble_predictions = {} for fold in range(1, NUM_FOLDS + 1): model = GRUClassifier(input_size, hidden_size, num_layers, num_classes, dropout=0.5).to(device) model.load_state_dict(torch.load(os.path.join(MODEL_DIR, f'gru_model_fold{fold}.pth'))) fold_predictions = inference(model, test_loader)
for video_id, pred in fold_predictions.items(): if video_id not in ensemble_predictions: ensemble_predictions[video_id] = [] ensemble_predictions[video_id].append(pred)
final_predictions = {video_id: max(set(preds), key=preds.count) for video_id, preds in ensemble_predictions.items()}
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") output_file = os.path.join(MODEL_DIR, f'test_predictions_{timestamp}_GRU2.csv')
with open(output_file, 'w', newline='') as f: writer = csv.writer(f) writer.writerow(['Id', 'Category']) for video_id, label in final_predictions.items(): writer.writerow([f"{video_id}", label])
print(f"Predictions saved to {output_file}")
if __name__ == "__main__": multiprocessing.set_start_method('spawn') main()
|