Run the style transfer.
(cnn, normalization_mean, normalization_std,
content_img, style_img, input_img, num_steps=300,
style_weight=1000000, content_weight=1)
| 412 | # |
| 413 | |
| 414 | def run_style_transfer(cnn, normalization_mean, normalization_std, |
| 415 | content_img, style_img, input_img, num_steps=300, |
| 416 | style_weight=1000000, content_weight=1): |
| 417 | """Run the style transfer.""" |
| 418 | print('Building the style transfer model..') |
| 419 | model, style_losses, content_losses = get_style_model_and_losses(cnn, |
| 420 | normalization_mean, normalization_std, style_img, content_img) |
| 421 | |
| 422 | # We want to optimize the input and not the model parameters so we |
| 423 | # update all the requires_grad fields accordingly |
| 424 | input_img.requires_grad_(True) |
| 425 | # We also put the model in evaluation mode, so that specific layers |
| 426 | # such as dropout or batch normalization layers behave correctly. |
| 427 | model.eval() |
| 428 | model.requires_grad_(False) |
| 429 | |
| 430 | optimizer = get_input_optimizer(input_img) |
| 431 | |
| 432 | print('Optimizing..') |
| 433 | run = [0] |
| 434 | while run[0] <= num_steps: |
| 435 | |
| 436 | def closure(): |
| 437 | # correct the values of updated input image |
| 438 | with torch.no_grad(): |
| 439 | input_img.clamp_(0, 1) |
| 440 | |
| 441 | optimizer.zero_grad() |
| 442 | model(input_img) |
| 443 | style_score = 0 |
| 444 | content_score = 0 |
| 445 | |
| 446 | for sl in style_losses: |
| 447 | style_score += sl.loss |
| 448 | for cl in content_losses: |
| 449 | content_score += cl.loss |
| 450 | |
| 451 | style_score *= style_weight |
| 452 | content_score *= content_weight |
| 453 | |
| 454 | loss = style_score + content_score |
| 455 | loss.backward() |
| 456 | |
| 457 | run[0] += 1 |
| 458 | if run[0] % 50 == 0: |
| 459 | print("run {}:".format(run)) |
| 460 | print('Style Loss : {:4f} Content Loss: {:4f}'.format( |
| 461 | style_score.item(), content_score.item())) |
| 462 | print() |
| 463 | |
| 464 | return style_score + content_score |
| 465 | |
| 466 | optimizer.step(closure) |
| 467 | |
| 468 | # a last correction... |
| 469 | with torch.no_grad(): |
| 470 | input_img.clamp_(0, 1) |
| 471 |
no test coverage detected