Git Product home page Git Product logo

keras-adversarial's Introduction

Keras Adversarial Models

Combine multiple models into a single Keras model. GANs made easy!

AdversarialModel simulates multi-player games. A single call to model.fit takes targets for each player and updates all of the players. Use AdversarialOptimizer for complete control of whether updates are simultaneous, alternating, or something else entirely. No more fooling with Trainable either!

Installation

git clone https://github.com/bstriner/keras_adversarial.git
cd keras_adversarial
python setup.py install

Usage

Please check the examples folder for exemplary usage.

Instantiating an adversarial model

  • Build separate models for each component / player such as generator and discriminator.
  • Build a combined model. For a GAN, this might have an input for images and an input for noise and an output for D(fake) and an output for D(real)
  • Pass the combined model and the separate models to the AdversarialModel constructor
adversarial_model = AdversarialModel(base_model=gan,
  player_params=[generator.trainable_weights, discriminator.trainable_weights],
  player_names=["generator", "discriminator"])

The resulting model will have the same inputs as gan but separate targets and metrics for each player. This is accomplished by copying the model for each player. If each player has a different model, use player_models (see below regarding dropout).

adversarial_model = AdversarialModel(player_models=[gan_g, gan_d],
  player_params=[generator.trainable_weights, discriminator.trainable_weights],
  player_names=["generator", "discriminator"])

Compiling an adversarial model

Use adversarial_compile to compile the model. The parameters are an AdversarialOptimizer and a list of Optimizer objects for each player. The loss is passed to model.compile for each model, so may be a dictionary or other object. Use the same order for player_optimizers as you did for player_params and player_names.

model.adversarial_compile(adversarial_optimizer=adversarial_optimizer,
  player_optimizers=[Adam(1e-4, decay=1e-4), Adam(1e-3, decay=1e-4)],
  loss='binary_crossentropy')

Training a simple adversarial model

Adversarial models can be trained using fit and callbacks just like any other Keras model. Just make sure to provide the correct targets in the correct order.

For example, given simple GAN named gan:

  • Inputs: [x]
  • Targets: [y_fake, y_real]
  • Metrics: [loss, loss_y_fake, loss_y_real]

AdversarialModel(base_model=gan, player_names=['g', 'd']...) will have:

  • Inputs: [x]
  • Targets: [g_y_fake, g_y_real, d_y_fake, d_y_real]
  • Metrics: [loss, g_loss, g_loss_y_fake, g_loss_y_real, d_loss, d_loss_y_fake, d_loss_y_real]

Adversarial Optimizers

There are many possible strategies for optimizing multiplayer games. AdversarialOptimizer is a base class that abstracts those strategies and is responsible for creating the training function.

  • AdversarialOptimizerSimultaneous updates each player simultaneously on each batch.
  • AdversarialOptimizerAlternating updates each player in a round-robin. Take each batch and run that batch through each of the models. All models are trained on each batch.
  • AdversarialOptimizerScheduled passes each batch to a different player according to a schedule. [1,1,0] would mean train player 1 on batches 0,1,3,4,6,7,etc. and train player 0 on batches 2,5,8,etc.
  • UnrolledAdversarialOptimizer unrolls updates to stabilize training (only tested in Theano; slow to build graph but runs reasonably fast)

Examples

MNIST Generative Adversarial Network (GAN)

example_gan.py shows how to create a GAN in Keras for the MNIST dataset.

Example GAN

Example GAN

CIFAR10 Generative Adversarial Network (GAN)

example_gan_cifar10.py shows how to create a GAN in Keras for the CIFAR10 dataset.

Example GAN

Example GAN

MNIST Bi-Directional Generative Adversarial Network (BiGAN)

example_bigan.py shows how to create a BiGAN in Keras.

Example BiGAN

Example BiGAN

MNIST Adversarial Autoencoder (AAE)

An AAE is like a cross between a GAN and a Variational Autoencoder (VAE). example_aae.py shows how to create an AAE in Keras.

Example AAE

Example AAE

Unrolled Generative Adversarial Network

example_gan_unrolled.py shows how to use the unrolled optimizer.

WARNING: Unrolling the discriminator 8 times takes about 6 hours to build the function on my computer, but only a few minutes for epoch of training. Be prepared to let it run a long time or turn the depth down to around 4.

Notes

Dropout

When training adversarial models using dropout, you may want to create separate models for each player.

If you want to train a discriminator with dropout, but train the generator against the discriminator without dropout, create two models. * GAN to train generator: D(G(z, dropout=0.5), dropout=0) * GAN to train discriminator: D(G(z, dropout=0), dropout=0.5)

If you create separate models, use player_models parameter of AdversarialModel constructor.

If you aren't using dropout, one model is sufficient, and use base_model parameter of AdversarialModel constructor, which will duplicate the base_model for each player.

Theano and Tensorflow

I do most of my development in theano but try to test tensorflow when I have extra time. The goal is to support both. Please let me know any issues you have with either backend.

Questions?

Feel free to start an issue or a PR here or in Keras if you are having any issues or think of something that might be useful.

keras-adversarial's People

Contributors

bstriner avatar d4nst avatar github-bot-bot avatar isaacmg avatar jskdr avatar mnill avatar musella avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

keras-adversarial's Issues

python example_gan.py --> ModuleNotFoundError: No module named 'keras_adversarial.legacy'

Hello,

I have no clue why I get the following error when I am executing: python example_gan.py

Using TensorFlow backend.
Traceback (most recent call last):
  File "example_gan.py", line 16, in <module>
    from keras_adversarial.legacy import l1l2, Dense, fit
ModuleNotFoundError: No module named 'keras_adversarial.legacy'

I cloned your repo and executed setup.py. The file legacy.py is also in the right folder. Has anybody a suggestion what I can do to fix it?

Thanks in advance!

problem with example_gan_cifar10.py

I get the following error when I try to run the code:

main()
Traceback (most recent call last):

File "", line 1, in
main()

File "", line 137, in main
generator = model_generator()

File "", line 33, in model_generator
model.add(Convolution2D(nch / 2, h, h, border_mode='same', W_regularizer=reg()))

File "C:\Users\M543015\AppData\Local\Continuum\Anaconda3\lib\site-packages\keras\models.py", line 476, in add
output_tensor = layer(self.outputs[0])

File "C:\Users\M543015\AppData\Local\Continuum\Anaconda3\lib\site-packages\keras\engine\topology.py", line 569, in call
self.build(input_shapes[0])

File "C:\Users\M543015\AppData\Local\Continuum\Anaconda3\lib\site-packages\keras\layers\convolutional.py", line 134, in build
constraint=self.kernel_constraint)

File "C:\Users\M543015\AppData\Local\Continuum\Anaconda3\lib\site-packages\keras\legacy\interfaces.py", line 88, in wrapper
return func(*args, **kwargs)

File "C:\Users\M543015\AppData\Local\Continuum\Anaconda3\lib\site-packages\keras\engine\topology.py", line 391, in add_weight
weight = K.variable(initializer(shape), dtype=dtype, name=name)

File "C:\Users\M543015\AppData\Local\Continuum\Anaconda3\lib\site-packages\keras\initializers.py", line 208, in call
dtype=dtype, seed=self.seed)

File "C:\Users\M543015\AppData\Local\Continuum\Anaconda3\lib\site-packages\keras\backend\theano_backend.py", line 2123, in random_uniform
return rng.uniform(shape, low=minval, high=maxval, dtype=dtype)

File "C:\Users\M543015\AppData\Local\Continuum\Anaconda3\lib\site-packages\theano\sandbox\rng_mrg.py", line 1339, in uniform
for i in size]), msg

AssertionError: size must be a tuple of int or a Theano variable

Is this an issue somehow related to versioning, or to choice of backend?

AttributeError: 'Model' object has no attribute 'internal_input_shapes'

I am using Python 3.6 and install keras_adversarial with the master branch, it seems that Model has no attribute 'internal_input_shapes' BUT '_internal_input_shapes'. Also Model has no attribute 'internal_output_shapes' either.

Traceback (most recent call last):
File "example_gan.py", line 118, in
main()
File "example_gan.py", line 114, in main
latent_dim=latent_dim)
File "example_gan.py", line 71, in example_gan
loss=loss)
File "/Users/leo/Applications/anaconda3/lib/python3.6/site-packages/keras_adversarial-0.0.3-py3.6.egg/keras_adversarial/adversarial_model.py", line 91, in adversarial_compile
AttributeError: 'Model' object has no attribute 'internal_input_shapes'

I wrote the TensorFlow version of your work in Keras.

I wrote it yesterday, and today I came across your repo so just wanna let you know.

Here's the description: https://ctmakro.github.io/site/on_learning/fast_gan_in_keras.html
w/ code inside.

However I didn't make it into a class.

Oh and, your DCGAN implementation seems to have diversity problem(a lot of the generations are exactly the same). you should 1) single-sided label smoothing 2) add decaying noise to input 3) use batch discrimination.

No module named 'image_utils'

Hi,

I m using Python 3.5.2, Keras 2, Pillow 4.1. When I run 'from image_utils import...'. It shows 'No module named 'image_utils''. I cannot find any answers on the net. Can you help out?

Thanks
Tao

Keras 2 issues

Hi everybody! Just letting you know there are probably a lot of new issues with the change to Keras 2. Will update the library soon and keep you all posted.

Cheers!

ImportError: No module named graph_editor

Hi,

I just installed keras-adversarial, and tried to run the MNIST example. I got this error:

Using TensorFlow backend.
/usr/local/lib/python2.7/dist-packages/sklearn/cross_validation.py:44: Deprecation Warning: This module was deprecated in version 0.18 in favor of the model_sele                 ction module into which all the refactored classes and functions are moved. Also note that the interface of the new CV iterators are different from that of this                  module. This module will be removed in 0.20.
  "This module will be removed in 0.20.", DeprecationWarning)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "build/bdist.linux-x86_64/egg/keras_adversarial/__init__.py", line 1, in                  <module>
  File "build/bdist.linux-x86_64/egg/keras_adversarial/adversarial_model.py", li                 ne 8, in <module>
  File "build/bdist.linux-x86_64/egg/keras_adversarial/adversarial_utils.py", li                 ne 7, in <module>
  File "build/bdist.linux-x86_64/egg/keras_adversarial/backend/__init__.py", lin                 e 4, in <module>
  File "build/bdist.linux-x86_64/egg/keras_adversarial/backend/tensorflow_backen                 d.py", line 3, in <module>
ImportError: No module named graph_editor

Do you know what this graph_editor module is?

Running on Bash on Windows 10.

Typo in AAE example

I have reviewed paper https://arxiv.org/pdf/1511.05644.pdf and it looks like there is a typo in the AAE example generator and encoder variables names. According to the paper:

The generator of the adversarial network is also the encoder of the autoencoder q(z|x).

In the example, generator is decoder(see example code). Looks that it is only named typo and there are no other issues except confusion when you face with this.

AdversarialOptimizerAlternating

Hi Ben,

I just want to clarify something:
Does AdversarialOptimizerAlternating essentially mean constructing different mini-batches for real and fake?

On a side note -- not sure if you have come across this, but heres a nice summary of tips and tricks for training GANS:
https://github.com/soumith/ganhacks

Best,
Stephen

example_gan.py does not work with tensorflow backend

Running example_gan.py from the latest commit f87ace5 leads to the following error when using the tensorflow backend:

Traceback (most recent call last):
  File "example_gan.py", line 142, in <module>
    main()
  File "example_gan.py", line 138, in main
    latent_dim=latent_dim)
  File "example_gan.py", line 114, in example_gan
    batch_size=32)
  File "[...]/.local/lib/python2.7/site-packages/Keras-1.2.0-py2.7.egg/keras/engine/training.py", line 1115, in fit
    self._make_train_function()
  File "[...]/projects/keras_adversarial/keras_adversarial/adversarial_model.py", line 148, in _make_train_function
    self.updates,
  File "[...]/projects/keras_adversarial/keras_adversarial/adversarial_model.py", line 122, in updates
    return merge_updates(list(itertools.chain.from_iterable(model.updates for model in self.layers)))
  File "[...]/projects/keras_adversarial/keras_adversarial/adversarial_utils.py", line 133, in merge_updates
    for k, v in updates:
  File "[...]/.local/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 510, in __iter__
    raise TypeError("'Tensor' object is not iterable.")
TypeError: 'Tensor' object is not iterable.

The problem is visible since 67e2c07, where batch_norm_mode was changed. The code causing the problems was already added earlier in 1a4cd70. The newly added function merge_updates assumes that the updates are tuples, but for Tensorflow they are operations. Something like the following change should fix it (similar to how its done in unrolled_optimizer.py):

@@ -126,11 +126,19 @@ def uniform_latent_sampling(latent_shape, low=0.0, high=1.0):
 def n_choice(x, n):
     return x[np.random.choice(x.shape[0], size=n, replace=False)]
 
+if K.backend() == "tensorflow":
+    def unpack_assignment(a):
+        return a.op.inputs[0], a.op.inputs[1]
+
+else:
+    def unpack_assignment(a):
+        return a
 
 def merge_updates(updates):
     """Average repeated updates of the same variable"""
     upd = {}
-    for k, v in updates:
+    for kv in updates:
+        k, v = unpack_assignment(kv)
         if k not in upd:
             upd[k] = []
         upd[k].append(v)

Tested with tensorflow 0.12.1 and keras 1.2.0. If you need any additional information, please let me know.

Takes a lot of time while providing Imagegridcallback callback in training

Hi, I used one your function Imagegridcallback for visualization of images on every epoch, I set batch size of 16 and I have 739 image, but when it comes to last batch in every epoch , the process will going to be very slow , means after 736 images the training stops for a while(possibly due to callback of imagegrid ) and then completed and go to next epoch ,
can you optimize imagegridcallbback so it will not take time while generating images on every epoch ?
and if possible can I visualize those epoch images after training ? if yes then how ?

cifar_gan_example10.py input shape

When attempting to use the example_gan_cifar10.py I'm getting the following error message
ValueError: Error when checking input: expected conv2d_5_input to have shape (None, 32, 32, 3) but got array with shape (50000, 32, 3, 32)
I'm using the most recent version of Keras 2.04 and Python 3.6. Prior to this running at all I also had to cast all the floats to ints.

'Model' object has no attribute 'constraints'

Hey, I was working through this tutorial: https://www.analyticsvidhya.com/blog/2017/06/introductory-generative-adversarial-networks-gans/.

I'm trying to implement a simple GAN with the following code:
gan = simple_gan(model_1, model_2, normal_latent_sampling((100,)))

model = AdversarialModel(base_model=gan,
player_params=[model_1.trainable_weights, model_2.trainable_weights])

model.adversarial_compile(adversarial_optimizer=AdversarialOptimizerSimultaneous(),
player_optimizers=['adam', 'adam'],
loss='binary_crossentropy')

history = model.fit(x=train,
y=gan_targets(train.shape[0]),
epochs=10,
batch_size=batch_size)

However, I get this error:


AttributeError Traceback (most recent call last)
in ()
11 y=gan_targets(train.shape[0]),
12 epochs=10,
---> 13 batch_size=batch_size)

/anaconda/envs/py27/lib/python2.7/site-packages/keras/engine/training.pyc in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, **kwargs)
1573 else:
1574 ins = x + y + sample_weights
-> 1575 self._make_train_function()
1576 f = self.train_function
1577

/anaconda/envs/py27/lib/python2.7/site-packages/keras_adversarial-0.0.3-py2.7.egg/keras_adversarial/adversarial_model.pyc in _make_train_function(self)
159 self.optimizers,
160 [model.constraints for model in
--> 161 self.layers],
162 self.updates,
163 self._function_kwargs)

AttributeError: 'Model' object has no attribute 'constraints'

I'm thinking it might be an incompatibility between versions? I've tried a number of different tutorials and I always get this error while trying to call fit.

I've tried switching between Python 2 and 3; both use Tensorflow 1.3.0 and keras 2.0.8.

If I could get any help on what is causing this error it would be great :)

Cannot use lambda x: x[0] as output shape in BiGAN

The line
z = merge([mu, log_sigma_sq], mode=lambda p: p[0] + K.random_normal(p[0].shape) * K.exp(p[1] / 2),output_shape=lambda x: x[0])

is throwing the following error

File "exampleBiGan.py", line 97, in example_bigan encoder = model_encoder(latent_dim, input_shape) File "exampleBiGan.py", line 51, in model_encoder output_shape=lambda x: x[0]) File "/home/gardij/tensorflow/tf1/lib/python3.4/site-packages/keras/legacy/layers.py", line 460, in merge name=name) File "/home/gardij/tensorflow/tf1/lib/python3.4/site-packages/keras/legacy/layers.py", line 121, in __init__ self(input_tensors, mask=input_masks) File "/home/gardij/tensorflow/tf1/lib/python3.4/site-packages/keras/engine/topology.py", line 596, in __call__ output = self.call(inputs, **kwargs) File "/home/gardij/tensorflow/tf1/lib/python3.4/site-packages/keras/legacy/layers.py", line 203, in call return self.mode(inputs, **arguments) File "exampleBiGan.py", line 50, in <lambda> z = merge([mu, log_sigma_sq], mode=lambda p: p[0] + K.random_normal(p[0].shape) * K.exp(p[1] / 2), File "/home/gardij/tensorflow/tf1/lib/python3.4/site-packages/keras/backend/tensorflow_backend.py", line 3423, in random_normal dtype=dtype, seed=seed) File "/home/gardij/tensorflow/tf1/lib/python3.4/site-packages/tensorflow/python/ops/random_ops.py", line 71, in random_normal shape_tensor = _ShapeTensor(shape) File "/home/gardij/tensorflow/tf1/lib/python3.4/site-packages/tensorflow/python/ops/random_ops.py", line 42, in _ShapeTensor return ops.convert_to_tensor(shape, dtype=dtype, name="shape") File "/home/gardij/tensorflow/tf1/lib/python3.4/site-packages/tensorflow/python/framework/ops.py", line 676, in convert_to_tensor as_ref=False) File "/home/gardij/tensorflow/tf1/lib/python3.4/site-packages/tensorflow/python/framework/ops.py", line 741, in internal_convert_to_tensor ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref) File "/home/gardij/tensorflow/tf1/lib/python3.4/site-packages/tensorflow/python/framework/constant_op.py", line 131, in _tensor_shape_tensor_conversion_function "Cannot convert a partially known TensorShape to a Tensor: %s" % s) ValueError: Cannot convert a partially known TensorShape to a Tensor: (?, 25)

This error is found in the model_encoder definition for the BiGAN example code.

Thanks for any advice on this issue.

Question - no MINIST labels passed in training?

Hi there,

@bstriner this is a great package with powerful and comprehensive examples! Really enjoy working with it!

Quick question, something that I tried to understand from the source, looking at the simplest gan example in examples/example_gan.py

    xtrain, xtest = mnist_data()
    y = targets(xtrain.shape[0])
    ytest = targets(xtest.shape[0])

xtrain and xtest are what I expect them to be (-1,28,28) batches of data
However y and ytest are just tuples (of length 4) filled with 0 or 1 by gan_targets -- I was expecting those to be the true MINIST labels?

Sort of like in this example https://github.com/fchollet/keras/blob/master/examples/mnist_cnn.py

(x_train, y_train), (x_test, y_test) = mnist.load_data()

Maybe this is just me not getting something here about GANs, or maybe other users have similar questions.

Arbitrary Loss

Hi,
Is it possible to define arbitrary loss in the G and D part to get GANs such as WGAN, Least Square GAN, Boundary Seeking GAN, etc?

'AdversarialModel' object has no attribute 'nodes_by_depth'

I tried using this module and got following error:
'AdversarialModel' object has no attribute 'nodes_by_depth'

The stack traceback is :

Traceback (most recent call last):
File "/home/sukhad/Workspace/PyCharm/GAN/main.py", line 66, in
print(model.summary())
File "/home/sukhad/env/lib/python3.5/site-packages/keras/engine/topology.py", line 2708, in summary
print_fn=print_fn)
File "/home/sukhad/env/lib/python3.5/site-packages/keras/utils/layer_utils.py", line 39, in print_summary
nodes_by_depth = model.nodes_by_depth.values()
AttributeError: 'AdversarialModel' object has no attribute 'nodes_by_depth'

Any idea about how to solve to this issue?
Thanks.

Issues with Keras 2.2.0

It seems that there are some issues with the latest version of Keras 2.2.0

I try to use keras-adversarial with kears 2.2.0 but it doesen't work.

Traceback (most recent call last):
File "example_gan_convolutional.py", line 109, in <module>
player_names=["generator", "discriminator"])
File "C:\Users\MasayaOgushi\Anaconda3\envs\deep-learning-keras\lib\site-packages\keras_adversarial\adversarial_model.py", line 47, in init
self.layers = []
File "C:\Users\MasayaOgushi\Anaconda3\envs\deep-learning-keras\lib\site-packages\keras\engine\network.py", line 323, in setattr
super(Network, self).setattr(name, value)
AttributeError: can't set attribute

Any help? is this going to be fixed? Thanks

Conditional example_gan.py

Hi,

I am trying to do a version of example_gan.py in which both generator and discriminator admit a label that tells which number to generate/identify. This requires the the label to be untouched when the input is passed through eliminate_z. I thought of the following modification:

def eliminate_z(gan, latent_sampling, label_dim):
    """
    Eliminate z from GAN using latent_sampling
    :param gan: model with 2 inputs: z, x
    :param latent_sampling: layer that samples z with same batch size as x
    :return: Model x -> gan(latent_sampling(x), x)
    """
    x = gan.inputs[1]
    l = x[:,-label_dim:]
    z = concatenate([latent_sampling(x), l])
    model = Model(inputs=x, outputs=fix_names(gan([z, x]), gan.output_names), name=gan.name)
    return model

However, when running the following example (which is in essence example_gan.py with the modifications needed to do a conditional GAN)

import numpy as np
import os
from keras.layers import Reshape, Flatten, LeakyReLU, Activation, concatenate, Input, Lambda, Concatenate
from keras.models import Sequential, Model
from keras.optimizers import Adam, SGD
from keras.callbacks import TensorBoard
from keras.utils import to_categorical
from keras_adversarial.image_grid_callback import ImageGridCallback
from keras_adversarial import AdversarialModel, simple_gan, gan_targets
from keras_adversarial import normal_latent_sampling, AdversarialOptimizerSimultaneous
from keras_adversarial.legacy import l1l2, Dense, fit
import keras.backend as K
from keras.datasets import mnist

def model_generator(latent_dim, label_dim, image_shape, hidden_dim=1024, reg=lambda: l1l2(1e-5, 1e-5)):
    inputs = (Input(shape=(latent_dim + label_dim,), name='generator_input'))
    y = (Lambda(lambda x: x[:,-label_dim:], output_shape=(label_dim,)))(inputs)
    T = (Dense(int(hidden_dim / 4), name="generator_h1", W_regularizer=reg()))(inputs)
    T = (LeakyReLU(0.2))(T)
    T = (Dense(int(hidden_dim / 2), name="generator_h2", W_regularizer=reg()))(T)
    T = (LeakyReLU(0.2))(T)
    T = (Dense(hidden_dim, name="generator_h3", W_regularizer=reg()))(T)
    T = (LeakyReLU(0.2))(T)
    T = (Dense(np.prod(image_shape), name="generator_x_flat", W_regularizer=reg()))(T)
    T = (Activation('sigmoid'))(T)
    T = concatenate([T, y])    
    model = Model(inputs=inputs, outputs=T, name="generator")
    return model

def model_discriminator(imagepluslabel_shape, hidden_dim=1024, reg=lambda: l1l2(1e-5, 1e-5), output_activation="sigmoid"):
    inputs = (Input(shape=imagepluslabel_shape, name='discriminator_input'))
    T = (Dense(hidden_dim, name="discriminator_h1", W_regularizer=reg()))(inputs)
    T = (LeakyReLU(0.2))(T)
    T = (Dense(int(hidden_dim / 2), name="discriminator_h2", W_regularizer=reg()))(T)
    T = (LeakyReLU(0.2))(T)
    T = (Dense(int(hidden_dim / 4), name="discriminator_h3", W_regularizer=reg()))(T)
    T = (LeakyReLU(0.2))(T)
    T = (Dense(1, name="discriminator_y", W_regularizer=reg()))(T)
    T = (Activation(output_activation))(T)
    model = Model(inputs=inputs, outputs=T, name="discriminator")
    return model

def eliminate_z(gan, latent_sampling, label_dim):
    """
    Eliminate z from GAN using latent_sampling
    :param gan: model with 2 inputs: z, x
    :param latent_sampling: layer that samples z with same batch size as x
    :return: Model x -> gan(latent_sampling(x), x)
    """
    x = gan.inputs[1]
    l = x[:,-label_dim:]
    z = concatenate([latent_sampling(x), l])
    model = Model(inputs=x, outputs=fix_names(gan([z, x]), gan.output_names), name=gan.name)
    return model

def simple_gan(generator, discriminator, latent_sampling, label_dim):
    # build basic gan
    gan = build_gan(generator, discriminator)
    # generate z on gpu, eliminate one input
    if latent_sampling is None:
        return gan
    else:
        return eliminate_z(gan, latent_sampling, label_dim)

# z \in R^100
latent_dim = 100
# x \in R^{28x28}
image_shape = (int(28 * 28),)
# label in R^10
label_dim = 10

imagepluslabel_shape = (int(28 * 28 + label_dim),)
# generator ((z,l) -> (x,l))
generator = model_generator(latent_dim, label_dim, image_shape)
# discriminator ((x,l) -> y)
discriminator = model_discriminator(imagepluslabel_shape)
simple_gan(generator, discriminator, normal_latent_sampling((latent_dim,)), label_dim)

I get the following error:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-40-432f035f7981> in <module>()
----> 1 simple_gan(generator, discriminator, normal_latent_sampling((latent_dim,)), label_dim)

<ipython-input-38-20b3c0a977c6> in simple_gan(generator, discriminator, latent_sampling, label_dim)
     34         return gan
     35     else:
---> 36         return eliminate_z(gan, latent_sampling, label_dim)
     37 
     38 

<ipython-input-38-20b3c0a977c6> in eliminate_z(gan, latent_sampling, label_dim)
     23     l = x[:,-label_dim:]
     24     z = concatenate([latent_sampling(x), l])
---> 25     model = Model(inputs=x, outputs=fix_names(gan([z, x]), gan.output_names), name=gan.name)
     26     return model
     27 

c:\python\python35\lib\site-packages\keras\legacy\interfaces.py in wrapper(*args, **kwargs)
     86                 warnings.warn('Update your `' + object_name +
     87                               '` call to the Keras 2 API: ' + signature, stacklevel=2)
---> 88             return func(*args, **kwargs)
     89         wrapper._legacy_support_signature = inspect.getargspec(func)
     90         return wrapper

c:\python\python35\lib\site-packages\keras\engine\topology.py in __init__(self, inputs, outputs, name)
   1652         for x in self.outputs:
   1653             seen_nodes = set()
-> 1654             build_map_of_graph(x, seen_nodes, depth=0)
   1655 
   1656         # Build a dict {depth: list of nodes with this depth}

c:\python\python35\lib\site-packages\keras\engine\topology.py in build_map_of_graph(tensor, seen_nodes, depth, layer, node_index, tensor_index)
   1648                 if node_marker not in seen_nodes:
   1649                     build_map_of_graph(x, seen_nodes, current_depth + 1,
-> 1650                                        layer, node_index, tensor_index)
   1651 
   1652         for x in self.outputs:

c:\python\python35\lib\site-packages\keras\engine\topology.py in build_map_of_graph(tensor, seen_nodes, depth, layer, node_index, tensor_index)
   1648                 if node_marker not in seen_nodes:
   1649                     build_map_of_graph(x, seen_nodes, current_depth + 1,
-> 1650                                        layer, node_index, tensor_index)
   1651 
   1652         for x in self.outputs:

c:\python\python35\lib\site-packages\keras\engine\topology.py in build_map_of_graph(tensor, seen_nodes, depth, layer, node_index, tensor_index)
   1643                 node_index = node.node_indices[i]
   1644                 tensor_index = node.tensor_indices[i]
-> 1645                 next_node = layer.inbound_nodes[node_index]
   1646                 # use node_marker to prevent cycles
   1647                 node_marker = make_node_marker(next_node, current_depth + 1)

AttributeError: 'NoneType' object has no attribute 'inbound_nodes'

As far as I understand it is the Model function that is failing, but I cannot still manage to know why. Help would be very much appreciated.

Variable batchnormalization_1_running_mean/biased already exists, disallowed.

if I try to exec "example_gan.py" I have the following error:

Traceback (most recent call last):
  File "/Users/manuelepalmeri/Downloads/keras-adversarial-master/example_gan.py", line 142, in <module>
    main()
  File "/Users/manuelepalmeri/Downloads/keras-adversarial-master/example_gan.py", line 138, in main
    latent_dim=latent_dim)
  File "/Users/manuelepalmeri/Downloads/keras-adversarial-master/example_gan.py", line 82, in example_gan
    gan = simple_gan(generator, discriminator, normal_latent_sampling((latent_dim,)))
  File "/Users/manuelepalmeri/Downloads/keras-adversarial-master/keras_adversarial/adversarial_utils.py", line 38, in simple_gan
    gan = build_gan(generator, discriminator)
  File "/Users/manuelepalmeri/Downloads/keras-adversarial-master/keras_adversarial/adversarial_utils.py", line 17, in build_gan
    yfake = Activation("linear", name="yfake")(discriminator(generator(generator.inputs)))
  File "/Library/Python/2.7/site-packages/keras/engine/topology.py", line 517, in __call__
    self.add_inbound_node(inbound_layers, node_indices, tensor_indices)
  File "/Library/Python/2.7/site-packages/keras/engine/topology.py", line 571, in add_inbound_node
    Node.create_node(self, inbound_layers, node_indices, tensor_indices)
  File "/Library/Python/2.7/site-packages/keras/engine/topology.py", line 155, in create_node
    output_tensors = to_list(outbound_layer.call(input_tensors[0], mask=input_masks[0]))
  File "/Library/Python/2.7/site-packages/keras/models.py", line 378, in call
    return self.model.call(x, mask)
  File "/Library/Python/2.7/site-packages/keras/engine/topology.py", line 2075, in call
    output_tensors, output_masks, output_shapes = self.run_internal_graph(inputs, masks)
  File "/Library/Python/2.7/site-packages/keras/engine/topology.py", line 2217, in run_internal_graph
    output_tensors = to_list(layer.call(computed_tensor, computed_mask))
  File "/Library/Python/2.7/site-packages/keras/layers/normalization.py", line 128, in call
    self.add_updates([K.moving_average_update(self.running_mean, mean, self.momentum),
  File "/Library/Python/2.7/site-packages/keras/backend/tensorflow_backend.py", line 364, in moving_average_update
    variable, value, momentum)
  File "/Library/Python/2.7/site-packages/tensorflow/python/training/moving_averages.py", line 70, in assign_moving_average
    update_delta = _zero_debias(variable, value, decay)
  File "/Library/Python/2.7/site-packages/tensorflow/python/training/moving_averages.py", line 177, in _zero_debias
    trainable=False)
  File "/Library/Python/2.7/site-packages/tensorflow/python/ops/variable_scope.py", line 1024, in get_variable
    custom_getter=custom_getter)
  File "/Library/Python/2.7/site-packages/tensorflow/python/ops/variable_scope.py", line 850, in get_variable
    custom_getter=custom_getter)
  File "/Library/Python/2.7/site-packages/tensorflow/python/ops/variable_scope.py", line 346, in get_variable
    validate_shape=validate_shape)
  File "/Library/Python/2.7/site-packages/tensorflow/python/ops/variable_scope.py", line 331, in _true_getter
    caching_device=caching_device, validate_shape=validate_shape)
  File "/Library/Python/2.7/site-packages/tensorflow/python/ops/variable_scope.py", line 632, in _get_single_variable
    name, "".join(traceback.format_list(tb))))
ValueError: Variable batchnormalization_1_running_mean/biased already exists, disallowed. Did you mean to set reuse=True in VarScope? Originally defined at:

  File "/Library/Python/2.7/site-packages/keras/backend/tensorflow_backend.py", line 364, in moving_average_update
    variable, value, momentum)
  File "/Library/Python/2.7/site-packages/keras/layers/normalization.py", line 128, in call
    self.add_updates([K.moving_average_update(self.running_mean, mean, self.momentum),
  File "/Library/Python/2.7/site-packages/keras/engine/topology.py", line 155, in create_node
    output_tensors = to_list(outbound_layer.call(input_tensors[0], mask=input_masks[0]))

can someone help me?

AttributeError: 'Model' object has no attribute 'constraints' when running example_gan_cifar10.py

Hi folks. I'm trying to run this example on Ubuntu 16.04 and I'm getting this error:

  File "example_gan_cifar10.py", line 147, in <module>
    main()
  File "example_gan_cifar10.py", line 143, in main
    latent_dim=latent_dim)
  File "example_gan_cifar10.py", line 120, in example_gan
    batch_size=32)
  File "build/bdist.linux-x86_64/egg/keras_adversarial/legacy.py", line 18, in fit
  File "build/bdist.linux-x86_64/egg/keras/engine/training.py", line 1575, in fit
  File "build/bdist.linux-x86_64/egg/keras_adversarial/adversarial_model.py", line 161, in _make_train_function
AttributeError: 'Model' object has no attribute 'constraints'

Any idea what's going on here?

ValueError: Error when checking model input: the list of Numpy arrays that you are passing to your model is not the size the model expected. Expected to see 3 array(s), but instead got the following list of 2 arrays.

Hi.
I get the error:

Begin training model, 10000 epochs.
Epoch 1/10000
Traceback (most recent call last):
  File "main.py", line 60, in <module>
    main(None)
  File "main.py", line 57, in main
    period = 1)])
  File "/home/diana/Documents/VirtualNN/local/lib/python2.7/site-packages/keras/legacy/interfaces.py", line 87, in wrapper
    return func(*args, **kwargs)
  File "/home/diana/Documents/VirtualNN/local/lib/python2.7/site-packages/keras/engine/training.py", line 2114, in fit_generator
    class_weight=class_weight)
  File "/home/diana/Documents/VirtualNN/local/lib/python2.7/site-packages/keras/engine/training.py", line 1826, in train_on_batch
    check_batch_axis=True)
  File "/home/diana/Documents/VirtualNN/local/lib/python2.7/site-packages/keras/engine/training.py", line 1407, in _standardize_user_data
    exception_prefix='input')
  File "/home/diana/Documents/VirtualNN/local/lib/python2.7/site-packages/keras/engine/training.py", line 88, in _standardize_input_data
    '...')
ValueError: Error when checking model input: the list of Numpy arrays that you are passing to your model is not the size the model expected. Expected to see 3 array(s), but instead got the following list of 2 arrays: [array([[[[0.5803922 , 0.5882353 , 0.5921569 , ..., 0.53333336,
          0.5294118 , 0.5254902 ],
         [0.5882353 , 0.5921569 , 0.59607846, ..., 0.5372549 ,
          0.53333336, 0.5294118 ],
   ...

I am using ImageDataGenerator and I create my dataset like this because the input of my gan are noise and images, labels are images also:

train_datagen = ImageDataGenerator(rescale = 1./ 255, data_format = "channels_first")
    val_datagen   = ImageDataGenerator(rescale = 1./ 255, data_format = "channels_first")

    train_generator = train_datagen.flow_from_directory(train_folder, target_size = (img_rows, img_cols), batch_size = 1, class_mode = None)

    validation_generator = val_datagen.flow_from_directory(valid_folder, target_size = (img_rows, img_cols), batch_size = 1, class_mode = None)


    def train_generator_func():
        while True:
            train_generat       = train_generator.next()
            train_generat_label = train_generator.next()
            noise               = np.random.normal(size = (1, 8, 8, 100))
#there is the same iterator because I want to have pairs of images

            yield [train_generat,noise], [train_generat_label]
                         
    def val_generator_func():
        while True:
            valid_generat       = validation_generator.next()
            valid_generat_label = validation_generator.next()
            noise               = np.random.normal(size = (1, 8, 8, 100))
        
            yield [valid_generat,noise], [valid_generat_label]

    train_gen      = train_generator_func()
    validation_gen = val_generator_func()
    
    return train_gen, validation_gen

What do you think I get this error, because from my understanding i generate input, output shape for data_generator.

example_gan.py: module 'pandas.core.computation' has no attribute 'expressions'

So I ran your commands for cloning and installing your code and immediately switched to the examples directory and tried running the example_gan.py program and got this error:

D:\JJ\python\keras_adversarial\examples>python example_gan.py
D:\Anaconda3\lib\site-packages\h5py\__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.
  from ._conv import register_converters as _register_converters
Using TensorFlow backend.
Traceback (most recent call last):
  File "example_gan.py", line 13, in <module>
    from keras_adversarial.image_grid_callback import ImageGridCallback
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 656, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 626, in _load_backward_compatible
  File "D:\Anaconda3\lib\site-packages\keras_adversarial-0.0.3-py3.6.egg\keras_adversarial\__init__.py", line 1, in <module>
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 656, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 626, in _load_backward_compatible
  File "D:\Anaconda3\lib\site-packages\keras_adversarial-0.0.3-py3.6.egg\keras_adversarial\adversarial_model.py", line 8, in <module>
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 656, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 626, in _load_backward_compatible
  File "D:\Anaconda3\lib\site-packages\keras_adversarial-0.0.3-py3.6.egg\keras_adversarial\adversarial_utils.py", line 7, in <module>
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 656, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 626, in _load_backward_compatible
  File "D:\Anaconda3\lib\site-packages\keras_adversarial-0.0.3-py3.6.egg\keras_adversarial\backend\__init__.py", line 4, in <module>
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 656, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 626, in _load_backward_compatible
  File "D:\Anaconda3\lib\site-packages\keras_adversarial-0.0.3-py3.6.egg\keras_adversarial\backend\tensorflow_backend.py", line 3, in <module>
  File "D:\Anaconda3\lib\site-packages\tensorflow\contrib\__init__.py", line 22, in <module>
    from tensorflow.contrib import bayesflow
  File "D:\Anaconda3\lib\site-packages\tensorflow\contrib\bayesflow\__init__.py", line 28, in <module>
    from tensorflow.contrib.bayesflow.python.ops import layers
  File "D:\Anaconda3\lib\site-packages\tensorflow\contrib\bayesflow\python\ops\layers.py", line 26, in <module>
    from tensorflow.contrib.bayesflow.python.ops.layers_dense_variational_impl import *
  File "D:\Anaconda3\lib\site-packages\tensorflow\contrib\bayesflow\python\ops\layers_dense_variational_impl.py", line 30, in <module>
    from tensorflow.contrib.distributions.python.ops import deterministic as deterministic_lib
  File "D:\Anaconda3\lib\site-packages\tensorflow\contrib\distributions\__init__.py", line 37, in <module>
    from tensorflow.contrib.distributions.python.ops.estimator import *
  File "D:\Anaconda3\lib\site-packages\tensorflow\contrib\distributions\python\ops\estimator.py", line 21, in <module>
    from tensorflow.contrib.learn.python.learn.estimators.head import _compute_weighted_loss
  File "D:\Anaconda3\lib\site-packages\tensorflow\contrib\learn\__init__.py", line 92, in <module>
    from tensorflow.contrib.learn.python.learn import *
  File "D:\Anaconda3\lib\site-packages\tensorflow\contrib\learn\python\__init__.py", line 23, in <module>
    from tensorflow.contrib.learn.python.learn import *
  File "D:\Anaconda3\lib\site-packages\tensorflow\contrib\learn\python\learn\__init__.py", line 25, in <module>
    from tensorflow.contrib.learn.python.learn import estimators
  File "D:\Anaconda3\lib\site-packages\tensorflow\contrib\learn\python\learn\estimators\__init__.py", line 297, in <module>
    from tensorflow.contrib.learn.python.learn.estimators.dnn import DNNClassifier
  File "D:\Anaconda3\lib\site-packages\tensorflow\contrib\learn\python\learn\estimators\dnn.py", line 30, in <module>
    from tensorflow.contrib.learn.python.learn.estimators import dnn_linear_combined
  File "D:\Anaconda3\lib\site-packages\tensorflow\contrib\learn\python\learn\estimators\dnn_linear_combined.py", line 31, in <module>
    from tensorflow.contrib.learn.python.learn.estimators import estimator
  File "D:\Anaconda3\lib\site-packages\tensorflow\contrib\learn\python\learn\estimators\estimator.py", line 48, in <module>
    from tensorflow.contrib.learn.python.learn.learn_io import data_feeder
  File "D:\Anaconda3\lib\site-packages\tensorflow\contrib\learn\python\learn\learn_io\__init__.py", line 21, in <module>
    from tensorflow.contrib.learn.python.learn.learn_io.dask_io import extract_dask_data
  File "D:\Anaconda3\lib\site-packages\tensorflow\contrib\learn\python\learn\learn_io\dask_io.py", line 26, in <module>
    import dask.dataframe as dd
  File "D:\Anaconda3\lib\site-packages\dask\dataframe\__init__.py", line 3, in <module>
    from .core import (DataFrame, Series, Index, _Frame, map_partitions,
  File "D:\Anaconda3\lib\site-packages\dask\dataframe\core.py", line 40, in <module>
    pd.core.computation.expressions.set_use_numexpr(False)
AttributeError: module 'pandas.core.computation' has no attribute 'expressions'

D:\JJ\python\keras_adversarial\examples>python
Python 3.6.3 |Anaconda custom (64-bit)| (default, Oct 15 2017, 03:27:45) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import pandas as pd
>>> pd.__version__
'0.22.0'
>>> import tensorflow as tf
D:\Anaconda3\lib\site-packages\h5py\__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.
  from ._conv import register_converters as _register_converters
>>> import keras
Using TensorFlow backend.
>>> tf.__version__
'1.5.0'
>>> keras.__version__
'2.1.5'
>>>



Issues about "AdversarialOptimizerScheduled" optimizer

Thank you for your great work!
I recently tried the AdversarialOptimizerScheduled optimizer for two players, however, I got this error " File "build/bdist.linux-x86_64/egg/keras_adversarial/adversarial_model.py", line 171, in _make_train_function
File "build/bdist.linux-x86_64/egg/keras_adversarial/adversarial_optimizers.py", line 100, in make_train_function
TypeError: unsupported operand type(s) for +: 'NoneType' and 'list'
"
Do you have any comments on this error? Thank you so much!

'AdversarialModel' object has no attribute '_feed_output_shapes'

I tried creating an adversarial network, when I got the following error. (I'm using python 3.5.3)

Traceback (most recent call last):
File "gan.py", line 69, in
history = model.fit(x=train_x, y=gan_targets(train_x.shape[0]), epochs=10, batch_size=batch_size)
File "/home/atul/anaconda3/lib/python3.6/site-packages/keras/engine/training.py", line 1581, in fit
batch_size=batch_size)
File "/home/atul/anaconda3/lib/python3.6/site-packages/keras/engine/training.py", line 1399, in _standardize_user_data
for output_shape, loss_fn in zip(self._feed_output_shapes, self._feed_loss_fns):
AttributeError: 'AdversarialModel' object has no attribute '_feed_output_shapes'

Generator real loss

I am having problems understanding the generator real loss. As I understand, the generator loss only depends on the output of the discriminator on fake data, so why is there a loss on real data for the generator?

I would expect that eliminating the contribution of this loss should not change the results, however, I modified the code to pass a loss_weight of 0 to the generator_yreal_loss and the training did not succeed.

Am I missing something?

Error while running example_gan_unrolled.py

When I run example_gan_unrolled.py, I get the following error with keras '2.0.4 and tensorflow '1.1.0' with Python 2.7.12. I would really appreciate your help. Or please let me know the running versions of these examples.

Traceback (most recent call last):
File "example_gan_unrolled.py", line 38, in
example("k_8_8", 2, 2)
File "example_gan_unrolled.py", line 33, in example
example_gan_unrolled(os.path.join(path, name), depth_g, depth_d)
File "example_gan_unrolled.py", line 28, in example_gan_unrolled
latent_dim=latent_dim)
File "/scratch0/username/Users/Jaiusername/Documents/Study/research/pytorchExamples/GAN/keras-adversarial/examples/example_gan.py", line 90, in example_gan
batch_size=32)
File "build/bdist.linux-x86_64/egg/keras_adversarial/legacy.py", line 18, in fit
File "/scratch0/username/installs/tensorflow/lib/python2.7/site-packages/keras/engine/training.py", line 1481, in fit
self._make_train_function()
File "build/bdist.linux-x86_64/egg/keras_adversarial/adversarial_model.py", line 163, in _make_train_function
File "build/bdist.linux-x86_64/egg/keras_adversarial/adversarial_optimizers.py", line 35, in make_train_function
File "build/bdist.linux-x86_64/egg/keras_adversarial/unrolled_optimizer.py", line 30, in call
File "build/bdist.linux-x86_64/egg/keras_adversarial/unrolled_optimizer.py", line 11, in unroll
File "build/bdist.linux-x86_64/egg/keras_adversarial/backend/tensorflow_backend.py", line 54, in clone_replace
File "/scratch0/username/installs/tensorflow/lib/python2.7/site-packages/tensorflow/contrib/graph_editor/transform.py", line 655, in graph_replace
ops, replacement_ts, None, dst_scope, src_scope, reuse_dst_scope)
File "/scratch0/username/installs/tensorflow/lib/python2.7/site-packages/tensorflow/contrib/graph_editor/transform.py", line 617, in copy_with_input_replacements
sgv, dst_graph, dst_scope, src_scope, reuse_dst_scope=reuse_dst_scope)
File "/scratch0/username/installs/tensorflow/lib/python2.7/site-packages/tensorflow/contrib/graph_editor/transform.py", line 434, in call
self.copy_ops(info)
File "/scratch0/username/installs/tensorflow/lib/python2.7/site-packages/tensorflow/contrib/graph_editor/transform.py", line 447, in copy_ops
op
, op_outputs
= self.transform_op_handler(info, op)
File "/scratch0/username/installs/tensorflow/lib/python2.7/site-packages/tensorflow/contrib/graph_editor/transform.py", line 171, in copy_op_handler
original_op = info.transform_original_op_handler(info, op._original_op)
File "/scratch0/username/installs/tensorflow/lib/python2.7/site-packages/tensorflow/contrib/graph_editor/transform.py", line 124, in transform_op_if_inside_handler
return info.transformed_ops[op]
KeyError: <tf.Operation 'gan_1/gan/discriminator_1/discriminator_y/MatMul' type=MatMul>

Understanding keras output

I am using keras-adversarial for semantic segmentation and I don't understand why loss values output by keras are changing on a model that should not be training (based on the schedule set).

I have specifically set the schedule so that the discriminator is not training for the first 500 batches, but even so, the discriminator loss values are changing in the keras output from the outset. Why is this the case?

generator and discriminator models are created and this is the code that follows:

seg = generator(generator.inputs)  # the segmentation of the input images
y_fake = discriminator(generator(generator.inputs)) # output on fake segmentations
y_real = discriminator(discriminator.inputs) # output on real segmentations

# make gan model          
gan_model = Model(generator.inputs + discriminator.inputs, fix_names([tissue_pred, y_fake, y_real], ['tissue_pred', 'y_fake', 'y_real']))
  
gan_model.summary()

# only update the discriminator every 500 batches  
sched = np.ndarray.tolist(np.zeros(500, dtype=np.int8))
sched[499]=1

# adversarial model        
model = AdversarialModel(base_model=gan_model,
                              player_params=[generator.trainable_weights, discriminator.trainable_weights],
                               player_names=["generator", "discriminator"])

# compile  (cross_ent is a measure computing cross entropy loss across channels)
model.adversarial_compile(adversarial_optimizer=AdversarialOptimizerScheduled(schedule=sched),
                                player_optimizers=[Adam(lr=0.001), Adam(lr=0.001)],
                                loss={'seg':cross_ent, 'y_fake':'binary_crossentropy', 'y_real':'binary_crossentropy'})

Output is as follows: I expected that loss values starting with discriminator_ would not change yet, but they do.

Epoch 1/500
53/54 [============================>.] - ETA: 0s - loss: 4.7940 - generator_loss: 2.3954 - generator_tissue_pred_loss: 1.0078 - generator_y_fake_loss: 0.7124 - generator_y_real_loss: 0.6742 - discriminator_loss: 2.3985 - discriminator_tissue_pred_loss: 1.0078 - discriminator_y_fake_loss: 0.6754 - discriminator_y_real_loss: 0.7144
54/54 [==============================] - 44s - loss: 4.7919 - generator_loss: 2.3945 - generator_tissue_pred_loss: 1.0067 - generator_y_fake_loss: 0.7127 - generator_y_real_loss: 0.6741 - discriminator_loss: 2.3974 - discriminator_tissue_pred_loss: 1.0067 - discriminator_y_fake_loss: 0.6751 - discriminator_y_real_loss: 0.7146 - val_loss: 7.9896 - val_generator_loss: 3.9992 - val_generator_tissue_pred_loss: 2.6059 - val_generator_y_fake_loss: 0.7231 - val_generator_y_real_loss: 0.6692 - val_discriminator_loss: 3.9904 - val_discriminator_tissue_pred_loss: 2.6059 - val_discriminator_y_fake_loss: 0.6641 - val_discriminator_y_real_loss: 0.7195

Issue with keras 1.2

Hello,
I installed this package while using keras1.2, this is the error I am getting when I am running the example_gan_cifar10.py
screen shot 2017-04-03 at 8 46 04 pm
I am new to keras but my guess is that this requires a trivial change but I fear updating it might make other associated functions go south!

example_gan.py TypeError

Hello,

Sorry to bother, I'm fairly new to Keras and everything. I'm trying to set up two adversarial neural networks, and your lib seems very interesting to me. I cloned the repository and installation went successfully. But I tried to launch example_gan.py, and I got an error. I don't understand enough yet to be able to solve it by myself...

I'm using Spyder 2.3.9, with Python 3.5, TensorFlow : 1.1.0, Keras : 2.0.4

The error is : "TypeError: Value passed to parameter 'shape' has DataType float32 not in list of allowed values: int32, int64"

PasteBin of the full Traceback : https://pastebin.com/0BaAcuQa

Any kind of help is appreciated :) !

Issues with Keras 2.1.5

It seems that there are some issues with the latest version of Keras 2.1.5

  1. in adversial_model internal_input_shapes and internal_output_shapes need to be corrected to _internal_input_shapes, _internal_output_shapes, this is easy to fix.

  2. However the following error needs some more careful attention
    File "/Users/MacBookPro1/Work/Code/Python/PycharmProjects/GANs/venv/lib/python3.6/site-packages/keras/engine/training.py", line 1132, in _fit_loop
    stateful_metrics=self.stateful_metric_names)]
    AttributeError: 'AdversarialModel' object has no attribute 'stateful_metric_names'

Any help? is this going to be fixed? Thanks

BIGAN example NaN

Hi,

I'm getting nans when running example_bigan.py with keras2.

Any ideas?

Thanks!

BIGAN: Error not decreasing

Hello,

I try to train the BIGAN with MNIST and the default parameters (as they are defined in the file) but the error rate don't increase (even after 1000 epochs). I'm new to GANs, could anyone give some advices?

Provide very simple example for crude data (not image dataset)

Hi,
Could you please provide very simple model to show how one can utilize the package for some test dataset which is not image dataset. I cannot understand how I can call the functions in crude simple dataset, for example one simple dataset.csv file (one dimensional not two or three dimensional image dataset).

All examples you utilize function 'generator_sampler()' and 'ImageGridCallback': I need to utilize generator_sampler directly.

ImportError: No module named legacy

I'm trying to run the example_gan_cifar10.py but I get this error:

ubuntu@ip-X-X-X-X:~/keras_adversarial/examples$ ~/gan_env/bin/python example_gan_cifar10.py 
Using TensorFlow backend.
2017-11-13 12:01:55.661466: I tensorflow/core/platform/cpu_feature_guard.cc:137] Your CPU supports instructions that this TensorFlow binary was not compiled to use: SSE4.1 SSE4.2 AVX AVX2 FMA
2017-11-13 12:01:58.843063: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:892] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2017-11-13 12:01:58.843430: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1030] Found device 0 with properties: 
name: Tesla K80 major: 3 minor: 7 memoryClockRate(GHz): 0.8235
pciBusID: 0000:00:1e.0
totalMemory: 11.17GiB freeMemory: 11.10GiB
2017-11-13 12:01:58.843468: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1120] Creating TensorFlow device (/device:GPU:0) -> (device: 0, name: Tesla K80, pci bus id: 0000:00:1e.0, compute capability: 3.7)
Traceback (most recent call last):
  File "example_gan_cifar10.py", line 18, in <module>
    from keras_adversarial.legacy import Dense, BatchNormalization, fit, l1l2, Convolution2D, AveragePooling2D
ImportError: No module named legacy

Strangely, the same script worked on my local machine (with non-gpu tensorflow), but was quite slow and didn't converge after a couple of hours, so I wanted to try it on a beefier GPU box.

Error: _gru_ops.dll not found // tensorflow 1.6.0, python 3.6.1

Get the following error, when running example_gan.py with tensorflow 1.6.0 under Python 3.6.1.
Had no problem with tensorflow 0.12.1, Python 3.5

Traceback (most recent call last):
File ".\example_gan.py", line 13, in
from keras_adversarial.image_grid_callback import ImageGridCallback
File "", line 961, in _find_and_load
File "", line 950, in _find_and_load_unlocked
File "", line 646, in _load_unlocked
File "", line 616, in load_backward_compatible
File "C:\Python_3_6\lib\site-packages\keras_adversarial-0.0.3-py3.6.egg\keras_adversarial_init
.py", line 1, in
from .adversarial_model import AdversarialModel
File "", line 961, in _find_and_load
File "", line 950, in _find_and_load_unlocked
File "", line 646, in _load_unlocked
File "", line 616, in _load_backward_compatible
File "C:\Python_3_6\lib\site-packages\keras_adversarial-0.0.3-py3.6.egg\keras_adversarial\adversarial_model.py", line 8, in
from .adversarial_utils import fix_names, merge_updates
File "", line 961, in _find_and_load
File "", line 950, in _find_and_load_unlocked
File "", line 646, in _load_unlocked
File "", line 616, in _load_backward_compatible
File "C:\Python_3_6\lib\site-packages\keras_adversarial-0.0.3-py3.6.egg\keras_adversarial\adversarial_utils.py", line 7, in
from .backend import unpack_assignment, variable_key
File "", line 961, in find_and_load
File "", line 950, in find_and_load_unlocked
File "", line 646, in load_unlocked
File "", line 616, in load_backward_compatible
File "C:\Python_3_6\lib\site-packages\keras_adversarial-0.0.3-py3.6.egg\keras_adversarial\backend_init
.py", line 4, in
from .adversarial_optimizers import AdversarialOptimizerScheduled
File "", line 961, in find_and_load
File "", line 950, in find_and_load_unlocked
File "", line 646, in load_unlocked
File "", line 616, in load_backward_compatible
File "C:\Python_3_6\lib\site-packages\keras_adversarial-0.0.3-py3.6.egg\keras_adversarial\backend\tensorflow_backend.py", line 3, in
File "C:\Python_3_6\lib\site-packages\tensorflow\contrib_init
.py", line 23, in
from tensorflow.contrib import bayesflow
File "C:\Python_3_6\lib\site-packages\tensorflow\contrib\bayesflow_init
.py", line 28, in
from tensorflow.contrib.bayesflow.python.ops import layers
File "C:\Python_3_6\lib\site-packages\tensorflow\contrib\bayesflow\python\ops\layers.py", line 26, in
from tensorflow.contrib.bayesflow.python.ops.layers_conv_variational import *
File "C:\Python_3_6\lib\site-packages\tensorflow\contrib\bayesflow\python\ops\layers_conv_variational.py", line 22, in
from tensorflow.contrib.bayesflow.python.ops import layers_util
File "C:\Python_3_6\lib\site-packages\tensorflow\contrib\bayesflow\python\ops\layers_util.py", line 24, in
from tensorflow.contrib.distributions.python.ops import deterministic as deterministic_lib
File "C:\Python_3_6\lib\site-packages\tensorflow\contrib\distributions_init.py", line 38, in
from tensorflow.contrib.distributions.python.ops.estimator import *
File "C:\Python_3_6\lib\site-packages\tensorflow\contrib\distributions\python\ops\estimator.py", line 21, in
from tensorflow.contrib.learn.python.learn.estimators.head import compute_weighted_loss
File "C:\Python_3_6\lib\site-packages\tensorflow\contrib\learn_init
.py", line 92, in
from tensorflow.contrib.learn.python.learn import *
File "C:\Python_3_6\lib\site-packages\tensorflow\contrib\learn\python_init.py", line 23, in
from tensorflow.contrib.learn.python.learn import *
File "C:\Python_3_6\lib\site-packages\tensorflow\contrib\learn\python\learn_init.py", line 25, in
from tensorflow.contrib.learn.python.learn import estimators
File "C:\Python_3_6\lib\site-packages\tensorflow\contrib\learn\python\learn\estimators_init.py", line 303, in
from tensorflow.contrib.learn.python.learn.estimators.dynamic_rnn_estimator import DynamicRnnEstimator
File "C:\Python_3_6\lib\site-packages\tensorflow\contrib\learn\python\learn\estimators\dynamic_rnn_estimator.py", line 27, in
from tensorflow.contrib.learn.python.learn.estimators import rnn_common
File "C:\Python_3_6\lib\site-packages\tensorflow\contrib\learn\python\learn\estimators\rnn_common.py", line 22, in
from tensorflow.contrib import rnn as contrib_rnn
File "C:\Python_3_6\lib\site-packages\tensorflow\contrib\rnn_init.py", line 83, in
from tensorflow.contrib.rnn.python.ops.gru_ops import *
File "C:\Python_3_6\lib\site-packages\tensorflow\contrib\rnn\python\ops\gru_ops.py", line 33, in
resource_loader.get_path_to_datafile("_gru_ops.so"))
File "C:\Python_3_6\lib\site-packages\tensorflow\contrib\util\loader.py", line 55, in load_op_library
ret = load_library.load_op_library(path)
File "C:\Python_3_6\lib\site-packages\tensorflow\python\framework\load_library.py", line 58, in load_op_library
lib_handle = py_tf.TF_LoadLibrary(library_filename, status)
File "C:\Python_3_6\lib\site-packages\tensorflow\python\framework\errors_impl.py", line 516, in exit
c_api.TF_GetCode(self.status.status))
tensorflow.python.framework.errors_impl.NotFoundError: C:\Python_3_6\lib\site-packages\tensorflow\contrib\rnn\python\ops_gru_ops.dll not found

Running example_aae

Hi again,

When running the example_aae.py, I get the following error:
I am running tensorflow as the backend

Traceback (most recent call last):
  File "examples/example_aae.py", line 140, in <module>
    main()
  File "examples/example_aae.py", line 136, in main
    example_aae("output/aae", AdversarialOptimizerSimultaneous())
  File "examples/example_aae.py", line 71, in example_aae
    encoder = model_encoder(latent_dim, input_shape)
  File "examples/example_aae.py", line 46, in model_encoder
    output_shape=lambda p: p[0])
  File "/usr/local/lib/python2.7/dist-packages/keras/engine/topology.py", line 1680, in merge
    name=name)
  File "/usr/local/lib/python2.7/dist-packages/keras/engine/topology.py", line 1301, in __init__
    self.add_inbound_node(layers, node_indices, tensor_indices)
  File "/usr/local/lib/python2.7/dist-packages/keras/engine/topology.py", line 635, in add_inbound_node
    Node.create_node(self, inbound_layers, node_indices, tensor_indices)
  File "/usr/local/lib/python2.7/dist-packages/keras/engine/topology.py", line 172, in create_node
    output_tensors = to_list(outbound_layer.call(input_tensors, mask=input_masks))
  File "/usr/local/lib/python2.7/dist-packages/keras/engine/topology.py", line 1383, in call
    return self.mode(inputs, **arguments)
  File "examples/example_aae.py", line 45, in <lambda>
    z = merge([mu, log_sigma_sq], mode=lambda p: p[0] + K.random_normal(p[0].shape) * K.exp(p[1] / 2),
AttributeError: 'Tensor' object has no attribute 'shape'

Handling 'trainable' issue

In the README file it is stated that the Adversarial Optimizer gets around the issue of setting network 'trainable' properties. Can you explain how this works please?
In other sample code I have seen the discriminator model has to be compiled and then the 'trainable' property set to false before putting it into the GAN and compiling the GAN. The discriminator weights are therefore not updated when GAN is being trained (this is my understanding).
Can you please explain how it works in your implementation? Thanks.

AC-GAN using keras-adversarial package

A complete example of AC-GAN using keras-adversarial would be nice !

I have ac-gan implemented here :

https://github.com/rjpg/bftensor/blob/master/Autoencoder/src/ac-gan2.py

but it is slow ... I notice that it only uses one core ... this keras-adversarial package seams to be optimized to work with all cores ... that is why it is important.

If someone takes this task, it is important to have the accuracy metric (train/test) of the softmax on the discriminator side among with loss ..

In AC-GAN:
1 - the discriminator input is only the image : [image]
2 - the discriminator output is one softmax with N classes and one sigmoid to identify real/fake [labels,valid]
3 - the generator input is : [noise,label] (then they are multiplied to give color to the noise to be oriented to generate one class )
4 - the generator output is only one image : [image]

when training fake images the random labels to use in the generator to create images to train must be used also in the discriminator training , something like :

....
# Adversarial ground truths
valid = np.ones((batch_size, 1))
fake = np.zeros((batch_size, 1))
...

#inside train cycle
                ...
                # real data 
                imgs = X_train[index * batch_size:(index + 1) * batch_size]
                img_labels = y_train[index * batch_size:(index + 1) * batch_size]
                #end real data

                # generated data 
                noise = np.random.normal(0, 1, (batch_size, 100))
    
                # The labels of the digits that the generator tries to create an
                # image representation of
--->          sampled_labels = np.random.randint(0, 10, (batch_size, 1))
    
                # Generate a half batch of new images
--->            gen_imgs = self.generator.predict([noise, sampled_labels])
                #end generated data

                # Train the discriminator
                d_loss_real = self.discriminator.train_on_batch(imgs, [valid, img_labels])
--->           d_loss_fake = self.discriminator.train_on_batch(gen_imgs, [fake, sampled_labels])

                d_loss = 0.5 * np.add(d_loss_real, d_loss_fake)
                ...

if possible :-)

What are Generator/Discriminator yfake/real loss?

This isn't really an issue. I am just new to GAN and I am not sure how these are defined:

Generator yfake loss
Generator yreal loss
Discriminator yfake loss
Discriminator yreal loss

Are these general to GAN, or something specific to this framework? Would like to know the best source to read up on these.

Thanks.

Issue due to Attribute error constraints

Hi @bstriner , many thanks for the job.

I'd like to know if you are going to fix the issue due to constraint attribute in Keras, because Keras > 2.0.7 does not support this any more?

Message error below:
AttributeError: 'Model' object has no attribute 'constraints'

Thanks for the answer!!

Tensorflow issue

Hi, I tried to run the AAE example but got an error when calling fit:

TypeError: run() got an unexpected keyword argument 'compile_kwargs'

I appreciate your help.

Felipe

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.