|
| 1 | +# RESUED CODE FROM https://github.com/carpedm20/DCGAN-tensorflow/blob/master/ops.py |
| 2 | +import math |
| 3 | +import numpy as np |
| 4 | +import tensorflow as tf |
| 5 | + |
| 6 | +from tensorflow.python.framework import ops |
| 7 | + |
| 8 | + |
| 9 | +class batch_norm(object): |
| 10 | + |
| 11 | + # This function initailizes a batch_norm layer when the class name is called. |
| 12 | + # Code modification of http://stackoverflow.com/a/33950177 |
| 13 | + def __init__(self, epsilon=1e-5, momentum = 0.9, name="batch_norm"): |
| 14 | + |
| 15 | + with tf.variable_scope(name): |
| 16 | + |
| 17 | + self.epsilon = epsilon |
| 18 | + self.momentum = momentum |
| 19 | + self.ema = tf.train.ExponentialMovingAverage(decay=self.momentum) |
| 20 | + self.name = name |
| 21 | + |
| 22 | + |
| 23 | + def __call__(self, x, train=True): |
| 24 | + shape = x.get_shape().as_list() |
| 25 | + |
| 26 | + if train: |
| 27 | + with tf.variable_scope(self.name) as scope: |
| 28 | + self.beta = tf.get_variable("beta", [shape[-1]], |
| 29 | + initializer=tf.constant_initializer(0.)) |
| 30 | + self.gamma = tf.get_variable("gamma", [shape[-1]], |
| 31 | + initializer=tf.random_normal_initializer(1., 0.02)) |
| 32 | + |
| 33 | + try: |
| 34 | + batch_mean, batch_var = tf.nn.moments(x, [0, 1, 2], name='moments') |
| 35 | + except: |
| 36 | + batch_mean, batch_var = tf.nn.moments(x, [0, 1], name='moments') |
| 37 | + |
| 38 | + with tf.variable_scope(tf.get_variable_scope(), reuse=tf.AUTO_REUSE): |
| 39 | + ema_apply_op = self.ema.apply([batch_mean, batch_var]) |
| 40 | + self.ema_mean, self.ema_var = self.ema.average(batch_mean), self.ema.average(batch_var) |
| 41 | + |
| 42 | + with tf.control_dependencies([ema_apply_op]): |
| 43 | + mean, var = tf.identity(batch_mean), tf.identity(batch_var) |
| 44 | + else: |
| 45 | + mean, var = self.ema_mean, self.ema_var |
| 46 | + |
| 47 | + normed = tf.nn.batch_norm_with_global_normalization( |
| 48 | + x, mean, var, self.beta, self.gamma, self.epsilon, scale_after_normalization=True) |
| 49 | + |
| 50 | + return normed |
| 51 | + |
| 52 | +def binary_cross_entropy(preds, targets, name=None): |
| 53 | + """Computes binary cross entropy given `preds`. |
| 54 | + For brevity, let `x = `, `z = targets`. The logistic loss is |
| 55 | + loss(x, z) = - sum_i (x[i] * log(z[i]) + (1 - x[i]) * log(1 - z[i])) |
| 56 | + Args: |
| 57 | + preds: A `Tensor` of type `float32` or `float64`. |
| 58 | + targets: A `Tensor` of the same type and shape as `preds`. |
| 59 | + """ |
| 60 | + eps = 1e-12 |
| 61 | + with ops.op_scope([preds, targets], name, "bce_loss") as name: |
| 62 | + preds = ops.convert_to_tensor(preds, name="preds") |
| 63 | + targets = ops.convert_to_tensor(targets, name="targets") |
| 64 | + return tf.reduce_mean(-(targets * tf.log(preds + eps) + (1.0 - targets) * tf.log(1.0 - preds + eps))) |
| 65 | + |
| 66 | +def conv_cond_concat(x, y): |
| 67 | + """Concatenate conditioning vector on feature map axis.""" |
| 68 | + x_shapes = x.get_shape() |
| 69 | + y_shapes = y.get_shape() |
| 70 | + return tf.concat(3, [x, y*tf.ones([x_shapes[0], x_shapes[1], x_shapes[2], y_shapes[3]])]) |
| 71 | + |
| 72 | +def conv2d(input_, output_dim, k_h=5, k_w=5, d_h=2, d_w=2, stddev=0.02,name="conv2d"): |
| 73 | + with tf.variable_scope(name): |
| 74 | + w = tf.get_variable('w', [k_h, k_w, input_.get_shape()[-1], output_dim], initializer=tf.truncated_normal_initializer(stddev=stddev)) |
| 75 | + |
| 76 | + conv = tf.nn.conv2d(input_, w, strides=[1, d_h, d_w, 1], padding='SAME') |
| 77 | + |
| 78 | + biases = tf.get_variable('biases', [output_dim], initializer=tf.constant_initializer(0.0)) |
| 79 | + conv = tf.reshape(tf.nn.bias_add(conv, biases), conv.get_shape()) |
| 80 | + |
| 81 | + return conv |
| 82 | + |
| 83 | +# |
| 84 | +def deconv2d(input_, output_shape, k_h=5, k_w=5, d_h=2, d_w=2, stddev=0.02, name="deconv2d", with_w=False): |
| 85 | + |
| 86 | + with tf.variable_scope(name): |
| 87 | + # filter : [height, width, output_channels, in_channels] |
| 88 | + w = tf.get_variable('w', [k_h, k_h, output_shape[-1], input_.get_shape()[-1]], initializer=tf.random_normal_initializer(stddev=stddev)) |
| 89 | + |
| 90 | + try: |
| 91 | + deconv = tf.nn.conv2d_transpose(input_, w, output_shape=output_shape,strides=[1, d_h, d_w, 1]) |
| 92 | + |
| 93 | + # Support for verisons of TensorFlow before 0.7.0 |
| 94 | + except AttributeError: |
| 95 | + deconv = tf.nn.deconv2d(input_, w, output_shape=output_shape, strides=[1, d_h, d_w, 1]) |
| 96 | + |
| 97 | + biases = tf.get_variable('biases', [output_shape[-1]], initializer=tf.constant_initializer(0.0)) |
| 98 | + deconv = tf.reshape(tf.nn.bias_add(deconv, biases), deconv.get_shape()) |
| 99 | + |
| 100 | + if with_w: |
| 101 | + return deconv, w, biases |
| 102 | + else: |
| 103 | + return deconv |
| 104 | + |
| 105 | +# Leaky relu activation |
| 106 | +def lrelu(x, leak=0.2, name="lrelu"): |
| 107 | + return tf.maximum(x, leak*x) |
| 108 | + |
| 109 | + |
| 110 | + |
| 111 | +def linear(input_, output_size, scope=None, stddev=0.02, bias_start=0.0, with_w=False): |
| 112 | + |
| 113 | + # input_ is the text_embedding being passed from model.py |
| 114 | + shape = input_.get_shape().as_list() |
| 115 | + |
| 116 | + # Preserving the scope of the variable. Variable_scope allows to create new variables or use shared variables |
| 117 | + # Check out this for variable_scope https://www.tensorflow.org/api_docs/python/tf/compat/v1/variable_scope |
| 118 | + with tf.variable_scope(scope or "Linear"): |
| 119 | + |
| 120 | + # get_variable is used to get an existing variable with these parameters or to create a new one. |
| 121 | + # Input arguments are : name, share, dtype and initializer. |
| 122 | + |
| 123 | + # Weight matrix |
| 124 | + matrix = tf.get_variable("Matrix", [shape[1], output_size], tf.float32, tf.random_normal_initializer(stddev=stddev)) |
| 125 | + |
| 126 | + # Bias matrix |
| 127 | + bias = tf.get_variable("bias", [output_size], initializer=tf.constant_initializer(bias_start)) |
| 128 | + |
| 129 | + # Return the matmul of the input with the weight matrix + the bias |
| 130 | + if with_w: |
| 131 | + return tf.matmul(input_, matrix) + bias, matrix, bias |
| 132 | + else: |
| 133 | + return tf.matmul(input_, matrix) + bias |
0 commit comments