bn_main.py 974 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. import tensorflow as tf
  2. from tensorflow import keras
  3. from tensorflow.keras import layers, optimizers
  4. # 2 images with 4x4 size, 3 channels
  5. # we explicitly enforce the mean and stddev to N(1, 0.5)
  6. x = tf.random.normal([2,4,4,3], mean=1.,stddev=0.5)
  7. net = layers.BatchNormalization(axis=-1, center=True, scale=True,
  8. trainable=True)
  9. out = net(x)
  10. print('forward in test mode:', net.variables)
  11. out = net(x, training=True)
  12. print('forward in train mode(1 step):', net.variables)
  13. for i in range(100):
  14. out = net(x, training=True)
  15. print('forward in train mode(100 steps):', net.variables)
  16. optimizer = optimizers.SGD(lr=1e-2)
  17. for i in range(10):
  18. with tf.GradientTape() as tape:
  19. out = net(x, training=True)
  20. loss = tf.reduce_mean(tf.pow(out,2)) - 1
  21. grads = tape.gradient(loss, net.trainable_variables)
  22. optimizer.apply_gradients(zip(grads, net.trainable_variables))
  23. print('backward(10 steps):', net.variables)