|
| 1 | +namespace Gradient.Samples { |
| 2 | + using System.Collections.Generic; |
| 3 | + using System.Linq; |
| 4 | + using Gradient.ManualWrappers; |
| 5 | + using SharPy.Runtime; |
| 6 | + using tensorflow; |
| 7 | + using tensorflow.keras; |
| 8 | + using tensorflow.keras.layers; |
| 9 | + |
| 10 | + class ResNetBlock: Model { |
| 11 | + const int PartCount = 3; |
| 12 | + readonly PythonList<Conv2D> convs = new PythonList<Conv2D>(); |
| 13 | + readonly PythonList<BatchNormalization> batchNorms = new PythonList<BatchNormalization>(); |
| 14 | + public ResNetBlock(int kernelSize, int[] filters) { |
| 15 | + for (int part = 0; part < PartCount; part++) { |
| 16 | + this.convs.Add(this.Track(part == 1 |
| 17 | + ? Conv2D.NewDyn(filters[part], kernel_size: kernelSize, padding: "same") |
| 18 | + : Conv2D.NewDyn(filters[part], kernel_size: (1, 1)))); |
| 19 | + this.batchNorms.Add(this.Track(new BatchNormalization())); |
| 20 | + } |
| 21 | + } |
| 22 | + |
| 23 | + public override dynamic call(IEnumerable<IGraphNodeBase> inputs, ImplicitContainer<IGraphNodeBase> training, IGraphNodeBase mask) { |
| 24 | + return this.callImpl((Tensor)inputs.Single(), training); |
| 25 | + } |
| 26 | + |
| 27 | + public override object call(object inputs, bool training, IGraphNodeBase mask = null) { |
| 28 | + return this.callImpl((Tensor)inputs, training); |
| 29 | + } |
| 30 | + |
| 31 | + public override dynamic call(object inputs, ImplicitContainer<IGraphNodeBase> training = null, IEnumerable<IGraphNodeBase> mask = null) { |
| 32 | + return this.callImpl((Tensor)inputs, training?.Value); |
| 33 | + } |
| 34 | + |
| 35 | + object callImpl(IGraphNodeBase inputs, dynamic training) { |
| 36 | + IGraphNodeBase result = inputs; |
| 37 | + |
| 38 | + var batchNormExtraArgs = new PythonDict<string, object>(); |
| 39 | + if (training != null) |
| 40 | + batchNormExtraArgs["training"] = training; |
| 41 | + |
| 42 | + for (int part = 0; part < PartCount; part++) { |
| 43 | + result = this.convs[part].apply(result); |
| 44 | + result = this.batchNorms[part].apply(result, kwargs: batchNormExtraArgs); |
| 45 | + if (part + 1 != PartCount) |
| 46 | + result = tf.nn.relu(result); |
| 47 | + } |
| 48 | + |
| 49 | + result += (Tensor)result + inputs; |
| 50 | + |
| 51 | + return tf.nn.relu(result); |
| 52 | + } |
| 53 | + } |
| 54 | +} |
0 commit comments