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.

tf.layers.cs 10 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  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.Collections.Generic;
  14. using System.Linq;
  15. using NumSharp;
  16. using Tensorflow.Keras.Layers;
  17. using Tensorflow.Operations.Activation;
  18. using static Tensorflow.Binding;
  19. namespace Tensorflow
  20. {
  21. public partial class tensorflow
  22. {
  23. public layers_internal layers { get; } = new layers_internal();
  24. public class layers_internal
  25. {
  26. public Tensor conv2d(Tensor inputs,
  27. int filters,
  28. int[] kernel_size,
  29. int[] strides = null,
  30. string padding = "valid",
  31. string data_format= "channels_last",
  32. int[] dilation_rate = null,
  33. bool use_bias = true,
  34. IActivation activation = null,
  35. IInitializer kernel_initializer = null,
  36. IInitializer bias_initializer = null,
  37. bool trainable = true,
  38. string name = null)
  39. {
  40. if (strides == null)
  41. strides = new int[] { 1, 1 };
  42. if (dilation_rate == null)
  43. dilation_rate = new int[] { 1, 1 };
  44. if (bias_initializer == null)
  45. bias_initializer = tf.zeros_initializer;
  46. var layer = new Conv2D(filters,
  47. kernel_size: kernel_size,
  48. strides: strides,
  49. padding: padding,
  50. data_format: data_format,
  51. dilation_rate: dilation_rate,
  52. activation: activation,
  53. use_bias: use_bias,
  54. kernel_initializer: kernel_initializer,
  55. bias_initializer: bias_initializer,
  56. trainable: trainable,
  57. name: name);
  58. return layer.apply(inputs).Item1;
  59. }
  60. /// <summary>
  61. /// Functional interface for the batch normalization layer.
  62. /// http://arxiv.org/abs/1502.03167
  63. /// </summary>
  64. /// <param name="inputs"></param>
  65. /// <param name="axis"></param>
  66. /// <param name="momentum"></param>
  67. /// <param name="epsilon"></param>
  68. /// <param name="center"></param>
  69. /// <param name="scale"></param>
  70. /// <param name="beta_initializer"></param>
  71. /// <param name="gamma_initializer"></param>
  72. /// <param name="moving_mean_initializer"></param>
  73. /// <param name="moving_variance_initializer"></param>
  74. /// <param name="training"></param>
  75. /// <param name="trainable"></param>
  76. /// <param name="name"></param>
  77. /// <param name="renorm"></param>
  78. /// <param name="renorm_momentum"></param>
  79. /// <returns></returns>
  80. public Tensor batch_normalization(Tensor inputs,
  81. int axis = -1,
  82. float momentum = 0.99f,
  83. float epsilon = 0.001f,
  84. bool center = true,
  85. bool scale = true,
  86. IInitializer beta_initializer = null,
  87. IInitializer gamma_initializer = null,
  88. IInitializer moving_mean_initializer = null,
  89. IInitializer moving_variance_initializer = null,
  90. Tensor training = null,
  91. bool trainable = true,
  92. string name = null,
  93. bool renorm = false,
  94. float renorm_momentum = 0.99f)
  95. {
  96. var layer = new BatchNormalization(
  97. axis: axis,
  98. momentum: momentum,
  99. epsilon: epsilon,
  100. center: center,
  101. scale: scale,
  102. beta_initializer: beta_initializer,
  103. gamma_initializer: gamma_initializer,
  104. moving_mean_initializer: moving_mean_initializer,
  105. moving_variance_initializer: moving_variance_initializer,
  106. renorm: renorm,
  107. renorm_momentum: renorm_momentum,
  108. trainable: trainable,
  109. name: name);
  110. return layer.apply(inputs, training: training).Item1;
  111. }
  112. /// <summary>
  113. /// Max pooling layer for 2D inputs (e.g. images).
  114. /// </summary>
  115. /// <param name="inputs">The tensor over which to pool. Must have rank 4.</param>
  116. /// <param name="pool_size"></param>
  117. /// <param name="strides"></param>
  118. /// <param name="padding"></param>
  119. /// <param name="data_format"></param>
  120. /// <param name="name"></param>
  121. /// <returns></returns>
  122. public Tensor max_pooling2d(Tensor inputs,
  123. int[] pool_size,
  124. int[] strides,
  125. string padding = "valid",
  126. string data_format = "channels_last",
  127. string name = null)
  128. {
  129. var layer = new MaxPooling2D(pool_size: pool_size,
  130. strides: strides,
  131. padding: padding,
  132. data_format: data_format,
  133. name: name);
  134. return layer.apply(inputs).Item1;
  135. }
  136. /// <summary>
  137. /// Densely-connected layer class. aka fully-connected<br></br>
  138. /// `outputs = activation(inputs * kernel + bias)`
  139. /// </summary>
  140. /// <param name="inputs"></param>
  141. /// <param name="units">Python integer, dimensionality of the output space.</param>
  142. /// <param name="activation"></param>
  143. /// <param name="use_bias">Boolean, whether the layer uses a bias.</param>
  144. /// <param name="kernel_initializer"></param>
  145. /// <param name="bias_initializer"></param>
  146. /// <param name="trainable"></param>
  147. /// <param name="name"></param>
  148. /// <param name="reuse"></param>
  149. /// <returns></returns>
  150. public Tensor dense(Tensor inputs,
  151. int units,
  152. IActivation activation = null,
  153. bool use_bias = true,
  154. IInitializer kernel_initializer = null,
  155. IInitializer bias_initializer = null,
  156. bool trainable = true,
  157. string name = null,
  158. bool? reuse = null)
  159. {
  160. if (bias_initializer == null)
  161. bias_initializer = tf.zeros_initializer;
  162. var layer = new Dense(units, activation,
  163. use_bias: use_bias,
  164. bias_initializer: bias_initializer,
  165. kernel_initializer: kernel_initializer,
  166. trainable: trainable,
  167. name: name);
  168. return layer.apply(inputs).Item1;
  169. }
  170. /// <summary>
  171. /// Flattens an input tensor while preserving the batch axis (axis 0).
  172. /// </summary>
  173. /// <param name="inputs">Tensor input.</param>
  174. /// <param name="name">The name of the layer.</param>
  175. /// <param name="data_format">
  176. /// A string, one of `channels_last` (default) or `channels_first`. <br></br>
  177. /// The ordering of the dimensions in the inputs. <br></br>
  178. /// `channels_last` corresponds to inputs with shape <br></br>
  179. /// `(batch, height, width, channels)` while `channels_first` corresponds to <br></br>
  180. /// inputs with shape `(batch, channels, height, width)`.
  181. /// </param>
  182. /// <returns></returns>
  183. public Tensor flatten(Tensor inputs,
  184. string name = null,
  185. string data_format = "channels_last")
  186. {
  187. var input_shape = inputs.shape;
  188. if (inputs.shape.Length == 0)
  189. throw new ValueError($"Input 0 of layer flatten is incompatible with the layer: : expected min_ndim={1}, found ndim={0}. Full shape received: ()");
  190. var premutation = new List<int>() {0};
  191. if (data_format == "channels_first" && inputs.NDims > 1)
  192. {
  193. premutation.AddRange(Binding.range(2, inputs.NDims));
  194. premutation.Add(1);
  195. inputs = array_ops.transpose(inputs, premutation.ToArray());
  196. }
  197. var ret = array_ops.reshape(inputs, compute_output_shape(input_shape));
  198. //ret.set_shape(compute_output_shape(ret.shape));
  199. return ret;
  200. int[] compute_output_shape(int[] inputshape)
  201. {
  202. if (inputshape == null || inputshape.Length == 0)
  203. inputshape = new int[] {1};
  204. if (inputshape.Skip(1).All(d => d > 0))
  205. {
  206. int[] output_shape = new int[2];
  207. output_shape[0] = inputshape[0];
  208. output_shape[1] = inputshape.Skip(1).Aggregate(1, (acc, rhs) => acc*rhs); //calculate size of all the rest dimensions
  209. return output_shape;
  210. } else
  211. return new int[] {inputshape[0], -1}; //-1 == Binding.None
  212. }
  213. }
  214. }
  215. }
  216. }