hypergan.discriminators.fully_connected_discriminator module
import tensorflow as tf
import hyperchamber as hc
import os
import hypergan
from hypergan.discriminators.common import *
from hypergan.discriminators.pyramid_discriminator import PyramidDiscriminator
from hypergan.generators.resize_conv_generator import ResizeConvGenerator
from .base_discriminator import BaseDiscriminator
class FullyConnectedDiscriminator(BaseDiscriminator):
def build(self, net):
config = self.config
gan = self.gan
ops = self.ops
activation = ops.lookup(config.activation or 'lrelu')
final_activation = ops.lookup(config.final_activation or 'tanh')
net = ops.linear(net, 512)
net = activation(net)
net = ops.linear(net, 512)
if final_activation:
net = final_activation(net)
return net
Classes
class FullyConnectedDiscriminator
GANComponents are pluggable pieces within a GAN.
GAN objects are also GANComponents.
class FullyConnectedDiscriminator(BaseDiscriminator):
def build(self, net):
config = self.config
gan = self.gan
ops = self.ops
activation = ops.lookup(config.activation or 'lrelu')
final_activation = ops.lookup(config.final_activation or 'tanh')
net = ops.linear(net, 512)
net = activation(net)
net = ops.linear(net, 512)
if final_activation:
net = final_activation(net)
return net
Ancestors (in MRO)
- FullyConnectedDiscriminator
- hypergan.discriminators.base_discriminator.BaseDiscriminator
- hypergan.gan_component.GANComponent
- builtins.object
Static methods
def __init__(
self, gan, config)
Initializes a gan component based on a gan
and a config
dictionary.
Different components require different config variables.
A ValidationException
is raised if the GAN component configuration fails to validate.
def __init__(self, gan, config):
"""
Initializes a gan component based on a `gan` and a `config` dictionary.
Different components require different config variables.
A `ValidationException` is raised if the GAN component configuration fails to validate.
"""
self.gan = gan
self.config = hc.Config(config)
errors = self.validate()
if errors != []:
raise ValidationException(self.__class__.__name__+": " +"\n".join(errors))
self.create_ops(config)
def add_noise(
self, net)
def add_noise(self, net):
config = self.config
if not config.noise:
return net
print("[discriminator] adding noise", config.noise)
net += tf.random_normal(net.get_shape(), mean=0, stddev=config.noise, dtype=tf.float32)
return net
def biases(
self)
Biases of the GAN component.
def biases(self):
"""
Biases of the GAN component.
"""
return self.ops.biases
def build(
self, net)
def build(self, net):
config = self.config
gan = self.gan
ops = self.ops
activation = ops.lookup(config.activation or 'lrelu')
final_activation = ops.lookup(config.final_activation or 'tanh')
net = ops.linear(net, 512)
net = activation(net)
net = ops.linear(net, 512)
if final_activation:
net = final_activation(net)
return net
def create(
self, net=None, x=None, g=None)
def create(self, net=None, x=None, g=None):
config = self.config
gan = self.gan
ops = self.ops
if net is None:
if x is None:
x = gan.inputs.x
if g is None:
g = gan.generator.sample
x, g = self.resize(config, x, g)
net = tf.concat(axis=0, values=[x, g])
net = self.layer_filter(net)
net = self.build(net)
self.sample = net
return net
def create_ops(
self, config)
Create the ops object as self.ops
. Also looks up config
def create_ops(self, config):
"""
Create the ops object as `self.ops`. Also looks up config
"""
if self.gan is None:
return
if self.gan.ops_backend is None:
return
self.ops = self.gan.ops_backend(config=self.config, device=self.gan.device)
self.config = self.gan.ops.lookup(config)
def fully_connected_from_list(
self, nets)
def fully_connected_from_list(self, nets):
results = []
ops = self.ops
for net, net2 in nets:
net = ops.concat([net, net2], axis=3)
shape = ops.shape(net)
bs = shape[0]
net = ops.reshape(net, [bs, -1])
features = ops.shape(net)[1]
net = ops.linear(net, features)
#net = self.layer_regularizer(net)
net = ops.lookup('lrelu')(net)
#net = ops.linear(net, features)
net = ops.reshape(net, shape)
results.append(net)
return results
def layer_filter(
self, net)
def layer_filter(self, net):
config = self.config
gan = self.gan
ops = self.ops
if 'layer_filter' in config and config.layer_filter is not None:
print("[discriminator] applying layer filter", config['layer_filter'])
stacks = ops.shape(net)[0] // gan.batch_size()
filters = []
for stack in range(stacks):
piece = tf.slice(net, [stack * gan.batch_size(), 0,0,0], [gan.batch_size(), -1, -1, -1])
filters.append(config.layer_filter(gan, self.config, piece))
layer = tf.concat(axis=0, values=filters)
net = tf.concat(axis=3, values=[net, layer])
return net
def layer_regularizer(
self, net)
def layer_regularizer(self, net):
symbol = self.config.layer_regularizer
op = self.gan.ops.lookup(symbol)
if op:
net = op(self, net)
return net
def permute(
self, nets, k)
def permute(self, nets, k):
return list(itertools.permutations(nets, k))
def progressive_enhancement(
self, config, net, xg)
def progressive_enhancement(self, config, net, xg):
if 'progressive_enhancement' in config and config.progressive_enhancement and xg is not None:
net = tf.concat(axis=3, values=[net, xg])
return net
def relation_layer(
self, net)
def relation_layer(self, net):
ops = self.ops
#hack
shape = ops.shape(net)
input_size = shape[1]*shape[2]*shape[3]
netlist = self.split_by_width_height(net)
permutations = self.permute(netlist, 2)
permutations = self.fully_connected_from_list(permutations)
net = ops.concat(permutations, axis=3)
#hack
bs = ops.shape(net)[0]
net = ops.reshape(net, [bs, -1])
net = ops.linear(net, input_size)
net = ops.reshape(net, shape)
return net
def required(
self)
Return a list of required config strings and a ValidationException
will be thrown if any are missing.
Example:
python
class MyComponent(GANComponent):
def required(self):
"learn rate is required"
["learn_rate"]
def required(self):
"""
Return a list of required config strings and a `ValidationException` will be thrown if any are missing.
Example:
```python
class MyComponent(GANComponent):
def required(self):
"learn rate is required"
["learn_rate"]
```
"""
return []
def resize(
self, config, x, g)
def resize(self, config, x, g):
if(config.resize):
# shave off layers >= resize
def should_ignore_layer(layer, resize):
return int(layer.get_shape()[1]) > config['resize'][0] or \
int(layer.get_shape()[2]) > config['resize'][1]
xs = [px for px in xs if not should_ignore_layer(px, config['resize'])]
gs = [pg for pg in gs if not should_ignore_layer(pg, config['resize'])]
x = tf.image.resize_images(x,config['resize'], 1)
g = tf.image.resize_images(g,config['resize'], 1)
else:
return x, g
def reuse(
self, net=None, x=None, g=None)
def reuse(self, net=None, x=None, g=None):
config = self.config
gan = self.gan
ops = self.ops
if net is None:
if x is None:
x or gan.inputs.x
if g is None:
g or gan.generator.sample
x, g = self.resize(config, x, g)
net = self.combine_filter(config, x, g)
self.ops.reuse()
net = self.build(net)
self.ops.stop_reuse()
return net
def split_batch(
self, net, count=2)
Discriminators return stacked results (on axis 0).
This splits the results. Returns [d_real, d_fake]
def split_batch(self, net, count=2):
"""
Discriminators return stacked results (on axis 0).
This splits the results. Returns [d_real, d_fake]
"""
ops = self.ops or self.gan.ops
s = ops.shape(net)
bs = s[0]
nets = []
net = ops.reshape(net, [bs, -1])
start = [0 for x in ops.shape(net)]
for i in range(count):
size = [bs//count] + [x for x in ops.shape(net)[1:]]
nets.append(ops.slice(net, start, size))
start[0] += bs//count
return nets
def split_by_width_height(
self, net)
def split_by_width_height(self, net):
elems = []
ops = self.gan.ops
shape = ops.shape(net)
bs = shape[0]
height = shape[1]
width = shape[2]
for i in range(width):
for j in range(height):
elems.append(ops.slice(net, [0, i, j, 0], [bs, 1, 1, -1]))
return elems
def validate(
self)
Validates a GANComponent. Return an array of error messages. Empty array []
means success.
def validate(self):
"""
Validates a GANComponent. Return an array of error messages. Empty array `[]` means success.
"""
errors = []
required = self.required()
for argument in required:
if(self.config.__getattr__(argument) == None):
errors.append("`"+argument+"` required")
if(self.gan is None):
errors.append("GANComponent constructed without GAN")
return errors
def variables(
self)
All variables associated with this component.
def variables(self):
"""
All variables associated with this component.
"""
return self.ops.variables()
def weights(
self)
The weights of the GAN component.
def weights(self):
"""
The weights of the GAN component.
"""
return self.ops.weights