You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

Convolutional.cs 5.3 kB

6 years ago
6 years ago
6 years ago
4 years ago
6 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. /*****************************************************************************
  2. Copyright 2018 The TensorFlow.NET Authors. All Rights Reserved.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ******************************************************************************/
  13. using System;
  14. using System.Collections.Generic;
  15. using System.Linq;
  16. using Tensorflow.Keras.ArgsDefinition;
  17. using Tensorflow.Keras.Engine;
  18. using Tensorflow.Keras.Saving;
  19. using Tensorflow.Keras.Utils;
  20. using Tensorflow.Operations;
  21. using static Tensorflow.Binding;
  22. namespace Tensorflow.Keras.Layers
  23. {
  24. public class Convolutional : Layer
  25. {
  26. ConvolutionalArgs args;
  27. protected int rank => args.Rank;
  28. protected int filters => args.Filters;
  29. protected Shape kernel_size => args.KernelSize;
  30. protected Shape strides => args.Strides;
  31. protected string padding => args.Padding;
  32. protected string data_format => args.DataFormat;
  33. protected Shape dilation_rate => args.DilationRate;
  34. protected Activation activation => args.Activation;
  35. protected bool use_bias => args.UseBias;
  36. protected IInitializer kernel_initializer => args.KernelInitializer;
  37. protected IRegularizer kernel_regularizer => args.KernelRegularizer;
  38. protected IInitializer bias_initializer => args.BiasInitializer;
  39. protected IVariableV1 kernel;
  40. protected IVariableV1 bias;
  41. ConvolutionInternal _convolution_op;
  42. protected string _tf_data_format;
  43. public Convolutional(ConvolutionalArgs args) : base(args)
  44. {
  45. this.args = args;
  46. args.KernelSize = conv_utils.normalize_tuple(args.KernelSize.as_int_list(), args.Rank, "kernel_size");
  47. args.Strides = conv_utils.normalize_tuple(args.Strides.as_int_list(), args.Rank, "strides");
  48. args.Padding = conv_utils.normalize_padding(args.Padding);
  49. args.DataFormat = conv_utils.normalize_data_format(args.DataFormat);
  50. args.DilationRate = conv_utils.normalize_tuple(args.DilationRate.as_int_list(), args.Rank, "dilation_rate");
  51. inputSpec = new InputSpec(ndim: rank + 2);
  52. _tf_data_format = conv_utils.convert_data_format(data_format, rank + 2);
  53. }
  54. public override void build(KerasShapesWrapper input_shape)
  55. {
  56. int channel_axis = data_format == "channels_first" ? 1 : -1;
  57. var single_shape = input_shape.ToSingleShape();
  58. var input_channel = channel_axis < 0 ?
  59. single_shape.dims[single_shape.ndim + channel_axis] :
  60. single_shape.dims[channel_axis];
  61. Shape kernel_shape = kernel_size.dims.concat(new long[] { input_channel / args.Groups, filters });
  62. kernel = add_weight(name: "kernel",
  63. shape: kernel_shape,
  64. initializer: kernel_initializer,
  65. regularizer: kernel_regularizer,
  66. trainable: true,
  67. dtype: DType);
  68. if (use_bias)
  69. bias = add_weight(name: "bias",
  70. shape: new int[] { filters },
  71. initializer: bias_initializer,
  72. trainable: true,
  73. dtype: DType);
  74. var axes = new Dictionary<int, int>();
  75. axes.Add(-1, (int)input_channel);
  76. inputSpec = new InputSpec(min_ndim: rank + 2, axes: axes);
  77. string tf_padding;
  78. if (padding == "causal")
  79. tf_padding = "VALID";
  80. else
  81. tf_padding = padding.ToUpper();
  82. string tf_op_name = GetType().Name;
  83. _convolution_op = nn_ops.convolution_internal(tf_padding,
  84. strides,
  85. dilation_rate,
  86. rank,
  87. data_format: _tf_data_format,
  88. name: tf_op_name);
  89. built = true;
  90. _buildInputShape = input_shape;
  91. }
  92. protected override Tensors Call(Tensors inputs, Tensor mask = null, bool? training = null, Tensors initial_state = null, Tensors constants = null)
  93. {
  94. var outputs = _convolution_op.Apply(inputs, kernel.AsTensor());
  95. if (use_bias)
  96. {
  97. if (data_format == "channels_first")
  98. {
  99. throw new NotImplementedException("call channels_first");
  100. }
  101. else
  102. {
  103. outputs = nn_ops.bias_add(outputs, bias, data_format: "NHWC");
  104. }
  105. }
  106. if (activation != null)
  107. outputs = activation.Apply(outputs);
  108. return outputs;
  109. }
  110. protected virtual int _get_channel_axis()
  111. => data_format == "channels_first" ? -1 - rank : -1;
  112. }
  113. }