def __call__(self, image, style_name):
        """
        Deep Dream Main Algorithm.
        Passes the given image through the model and uses the
        Gradient Ascent Method to update the image.
        """
        # prepare style
        style = self.cfg.STYLES_CFG[style_name]
        logger.info(f'Running deep dream algorithm using style: {style_name}')

        # prepare model
        model = DeepGoogLeNet(loi=style.loi)
        model.eval()

        # prepare input image
        try:
            original_size = image.size
            image = image.resize((style.size, style.size))
            target = utils.preprocess(image).to(self.device)
        except Exception:
            raise PreProcessingError()

        start = time()
        for e in range(style.epochs):
            # reset gradient
            if target.grad is not None:
                target.grad.zero_()

            # loss backward
            loss = self.deep_dream_loss(model, target)
            loss.backward(retain_graph=True)

            # gradient ascent step (standarizing the gradient)
            grad = target.grad.data / (torch.std(target.grad.data) + 1e-8)
            target.data = target.data + grad * style.learning_rate

            # clip pixel values
            target.data = utils.clip(target.data)

            logger.debug(f'Epoch {e}/{style.epochs} '
                         f'took: {time() - start:.2f}')

        logger.info('Deep Dream with style: '
                    f'{style_name} took: {time() - start:.2f}')

        try:
            dream = target.cpu().clone().detach().squeeze(0)
            dream = utils.postprocess(dream).resize(original_size)
        except Exception:
            raise PostProcessingError()

        return dream
Exemple #2
0
    def test_feature_extraction_count(self):
        model = DeepGoogLeNet((2, 4))
        inp = torch.randn(1, 3, 256, 256)
        _ = model(inp)

        assert len(model.features) == 2, 'Incorrect feature count'
Exemple #3
0
 def test_init_loi_interpretation(self):
     model = DeepGoogLeNet((2, 4))
     assert len(model.hooks) == 2, 'Incorrect hook count'
     assert len(model.layers) == 4, 'Incorrect layer count'
Exemple #4
0
 def test_init_over_b(self):
     self.assertRaises(ModelInitializationError,
                       lambda: DeepGoogLeNet((1, 17)))
Exemple #5
0
 def test_init_neg_a(self):
     self.assertRaises(ModelInitializationError,
                       lambda: DeepGoogLeNet((-1, 9)))
Exemple #6
0
 def test_init(self):
     self.assertNotRaise(lambda: DeepGoogLeNet((0, 4)),
                         'Model Initalization failed')