Learn on a batch of training_data for a specified number of iterations and reporting thresholds
(rnn, training_data, n_epoch = 10, n_batch_size = 64, report_every = 50, learning_rate = 0.2, criterion = nn.NLLLoss())
| 297 | import numpy as np |
| 298 | |
| 299 | def train(rnn, training_data, n_epoch = 10, n_batch_size = 64, report_every = 50, learning_rate = 0.2, criterion = nn.NLLLoss()): |
| 300 | """ |
| 301 | Learn on a batch of training_data for a specified number of iterations and reporting thresholds |
| 302 | """ |
| 303 | # Keep track of losses for plotting |
| 304 | current_loss = 0 |
| 305 | all_losses = [] |
| 306 | rnn.train() |
| 307 | optimizer = torch.optim.SGD(rnn.parameters(), lr=learning_rate) |
| 308 | |
| 309 | start = time.time() |
| 310 | print(f"training on data set with n = {len(training_data)}") |
| 311 | |
| 312 | for iter in range(1, n_epoch + 1): |
| 313 | rnn.zero_grad() # clear the gradients |
| 314 | |
| 315 | # create some minibatches |
| 316 | # we cannot use dataloaders because each of our names is a different length |
| 317 | batches = list(range(len(training_data))) |
| 318 | random.shuffle(batches) |
| 319 | batches = np.array_split(batches, len(batches) //n_batch_size ) |
| 320 | |
| 321 | for idx, batch in enumerate(batches): |
| 322 | batch_loss = 0 |
| 323 | for i in batch: #for each example in this batch |
| 324 | (label_tensor, text_tensor, label, text) = training_data[i] |
| 325 | output = rnn.forward(text_tensor) |
| 326 | loss = criterion(output, label_tensor) |
| 327 | batch_loss += loss |
| 328 | |
| 329 | # optimize parameters |
| 330 | batch_loss.backward() |
| 331 | nn.utils.clip_grad_norm_(rnn.parameters(), 3) |
| 332 | optimizer.step() |
| 333 | optimizer.zero_grad() |
| 334 | |
| 335 | current_loss += batch_loss.item() / len(batch) |
| 336 | |
| 337 | all_losses.append(current_loss / len(batches) ) |
| 338 | if iter % report_every == 0: |
| 339 | print(f"{iter} ({iter / n_epoch:.0%}): \t average batch loss = {all_losses[-1]}") |
| 340 | current_loss = 0 |
| 341 | |
| 342 | return all_losses |
| 343 | |
| 344 | ########################################################################## |
| 345 | # We can now train a dataset with minibatches for a specified number of epochs. The number of epochs for this |
no test coverage detected