|
| 1 | +/***************************************************************************** |
| 2 | + Copyright 2023 Haiping Chen. All Rights Reserved. |
| 3 | +
|
| 4 | + Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + you may not use this file except in compliance with the License. |
| 6 | + You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | + Unless required by applicable law or agreed to in writing, software |
| 11 | + distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + See the License for the specific language governing permissions and |
| 14 | + limitations under the License. |
| 15 | +******************************************************************************/ |
| 16 | + |
| 17 | +using Tensorflow.Keras.ArgsDefinition; |
| 18 | + |
| 19 | +namespace Tensorflow.Keras.Layers |
| 20 | +{ |
| 21 | + public class Normalization : PreprocessingLayer |
| 22 | + { |
| 23 | + NormalizationArgs _args; |
| 24 | + |
| 25 | + int[] axis; |
| 26 | + int[] _reduce_axis; |
| 27 | + IVariableV1 adapt_mean, adapt_variance, count; |
| 28 | + Tensor mean, variance; |
| 29 | + Shape _broadcast_shape; |
| 30 | + float? input_mean, input_variance; |
| 31 | + TF_DataType compute_dtype = tf.float32; |
| 32 | + |
| 33 | + public Normalization(NormalizationArgs args) : base(args) |
| 34 | + { |
| 35 | + _args = args; |
| 36 | + if (args.Axis == null) |
| 37 | + { |
| 38 | + axis = new int[0]; |
| 39 | + } |
| 40 | + else |
| 41 | + { |
| 42 | + axis = args.Axis.axis; |
| 43 | + } |
| 44 | + input_mean = args.Mean; |
| 45 | + input_variance = args.Variance; |
| 46 | + } |
| 47 | + |
| 48 | + public override void build(Shape input_shape) |
| 49 | + { |
| 50 | + base.build(input_shape); |
| 51 | + var ndim = input_shape.ndim; |
| 52 | + foreach (var (idx, x) in enumerate(axis)) |
| 53 | + if (x < 0) |
| 54 | + axis[idx] = ndim + x; |
| 55 | + |
| 56 | + var _keep_axis = axis.Select(d => d >= 0 ? d : d + ndim).ToArray(); |
| 57 | + _reduce_axis = range(ndim).Where(d => !_keep_axis.Contains(d)).ToArray(); |
| 58 | + var _reduce_axis_mask = range(ndim).Select(d => _keep_axis.Contains(d) ? 0 : 1).ToArray(); |
| 59 | + // Broadcast any reduced axes. |
| 60 | + _broadcast_shape = new Shape(range(ndim).Select(d => _keep_axis.Contains(d) ? input_shape.dims[d] : 1).ToArray()); |
| 61 | + var mean_and_var_shape = _keep_axis.Select(d => input_shape.dims[d]).ToArray(); |
| 62 | + |
| 63 | + var param_dtype = DType == TF_DataType.DtInvalid ? TF_DataType.TF_FLOAT : DType; |
| 64 | + var param_shape = input_shape; |
| 65 | + |
| 66 | + if(input_mean == null) |
| 67 | + { |
| 68 | + adapt_mean = add_weight("mean", |
| 69 | + mean_and_var_shape, |
| 70 | + dtype: tf.float32, |
| 71 | + initializer: tf.zeros_initializer, |
| 72 | + trainable: false); |
| 73 | + |
| 74 | + adapt_variance = add_weight("variance", |
| 75 | + mean_and_var_shape, |
| 76 | + dtype: tf.float32, |
| 77 | + initializer: tf.ones_initializer, |
| 78 | + trainable: false); |
| 79 | + |
| 80 | + count = add_weight("count", |
| 81 | + Shape.Scalar, |
| 82 | + dtype: tf.int64, |
| 83 | + initializer: tf.zeros_initializer, |
| 84 | + trainable: false); |
| 85 | + |
| 86 | + finalize_state(); |
| 87 | + } |
| 88 | + else |
| 89 | + { |
| 90 | + mean = input_mean * np.ones(mean_and_var_shape); |
| 91 | + variance = input_variance * np.ones(mean_and_var_shape); |
| 92 | + mean = tf.reshape(mean, _broadcast_shape); |
| 93 | + variance = tf.reshape(variance, _broadcast_shape); |
| 94 | + mean = tf.cast(mean, compute_dtype); |
| 95 | + variance = tf.cast(variance, compute_dtype); |
| 96 | + } |
| 97 | + } |
| 98 | + |
| 99 | + public override void reset_state() |
| 100 | + { |
| 101 | + if (input_mean != null && !built) |
| 102 | + { |
| 103 | + return; |
| 104 | + } |
| 105 | + adapt_mean.assign(tf.zeros_like(adapt_mean.AsTensor())); |
| 106 | + adapt_variance.assign(tf.ones_like(adapt_variance.AsTensor())); |
| 107 | + count.assign(tf.zeros_like(count.AsTensor())); |
| 108 | + } |
| 109 | + |
| 110 | + public override void finalize_state() |
| 111 | + { |
| 112 | + if (input_mean != null && !built) |
| 113 | + { |
| 114 | + return; |
| 115 | + } |
| 116 | + mean = tf.reshape(adapt_mean.AsTensor(), _broadcast_shape); |
| 117 | + variance = tf.reshape(adapt_variance.AsTensor(), _broadcast_shape); |
| 118 | + } |
| 119 | + |
| 120 | + public override void update_state(Tensor data) |
| 121 | + { |
| 122 | + data = tf.cast(data, adapt_mean.dtype); |
| 123 | + var (batch_mean, batch_variance) = tf.nn.moments(data, axes: _reduce_axis); |
| 124 | + var batch_shape = tf.shape(data, out_type: count.dtype); |
| 125 | + |
| 126 | + var batch_count = constant_op.constant(1L); |
| 127 | + if (_reduce_axis != null) |
| 128 | + { |
| 129 | + var batch_reduce_shape = tf.gather(batch_shape, constant_op.constant(_reduce_axis)); |
| 130 | + batch_count = tf.reduce_prod(batch_reduce_shape); |
| 131 | + } |
| 132 | + var total_count = batch_count + count.AsTensor(); |
| 133 | + var batch_weight = tf.cast(batch_count, dtype: compute_dtype) / tf.cast( |
| 134 | + total_count, dtype: compute_dtype); |
| 135 | + var existing_weight = 1.0 - batch_weight; |
| 136 | + var total_mean = adapt_mean.AsTensor() * existing_weight + batch_mean * batch_weight; |
| 137 | + |
| 138 | + var total_variance = ( |
| 139 | + adapt_variance.AsTensor() + tf.square(adapt_mean.AsTensor() - total_mean) |
| 140 | + ) * existing_weight + ( |
| 141 | + batch_variance + tf.square(batch_mean - total_mean) |
| 142 | + ) * batch_weight; |
| 143 | + adapt_mean.assign(total_mean); |
| 144 | + adapt_variance.assign(total_variance); |
| 145 | + count.assign(total_count); |
| 146 | + } |
| 147 | + |
| 148 | + public override Shape ComputeOutputShape(Shape input_shape) |
| 149 | + { |
| 150 | + return input_shape; |
| 151 | + } |
| 152 | + |
| 153 | + public override void adapt(Tensor data, int? batch_size = null, int? steps = null) |
| 154 | + { |
| 155 | + base.adapt(data, batch_size: batch_size, steps: steps); |
| 156 | + } |
| 157 | + |
| 158 | + protected override Tensors Call(Tensors inputs, Tensor state = null, bool? training = null) |
| 159 | + { |
| 160 | + if (_args.Invert) |
| 161 | + { |
| 162 | + return mean + ( |
| 163 | + inputs * tf.maximum(tf.sqrt(variance), keras.backend.epsilon()) |
| 164 | + ); |
| 165 | + } |
| 166 | + else |
| 167 | + { |
| 168 | + return (inputs - mean) / tf.maximum( |
| 169 | + tf.sqrt(variance), keras.backend.epsilon()); |
| 170 | + } |
| 171 | + } |
| 172 | + } |
| 173 | +} |
0 commit comments