ops.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import math
  2. import numpy as np
  3. import tensorflow as tf
  4. import tensorflow.contrib.slim as slim
  5. from tensorflow.python.framework import ops
  6. from utils import *
  7. def batch_norm(x, name="batch_norm"):
  8. return tf.contrib.layers.batch_norm(x, decay=0.9, updates_collections=None, epsilon=1e-5, scale=True, scope=name)
  9. def instance_norm(input, name="instance_norm"):
  10. with tf.variable_scope(name):
  11. depth = input.get_shape()[3]
  12. scale = tf.get_variable("scale", [depth], initializer=tf.random_normal_initializer(1.0, 0.02, dtype=tf.float32))
  13. offset = tf.get_variable("offset", [depth], initializer=tf.constant_initializer(0.0))
  14. mean, variance = tf.nn.moments(input, axes=[1,2], keep_dims=True)
  15. epsilon = 1e-5
  16. inv = tf.rsqrt(variance + epsilon)
  17. normalized = (input-mean)*inv
  18. return scale*normalized + offset
  19. def conv2d(input_, output_dim, ks=4, s=2, stddev=0.02, padding='SAME', name="conv2d"):
  20. with tf.variable_scope(name):
  21. return slim.conv2d(input_, output_dim, ks, s, padding=padding, activation_fn=None,
  22. weights_initializer=tf.truncated_normal_initializer(stddev=stddev),
  23. biases_initializer=None)
  24. def deconv2d(input_, output_dim, ks=4, s=2, stddev=0.02, name="deconv2d"):
  25. with tf.variable_scope(name):
  26. return slim.conv2d_transpose(input_, output_dim, ks, s, padding='SAME', activation_fn=None,
  27. weights_initializer=tf.truncated_normal_initializer(stddev=stddev),
  28. biases_initializer=None)
  29. def lrelu(x, leak=0.2, name="lrelu"):
  30. return tf.maximum(x, leak*x)
  31. def linear(input_, output_size, scope=None, stddev=0.02, bias_start=0.0, with_w=False):
  32. with tf.variable_scope(scope or "Linear"):
  33. matrix = tf.get_variable("Matrix", [input_.get_shape()[-1], output_size], tf.float32,
  34. tf.random_normal_initializer(stddev=stddev))
  35. bias = tf.get_variable("bias", [output_size],
  36. initializer=tf.constant_initializer(bias_start))
  37. if with_w:
  38. return tf.matmul(input_, matrix) + bias, matrix, bias
  39. else:
  40. return tf.matmul(input_, matrix) + bias