From 418172200488aacf2fe212923267e942bd212b1d Mon Sep 17 00:00:00 2001 From: Niklas Gustafsson Date: Thu, 25 Feb 2021 07:48:44 -0800 Subject: [PATCH 1/5] Adding doc comments to the Keras Layers Api class --- src/TensorFlowNET.Keras/Layers/LayersApi.cs | 362 ++++++++++++++++---- 1 file changed, 300 insertions(+), 62 deletions(-) diff --git a/src/TensorFlowNET.Keras/Layers/LayersApi.cs b/src/TensorFlowNET.Keras/Layers/LayersApi.cs index 9b889635..458e87f5 100644 --- a/src/TensorFlowNET.Keras/Layers/LayersApi.cs +++ b/src/TensorFlowNET.Keras/Layers/LayersApi.cs @@ -12,25 +12,31 @@ namespace Tensorflow.Keras.Layers public Preprocessing preprocessing { get; } = new Preprocessing(); /// - /// Functional interface for the batch normalization layer. + /// Layer that normalizes its inputs. + /// Batch normalization applies a transformation that maintains the mean output close to 0 and the output standard deviation close to 1. + /// Importantly, batch normalization works differently during training and during inference. + /// /// http://arxiv.org/abs/1502.03167 /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// + /// The axis that should be normalized (typically the features axis). + /// For instance, after a Conv2D layer with data_format="channels_first", set axis=1 in BatchNormalization. + /// + /// Momentum for the moving average. + /// Small float added to variance to avoid dividing by zero. + /// If True, add offset of beta to normalized tensor. If False, beta is ignored. + /// If True, multiply by gamma. If False, gamma is not used. When the next layer is linear (also e.g. nn.relu), this can be disabled since the scaling will be done by the next layer. + /// Initializer for the beta weight. + /// Initializer for the gamma weight. + /// Initializer for the moving mean. + /// Initializer for the moving variance. + /// Boolean, if True the variables will be marked as trainable. + /// Layer name. + /// Whether to use Batch Renormalization. This adds extra variables during training. The inference is the same for either value of this parameter. + /// Momentum used to update the moving means and standard deviations with renorm. + /// Unlike momentum, this affects training and should be neither too small (which would add noise) nor too large (which would give stale estimates). + /// Note that momentum is still applied to get the means and variances for inference. + /// + /// Tensor of the same shape as input. public BatchNormalization BatchNormalization(int axis = -1, float momentum = 0.99f, float epsilon = 0.001f, @@ -62,23 +68,25 @@ namespace Tensorflow.Keras.Layers }); /// - /// + /// 2D convolution layer (e.g. spatial convolution over images). + /// This layer creates a convolution kernel that is convolved with the layer input to produce a tensor of outputs. + /// If use_bias is True, a bias vector is created and added to the outputs.Finally, if activation is not None, it is applied to the outputs as well. /// - /// - /// - /// - /// - /// - /// - /// - /// tf.keras.activations - /// - /// - /// - /// - /// - /// - /// + /// Integer, the dimensionality of the output space (i.e. the number of output filters in the convolution) + /// An integer or tuple/list of 2 integers, specifying the height and width of the 2D convolution window. Can be a single integer to specify the same value for all spatial dimensions. + /// An integer or tuple/list of 2 integers, specifying the strides of the convolution along the height and width. Can be a single integer to specify the same value for all spatial dimensions. Specifying any stride value != 1 is incompatible with specifying any dilation_rate value != 1. + /// one of "valid" or "same" (case-insensitive). "valid" means no padding. "same" results in padding evenly to the left/right or up/down of the input such that output has the same height/width dimension as the input. + /// A string, one of channels_last (default) or channels_first. The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch_size, height, width, channels) while channels_first corresponds to inputs with shape (batch_size, channels, height, width). It defaults to the image_data_format value found in your Keras config file at ~/.keras/keras.json. If you never set it, then it will be channels_last. + /// an integer or tuple/list of 2 integers, specifying the dilation rate to use for dilated convolution. Can be a single integer to specify the same value for all spatial dimensions. Currently, specifying any dilation_rate value != 1 is incompatible with specifying any stride value != 1. + /// A positive integer specifying the number of groups in which the input is split along the channel axis. Each group is convolved separately with filters / groups filters. The output is the concatenation of all the groups results along the channel axis. Input channels and filters must both be divisible by groups. + /// Activation function to use. If you don't specify anything, no activation is applied (see keras.activations). + /// Boolean, whether the layer uses a bias vector. + /// Initializer for the kernel weights matrix (see keras.initializers). + /// Initializer for the bias vector (see keras.initializers). + /// Regularizer function applied to the kernel weights matrix (see keras.regularizers). + /// Regularizer function applied to the bias vector (see keras.regularizers). + /// Regularizer function applied to the output of the layer (its "activation") (see keras.regularizers). + /// A tensor of rank 4+ representing activation(conv2d(inputs, kernel) + bias). public Conv2D Conv2D(int filters, TensorShape kernel_size = null, TensorShape strides = null, @@ -112,6 +120,26 @@ namespace Tensorflow.Keras.Layers Activation = activation ?? keras.activations.Linear }); + /// + /// 2D convolution layer (e.g. spatial convolution over images). + /// This layer creates a convolution kernel that is convolved with the layer input to produce a tensor of outputs. + /// If use_bias is True, a bias vector is created and added to the outputs.Finally, if activation is not None, it is applied to the outputs as well. + /// + /// Integer, the dimensionality of the output space (i.e. the number of output filters in the convolution) + /// An integer or tuple/list of 2 integers, specifying the height and width of the 2D convolution window. Can be a single integer to specify the same value for all spatial dimensions. + /// An integer or tuple/list of 2 integers, specifying the strides of the convolution along the height and width. Can be a single integer to specify the same value for all spatial dimensions. Specifying any stride value != 1 is incompatible with specifying any dilation_rate value != 1. + /// one of "valid" or "same" (case-insensitive). "valid" means no padding. "same" results in padding evenly to the left/right or up/down of the input such that output has the same height/width dimension as the input. + /// A string, one of channels_last (default) or channels_first. The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch_size, height, width, channels) while channels_first corresponds to inputs with shape (batch_size, channels, height, width). It defaults to the image_data_format value found in your Keras config file at ~/.keras/keras.json. If you never set it, then it will be channels_last. + /// an integer or tuple/list of 2 integers, specifying the dilation rate to use for dilated convolution. Can be a single integer to specify the same value for all spatial dimensions. Currently, specifying any dilation_rate value != 1 is incompatible with specifying any stride value != 1. + /// A positive integer specifying the number of groups in which the input is split along the channel axis. Each group is convolved separately with filters / groups filters. The output is the concatenation of all the groups results along the channel axis. Input channels and filters must both be divisible by groups. + /// Activation function to use. If you don't specify anything, no activation is applied (see keras.activations). + /// Boolean, whether the layer uses a bias vector. + /// The name of the initializer for the kernel weights matrix (see keras.initializers). + /// The name of the initializer for the bias vector (see keras.initializers). + /// The name of the regularizer function applied to the kernel weights matrix (see keras.regularizers). + /// The name of the regularizer function applied to the bias vector (see keras.regularizers). + /// The name of the regularizer function applied to the output of the layer (its "activation") (see keras.regularizers). + /// A tensor of rank 4+ representing activation(conv2d(inputs, kernel) + bias). public Conv2D Conv2D(int filters, TensorShape kernel_size = null, TensorShape strides = null, @@ -145,24 +173,24 @@ namespace Tensorflow.Keras.Layers /// /// Transposed convolution layer (sometimes called Deconvolution). /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// + /// Integer, the dimensionality of the output space (i.e. the number of output filters in the convolution) + /// An integer or tuple/list of 2 integers, specifying the height and width of the 2D convolution window. Can be a single integer to specify the same value for all spatial dimensions. + /// An integer or tuple/list of 2 integers, specifying the strides of the convolution along the height and width. Can be a single integer to specify the same value for all spatial dimensions. Specifying any stride value != 1 is incompatible with specifying any dilation_rate value != 1. + /// one of "valid" or "same" (case-insensitive). "valid" means no padding. "same" results in padding evenly to the left/right or up/down of the input such that output has the same height/width dimension as the input. + /// A string, one of channels_last (default) or channels_first. The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch_size, height, width, channels) while channels_first corresponds to inputs with shape (batch_size, channels, height, width). It defaults to the image_data_format value found in your Keras config file at ~/.keras/keras.json. If you never set it, then it will be channels_last. + /// an integer or tuple/list of 2 integers, specifying the dilation rate to use for dilated convolution. Can be a single integer to specify the same value for all spatial dimensions. Currently, specifying any dilation_rate value != 1 is incompatible with specifying any stride value != 1. + /// Activation function to use. If you don't specify anything, no activation is applied (see keras.activations). + /// Boolean, whether the layer uses a bias vector. + /// The name of the initializer for the kernel weights matrix (see keras.initializers). + /// The name of the initializer for the bias vector (see keras.initializers). + /// The name of the regularizer function applied to the kernel weights matrix (see keras.regularizers). + /// The name of the regularizer function applied to the bias vector (see keras.regularizers). + /// The name of the regularizer function applied to the output of the layer (its "activation") (see keras.regularizers). + /// A tensor of rank 4+ representing activation(conv2d(inputs, kernel) + bias). public Conv2DTranspose Conv2DTranspose(int filters, TensorShape kernel_size = null, TensorShape strides = null, - string padding = "valid", + string output_padding = "valid", string data_format = null, TensorShape dilation_rate = null, string activation = null, @@ -178,7 +206,7 @@ namespace Tensorflow.Keras.Layers Filters = filters, KernelSize = kernel_size, Strides = strides == null ? (1, 1) : strides, - Padding = padding, + Padding = output_padding, DataFormat = data_format, DilationRate = dilation_rate == null ? (1, 1) : dilation_rate, UseBias = use_bias, @@ -187,6 +215,20 @@ namespace Tensorflow.Keras.Layers Activation = GetActivationByName(activation) }); + /// + /// Just your regular densely-connected NN layer. + /// + /// Dense implements the operation: output = activation(dot(input, kernel) + bias) where activation is the + /// element-wise activation function passed as the activation argument, kernel is a weights matrix created by the layer, + /// and bias is a bias vector created by the layer (only applicable if use_bias is True). + /// + /// Positive integer, dimensionality of the output space. + /// Activation function to use. If you don't specify anything, no activation is applied (ie. "linear" activation: a(x) = x). + /// Initializer for the kernel weights matrix. + /// Boolean, whether the layer uses a bias vector. + /// Initializer for the bias vector. + /// N-D tensor with shape: (batch_size, ..., input_dim). The most common situation would be a 2D input with shape (batch_size, input_dim). + /// N-D tensor with shape: (batch_size, ..., units). For instance, for a 2D input with shape (batch_size, input_dim), the output would have shape (batch_size, units). public Dense Dense(int units, Activation activation = null, IInitializer kernel_initializer = null, @@ -202,6 +244,15 @@ namespace Tensorflow.Keras.Layers InputShape = input_shape }); + /// + /// Just your regular densely-connected NN layer. + /// + /// Dense implements the operation: output = activation(dot(input, kernel) + bias) where activation is the + /// element-wise activation function passed as the activation argument, kernel is a weights matrix created by the layer, + /// and bias is a bias vector created by the layer (only applicable if use_bias is True). + /// + /// Positive integer, dimensionality of the output space. + /// N-D tensor with shape: (batch_size, ..., units). For instance, for a 2D input with shape (batch_size, input_dim), the output would have shape (batch_size, units). public Dense Dense(int units) => new Dense(new DenseArgs { @@ -209,6 +260,17 @@ namespace Tensorflow.Keras.Layers Activation = GetActivationByName("linear") }); + /// + /// Just your regular densely-connected NN layer. + /// + /// Dense implements the operation: output = activation(dot(input, kernel) + bias) where activation is the + /// element-wise activation function passed as the activation argument, kernel is a weights matrix created by the layer, + /// and bias is a bias vector created by the layer (only applicable if use_bias is True). + /// + /// Positive integer, dimensionality of the output space. + /// Activation function to use. If you don't specify anything, no activation is applied (ie. "linear" activation: a(x) = x). + /// N-D tensor with shape: (batch_size, ..., input_dim). The most common situation would be a 2D input with shape (batch_size, input_dim). + /// N-D tensor with shape: (batch_size, ..., units). For instance, for a 2D input with shape (batch_size, input_dim), the output would have shape (batch_size, units). public Dense Dense(int units, string activation = null, TensorShape input_shape = null) @@ -260,6 +322,18 @@ namespace Tensorflow.Keras.Layers return layer.Apply(inputs); } + /// + /// Applies Dropout to the input. + /// The Dropout layer randomly sets input units to 0 with a frequency of rate at each step during training time, + /// which helps prevent overfitting.Inputs not set to 0 are scaled up by 1/(1 - rate) such that the sum over all inputs is unchanged. + /// + /// Float between 0 and 1. Fraction of the input units to drop. + /// 1D integer tensor representing the shape of the binary dropout mask that will be multiplied with the input. For instance, + /// if your inputs have shape (batch_size, timesteps, features) and you want the dropout mask to be the same for all timesteps, + /// you can use noise_shape=(batch_size, 1, features). + /// + /// An integer to use as random seed. + /// public Dropout Dropout(float rate, TensorShape noise_shape = null, int? seed = null) => new Dropout(new DropoutArgs { @@ -295,6 +369,15 @@ namespace Tensorflow.Keras.Layers EmbeddingsInitializer = embeddings_initializer }); + /// + /// Flattens the input. Does not affect the batch size. + /// + /// A string, one of channels_last (default) or channels_first. The ordering of the dimensions in the inputs. + /// channels_last corresponds to inputs with shape (batch, ..., channels) while channels_first corresponds to inputs with shape (batch, channels, ...). + /// It defaults to the image_data_format value found in your Keras config file at ~/.keras/keras.json. + /// If you never set it, then it will be "channels_last". + /// + /// public Flatten Flatten(string data_format = null) => new Flatten(new FlattenArgs { @@ -303,12 +386,18 @@ namespace Tensorflow.Keras.Layers /// /// `Input()` is used to instantiate a Keras tensor. + /// Keras tensor is a TensorFlow symbolic tensor object, which we augment with certain attributes that allow us + /// to build a Keras model just by knowing the inputs and outputs of the model. /// /// A shape tuple not including the batch size. - /// - /// - /// - /// + /// An optional name string for the layer. Should be unique in a model (do not reuse the same name twice). It will be autogenerated if it isn't provided. + /// A boolean specifying whether the placeholder to be created is sparse. Only one of 'ragged' and 'sparse' can be True. + /// Note that, if sparse is False, sparse tensors can still be passed into the input - they will be densified with a default value of 0. + /// + /// A boolean specifying whether the placeholder to be created is ragged. Only one of 'ragged' and 'sparse' can be True. + /// In this case, values of 'None' in the 'shape' argument represent ragged dimensions. For more information about RaggedTensors, see this guide. + /// + /// A tensor. public Tensors Input(TensorShape shape, string name = null, bool sparse = false, @@ -325,35 +414,90 @@ namespace Tensorflow.Keras.Layers return input_layer.InboundNodes[0].Outputs; } + /// + /// Max pooling operation for 1D temporal data. + /// + /// Integer, size of the max pooling window. + /// Integer, or null. Specifies how much the pooling window moves for each pooling step. If null, it will default to pool_size. + /// One of "valid" or "same" (case-insensitive). "valid" means no padding. + /// "same" results in padding evenly to the left/right or up/down of the input such that output has the same height/width dimension as the input. + /// + /// + /// A string, one of channels_last (default) or channels_first. The ordering of the dimensions in the inputs. + /// channels_last corresponds to inputs with shape (batch, steps, features) while channels_first corresponds to inputs with shape (batch, features, steps). + /// + /// public MaxPooling1D MaxPooling1D(int? pool_size = null, int? strides = null, - string padding = "valid") + string padding = "valid", + string data_format = null) => new MaxPooling1D(new Pooling1DArgs { PoolSize = pool_size ?? 2, Strides = strides ?? (pool_size ?? 2), - Padding = padding + Padding = padding, + DataFormat = data_format }); + /// + /// Max pooling operation for 2D spatial data. + /// Downsamples the input representation by taking the maximum value over the window defined by pool_size for each dimension along the features axis. + /// The window is shifted by strides in each dimension. The resulting output when using "valid" padding option has a shape(number of rows or columns) + /// of: output_shape = (input_shape - pool_size + 1) / strides) + /// The resulting output shape when using the "same" padding option is: output_shape = input_shape / strides + /// + /// + /// Integer or tuple of 2 integers, window size over which to take the maximum. + /// (2, 2) will take the max value over a 2x2 pooling window. If only one integer is specified, the same window length will be used for both dimensions. + /// + /// + /// Integer, tuple of 2 integers, or null. Strides values. Specifies how far the pooling window moves for each pooling step. + /// If null, it will default to pool_size. + /// + /// One of "valid" or "same" (case-insensitive). "valid" means no padding. + /// "same" results in padding evenly to the left/right or up/down of the input such that output has the same height/width dimension as the input. + /// + /// + /// A string, one of channels_last (default) or channels_first. The ordering of the dimensions in the inputs. + /// channels_last corresponds to inputs with shape (batch, height, width, channels) while channels_first corresponds to + /// inputs with shape (batch, channels, height, width). + /// It defaults to the image_data_format value found in your Keras config file at ~/.keras/keras.json. + /// If you never set it, then it will be "channels_last" + /// public MaxPooling2D MaxPooling2D(TensorShape pool_size = null, TensorShape strides = null, - string padding = "valid") + string padding = "valid", + string data_format = null) => new MaxPooling2D(new MaxPooling2DArgs { PoolSize = pool_size ?? (2, 2), Strides = strides, - Padding = padding + Padding = padding, + DataFormat = data_format }); /// /// Max pooling layer for 2D inputs (e.g. images). /// /// The tensor over which to pool. Must have rank 4. - /// - /// - /// - /// - /// + /// + /// Integer or tuple of 2 integers, window size over which to take the maximum. + /// (2, 2) will take the max value over a 2x2 pooling window. If only one integer is specified, the same window length will be used for both dimensions. + /// + /// + /// Integer, tuple of 2 integers, or null. Strides values. Specifies how far the pooling window moves for each pooling step. + /// If null, it will default to pool_size. + /// + /// One of "valid" or "same" (case-insensitive). "valid" means no padding. + /// "same" results in padding evenly to the left/right or up/down of the input such that output has the same height/width dimension as the input. + /// + /// + /// A string, one of channels_last (default) or channels_first. The ordering of the dimensions in the inputs. + /// channels_last corresponds to inputs with shape (batch, height, width, channels) while channels_first corresponds to + /// inputs with shape (batch, channels, height, width). + /// It defaults to the image_data_format value found in your Keras config file at ~/.keras/keras.json. + /// If you never set it, then it will be "channels_last" + /// A name for the layer /// public Tensor max_pooling2d(Tensor inputs, int[] pool_size, @@ -385,8 +529,19 @@ namespace Tensorflow.Keras.Layers Alpha = alpha }); + /// + /// Fully-connected RNN where the output is to be fed back to input. + /// + /// Positive integer, dimensionality of the output space. + /// public Layer SimpleRNN(int units) => SimpleRNN(units, "tanh"); + /// + /// Fully-connected RNN where the output is to be fed back to input. + /// + /// Positive integer, dimensionality of the output space. + /// Activation function to use. If you pass null, no activation is applied (ie. "linear" activation: a(x) = x). + /// public Layer SimpleRNN(int units, Activation activation = null) => new SimpleRNN(new SimpleRNNArgs @@ -395,6 +550,12 @@ namespace Tensorflow.Keras.Layers Activation = activation }); + /// + /// + /// + /// Positive integer, dimensionality of the output space. + /// The name of the activation function to use. Default: hyperbolic tangent (tanh).. + /// public Layer SimpleRNN(int units, string activation = "tanh") => new SimpleRNN(new SimpleRNNArgs @@ -403,6 +564,27 @@ namespace Tensorflow.Keras.Layers Activation = GetActivationByName(activation) }); + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// public Layer LSTM(int units, Activation activation = null, Activation recurrent_activation = null, @@ -439,6 +621,13 @@ namespace Tensorflow.Keras.Layers Unroll = unroll }); + /// + /// + /// + /// + /// + /// + /// public Rescaling Rescaling(float scale, float offset = 0, TensorShape input_shape = null) @@ -449,28 +638,72 @@ namespace Tensorflow.Keras.Layers InputShape = input_shape }); + /// + /// + /// + /// public Add Add() => new Add(new MergeArgs { }); + /// + /// + /// + /// public Subtract Subtract() => new Subtract(new MergeArgs { }); + /// + /// Global max pooling operation for spatial data. + /// + /// public GlobalAveragePooling2D GlobalAveragePooling2D() => new GlobalAveragePooling2D(new Pooling2DArgs { }); + /// + /// Global average pooling operation for temporal data. + /// + /// A string, one of channels_last (default) or channels_first. The ordering of the dimensions in the inputs. + /// channels_last corresponds to inputs with shape (batch, steps, features) while channels_first corresponds to inputs with shape (batch, features, steps). + /// + /// public GlobalAveragePooling1D GlobalAveragePooling1D(string data_format = "channels_last") => new GlobalAveragePooling1D(new Pooling1DArgs { DataFormat = data_format }); + /// + /// Global max pooling operation for spatial data. + /// + /// A string, one of channels_last (default) or channels_first. The ordering of the dimensions in the inputs. + /// channels_last corresponds to inputs with shape (batch, height, width, channels) while channels_first corresponds to inputs with shape (batch, channels, height, width). + /// public GlobalAveragePooling2D GlobalAveragePooling2D(string data_format = "channels_last") => new GlobalAveragePooling2D(new Pooling2DArgs { DataFormat = data_format }); + /// + /// Global max pooling operation for 1D temporal data. + /// Downsamples the input representation by taking the maximum value over the time dimension. + /// + /// A string, one of channels_last (default) or channels_first. The ordering of the dimensions in the inputs. + /// channels_last corresponds to inputs with shape (batch, steps, features) while channels_first corresponds to inputs with shape (batch, features, steps). + /// + /// public GlobalMaxPooling1D GlobalMaxPooling1D(string data_format = "channels_last") => new GlobalMaxPooling1D(new Pooling1DArgs { DataFormat = data_format }); + /// + /// Global max pooling operation for spatial data. + /// + /// A string, one of channels_last (default) or channels_first. The ordering of the dimensions in the inputs. + /// channels_last corresponds to inputs with shape (batch, height, width, channels) while channels_first corresponds to inputs with shape (batch, channels, height, width). + /// public GlobalMaxPooling2D GlobalMaxPooling2D(string data_format = "channels_last") => new GlobalMaxPooling2D(new Pooling2DArgs { DataFormat = data_format }); + /// + /// Get an activation function layer from its name. + /// + /// The name of the activation function. One of linear, relu, sigmoid, and tanh. + /// Activation GetActivationByName(string name) => name switch @@ -482,6 +715,11 @@ namespace Tensorflow.Keras.Layers _ => keras.activations.Linear }; + /// + /// Get an weights initializer from its name. + /// + /// The name of the initializer. One of zeros, ones, and glorot_uniform. + /// IInitializer GetInitializerByName(string name) => name switch { From 3a2b270a7ededc8125558fe23f1afa7b7681fc91 Mon Sep 17 00:00:00 2001 From: Niklas Gustafsson Date: Thu, 25 Feb 2021 07:58:15 -0800 Subject: [PATCH 2/5] Adding doc comment for LSTM --- src/TensorFlowNET.Keras/Layers/LayersApi.cs | 40 ++++++++++++--------- 1 file changed, 23 insertions(+), 17 deletions(-) diff --git a/src/TensorFlowNET.Keras/Layers/LayersApi.cs b/src/TensorFlowNET.Keras/Layers/LayersApi.cs index 458e87f5..3cd46c28 100644 --- a/src/TensorFlowNET.Keras/Layers/LayersApi.cs +++ b/src/TensorFlowNET.Keras/Layers/LayersApi.cs @@ -565,25 +565,31 @@ namespace Tensorflow.Keras.Layers }); /// - /// + /// Long Short-Term Memory layer - Hochreiter 1997. /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// + /// Positive integer, dimensionality of the output space. + /// Activation function to use. If you pass null, no activation is applied (ie. "linear" activation: a(x) = x). + /// Activation function to use for the recurrent step. If you pass null, no activation is applied (ie. "linear" activation: a(x) = x). + /// Boolean (default True), whether the layer uses a bias vector. + /// Initializer for the kernel weights matrix, used for the linear transformation of the inputs. Default: glorot_uniform. + /// Initializer for the recurrent_kernel weights matrix, used for the linear transformation of the recurrent state. Default: orthogonal. + /// Initializer for the bias vector. Default: zeros. + /// Boolean (default True). If True, add 1 to the bias of the forget gate at initialization. Setting it to true will also force bias_initializer="zeros". This is recommended in Jozefowicz et al.. + /// Float between 0 and 1. Fraction of the units to drop for the linear transformation of the inputs. Default: 0. + /// Float between 0 and 1. Fraction of the units to drop for the linear transformation of the recurrent state. Default: 0. /// - /// - /// - /// - /// - /// - /// + /// Boolean. Whether to return the last output. in the output sequence, or the full sequence. Default: False. + /// Whether to return the last state in addition to the output. Default: False. + /// Boolean (default false). If True, process the input sequence backwards and return the reversed sequence. + /// Boolean (default False). If True, the last state for each sample at index i in a batch will be used as initial state for the sample of index i in the following batch. + /// + /// The shape format of the inputs and outputs tensors. If True, the inputs and outputs will be in shape [timesteps, batch, feature], + /// whereas in the False case, it will be [batch, timesteps, feature]. Using time_major = True is a bit more efficient because it avoids transposes at the + /// beginning and end of the RNN calculation. However, most TensorFlow data is batch-major, so by default this function accepts input and emits output in batch-major form. + /// + /// Boolean (default False). If True, the network will be unrolled, else a symbolic loop will be used. Unrolling can speed-up a RNN, + /// although it tends to be more memory-intensive. Unrolling is only suitable for short sequences. + /// /// public Layer LSTM(int units, Activation activation = null, From f3da1cd9b780508a36c16fe02f192b06b47db63a Mon Sep 17 00:00:00 2001 From: Niklas Gustafsson Date: Thu, 25 Feb 2021 14:21:49 -0800 Subject: [PATCH 3/5] Added unit tests for Conv2D --- src/TensorFlowNET.Keras/Layers/LayersApi.cs | 5 +- .../Layers/Layers.Convolution.Test.cs | 91 +++++++++++++++++++ 2 files changed, 94 insertions(+), 2 deletions(-) create mode 100644 test/TensorFlowNET.Keras.UnitTest/Layers/Layers.Convolution.Test.cs diff --git a/src/TensorFlowNET.Keras/Layers/LayersApi.cs b/src/TensorFlowNET.Keras/Layers/LayersApi.cs index 3cd46c28..dff9ff1b 100644 --- a/src/TensorFlowNET.Keras/Layers/LayersApi.cs +++ b/src/TensorFlowNET.Keras/Layers/LayersApi.cs @@ -66,7 +66,7 @@ namespace Tensorflow.Keras.Layers Trainable = trainable, Name = name }); - +#if false /// /// 2D convolution layer (e.g. spatial convolution over images). /// This layer creates a convolution kernel that is convolved with the layer input to produce a tensor of outputs. @@ -119,6 +119,7 @@ namespace Tensorflow.Keras.Layers ActivityRegularizer = activity_regularizer, Activation = activation ?? keras.activations.Linear }); +#endif /// /// 2D convolution layer (e.g. spatial convolution over images). @@ -158,7 +159,7 @@ namespace Tensorflow.Keras.Layers { Rank = 2, Filters = filters, - KernelSize = kernel_size, + KernelSize = (kernel_size == null) ? (5,5) : kernel_size, Strides = strides == null ? (1, 1) : strides, Padding = padding, DataFormat = data_format, diff --git a/test/TensorFlowNET.Keras.UnitTest/Layers/Layers.Convolution.Test.cs b/test/TensorFlowNET.Keras.UnitTest/Layers/Layers.Convolution.Test.cs new file mode 100644 index 00000000..b24b214a --- /dev/null +++ b/test/TensorFlowNET.Keras.UnitTest/Layers/Layers.Convolution.Test.cs @@ -0,0 +1,91 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; +using NumSharp; +using Tensorflow; +using static Tensorflow.KerasApi; + +namespace TensorFlowNET.Keras.UnitTest +{ + [TestClass] + public class LayersConvolutionTest : EagerModeTestBase + { + [TestMethod] + public void BasicConv2D() + { + var filters = 8; + var conv = keras.layers.Conv2D(filters); + + var x = np.arange(256.0f).reshape(1,8,8,4); + var y = conv.Apply(x); + + Assert.AreEqual(4, y.shape.ndim); + Assert.AreEqual(x.shape[0], y.shape[0]); + Assert.AreEqual(x.shape[1] - 4, y.shape[1]); + Assert.AreEqual(x.shape[2] - 4, y.shape[2]); + Assert.AreEqual(filters, y.shape[3]); + } + + [TestMethod] + public void BasicConv2D_ksize() + { + var filters = 8; + var conv = keras.layers.Conv2D(filters, kernel_size: 3); + + var x = np.arange(256.0f).reshape(1, 8, 8, 4); + var y = conv.Apply(x); + + Assert.AreEqual(4, y.shape.ndim); + Assert.AreEqual(x.shape[0], y.shape[0]); + Assert.AreEqual(x.shape[1] - 2, y.shape[1]); + Assert.AreEqual(x.shape[2] - 2, y.shape[2]); + Assert.AreEqual(filters, y.shape[3]); + } + + [TestMethod] + public void BasicConv2D_ksize_same() + { + var filters = 8; + var conv = keras.layers.Conv2D(filters, kernel_size: 3, padding: "same"); + + var x = np.arange(256.0f).reshape(1, 8, 8, 4); + var y = conv.Apply(x); + + Assert.AreEqual(4, y.shape.ndim); + Assert.AreEqual(x.shape[0], y.shape[0]); + Assert.AreEqual(x.shape[1], y.shape[1]); + Assert.AreEqual(x.shape[2], y.shape[2]); + Assert.AreEqual(filters, y.shape[3]); + } + + [TestMethod] + public void BasicConv2D_ksize_strides() + { + var filters = 8; + var conv = keras.layers.Conv2D(filters, kernel_size: 3, strides: 2); + + var x = np.arange(256.0f).reshape(1, 8, 8, 4); + var y = conv.Apply(x); + + Assert.AreEqual(4, y.shape.ndim); + Assert.AreEqual(x.shape[0], y.shape[0]); + Assert.AreEqual(x.shape[1] - 5, y.shape[1]); + Assert.AreEqual(x.shape[2] - 5, y.shape[2]); + Assert.AreEqual(filters, y.shape[3]); + } + + [TestMethod] + public void BasicConv2D_ksize_dilation() + { + var filters = 8; + var conv = keras.layers.Conv2D(filters, kernel_size: 3, dilation_rate: 2); + + var x = np.arange(256.0f).reshape(1, 8, 8, 4); + var y = conv.Apply(x); + + Assert.AreEqual(4, y.shape.ndim); + Assert.AreEqual(x.shape[0], y.shape[0]); + Assert.AreEqual(x.shape[1] - 4, y.shape[1]); + Assert.AreEqual(x.shape[2] - 4, y.shape[2]); + Assert.AreEqual(filters, y.shape[3]); + } + } +} From 2a42bcd09b6c33829fa152effcb7640cda49aa3b Mon Sep 17 00:00:00 2001 From: Niklas Gustafsson Date: Thu, 25 Feb 2021 14:38:18 -0800 Subject: [PATCH 4/5] Added unit tests for Keras Conv2D --- src/TensorFlowNET.Keras/Layers/LayersApi.cs | 3 +-- .../Layers/Layers.Convolution.Test.cs | 26 +++++++++++++++---- 2 files changed, 22 insertions(+), 7 deletions(-) diff --git a/src/TensorFlowNET.Keras/Layers/LayersApi.cs b/src/TensorFlowNET.Keras/Layers/LayersApi.cs index dff9ff1b..6c3e3556 100644 --- a/src/TensorFlowNET.Keras/Layers/LayersApi.cs +++ b/src/TensorFlowNET.Keras/Layers/LayersApi.cs @@ -66,7 +66,7 @@ namespace Tensorflow.Keras.Layers Trainable = trainable, Name = name }); -#if false + /// /// 2D convolution layer (e.g. spatial convolution over images). /// This layer creates a convolution kernel that is convolved with the layer input to produce a tensor of outputs. @@ -119,7 +119,6 @@ namespace Tensorflow.Keras.Layers ActivityRegularizer = activity_regularizer, Activation = activation ?? keras.activations.Linear }); -#endif /// /// 2D convolution layer (e.g. spatial convolution over images). diff --git a/test/TensorFlowNET.Keras.UnitTest/Layers/Layers.Convolution.Test.cs b/test/TensorFlowNET.Keras.UnitTest/Layers/Layers.Convolution.Test.cs index b24b214a..5e71ece6 100644 --- a/test/TensorFlowNET.Keras.UnitTest/Layers/Layers.Convolution.Test.cs +++ b/test/TensorFlowNET.Keras.UnitTest/Layers/Layers.Convolution.Test.cs @@ -12,7 +12,7 @@ namespace TensorFlowNET.Keras.UnitTest public void BasicConv2D() { var filters = 8; - var conv = keras.layers.Conv2D(filters); + var conv = keras.layers.Conv2D(filters, activation: "linear"); var x = np.arange(256.0f).reshape(1,8,8,4); var y = conv.Apply(x); @@ -28,7 +28,7 @@ namespace TensorFlowNET.Keras.UnitTest public void BasicConv2D_ksize() { var filters = 8; - var conv = keras.layers.Conv2D(filters, kernel_size: 3); + var conv = keras.layers.Conv2D(filters, kernel_size: 3, activation: "linear"); var x = np.arange(256.0f).reshape(1, 8, 8, 4); var y = conv.Apply(x); @@ -44,7 +44,7 @@ namespace TensorFlowNET.Keras.UnitTest public void BasicConv2D_ksize_same() { var filters = 8; - var conv = keras.layers.Conv2D(filters, kernel_size: 3, padding: "same"); + var conv = keras.layers.Conv2D(filters, kernel_size: 3, padding: "same", activation: "linear"); var x = np.arange(256.0f).reshape(1, 8, 8, 4); var y = conv.Apply(x); @@ -60,7 +60,7 @@ namespace TensorFlowNET.Keras.UnitTest public void BasicConv2D_ksize_strides() { var filters = 8; - var conv = keras.layers.Conv2D(filters, kernel_size: 3, strides: 2); + var conv = keras.layers.Conv2D(filters, kernel_size: 3, strides: 2, activation: "linear"); var x = np.arange(256.0f).reshape(1, 8, 8, 4); var y = conv.Apply(x); @@ -76,7 +76,7 @@ namespace TensorFlowNET.Keras.UnitTest public void BasicConv2D_ksize_dilation() { var filters = 8; - var conv = keras.layers.Conv2D(filters, kernel_size: 3, dilation_rate: 2); + var conv = keras.layers.Conv2D(filters, kernel_size: 3, dilation_rate: 2, activation: "linear"); var x = np.arange(256.0f).reshape(1, 8, 8, 4); var y = conv.Apply(x); @@ -87,5 +87,21 @@ namespace TensorFlowNET.Keras.UnitTest Assert.AreEqual(x.shape[2] - 4, y.shape[2]); Assert.AreEqual(filters, y.shape[3]); } + + [TestMethod] + public void BasicConv2D_ksize_dilation_same() + { + var filters = 8; + var conv = keras.layers.Conv2D(filters, kernel_size: 3, dilation_rate: 2, padding: "same", activation: "linear"); + + var x = np.arange(256.0f).reshape(1, 8, 8, 4); + var y = conv.Apply(x); + + Assert.AreEqual(4, y.shape.ndim); + Assert.AreEqual(x.shape[0], y.shape[0]); + Assert.AreEqual(x.shape[1], y.shape[1]); + Assert.AreEqual(x.shape[2], y.shape[2]); + Assert.AreEqual(filters, y.shape[3]); + } } } From 616b62bd4f109f1f3b38c8f0111604dea8490e82 Mon Sep 17 00:00:00 2001 From: Niklas Gustafsson Date: Thu, 25 Feb 2021 18:15:03 -0800 Subject: [PATCH 5/5] Implemented Conv1D and unit tests. --- .../ArgsDefinition/Convolution/Conv1DArgs.cs | 7 ++ .../Operations/NnOps/Conv1dParams.cs | 81 ++++++++++++ .../Operations/NnOps/ConvolutionInternal.cs | 47 +++++-- src/TensorFlowNET.Core/Operations/nn_ops.cs | 2 + .../Layers/Convolution/Conv1D.cs | 28 +++++ .../Layers/Convolution/Convolutional.cs | 1 + src/TensorFlowNET.Keras/Layers/LayersApi.cs | 116 +++++++++++++++++- .../Layers/Layers.Convolution.Test.cs | 94 ++++++++++++++ 8 files changed, 362 insertions(+), 14 deletions(-) create mode 100644 src/TensorFlowNET.Core/Keras/ArgsDefinition/Convolution/Conv1DArgs.cs create mode 100644 src/TensorFlowNET.Core/Operations/NnOps/Conv1dParams.cs create mode 100644 src/TensorFlowNET.Keras/Layers/Convolution/Conv1D.cs diff --git a/src/TensorFlowNET.Core/Keras/ArgsDefinition/Convolution/Conv1DArgs.cs b/src/TensorFlowNET.Core/Keras/ArgsDefinition/Convolution/Conv1DArgs.cs new file mode 100644 index 00000000..c461f7d2 --- /dev/null +++ b/src/TensorFlowNET.Core/Keras/ArgsDefinition/Convolution/Conv1DArgs.cs @@ -0,0 +1,7 @@ +namespace Tensorflow.Keras.ArgsDefinition +{ + public class Conv1DArgs : ConvolutionalArgs + { + + } +} diff --git a/src/TensorFlowNET.Core/Operations/NnOps/Conv1dParams.cs b/src/TensorFlowNET.Core/Operations/NnOps/Conv1dParams.cs new file mode 100644 index 00000000..4282a279 --- /dev/null +++ b/src/TensorFlowNET.Core/Operations/NnOps/Conv1dParams.cs @@ -0,0 +1,81 @@ +/***************************************************************************** + Copyright 2018 The TensorFlow.NET Authors. All Rights Reserved. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +******************************************************************************/ + +namespace Tensorflow.Operations +{ + public class Conv1dParams + { + public string Name { get; set; } + + /// + /// An optional `string` from: `"NHWC", "NCHW"`. Defaults to `"NHWC"`. + /// Specify the data format of the input and output data. With the + /// default format "NHWC", the data is stored in the order of: + /// [batch, height, width, channels]. + /// + public string DataFormat { get; set; } = "NHWC"; + + /// + /// Must be one of the following types: `half`, `bfloat16`, `float32`, `float64`. + /// A 4-D tensor. The dimension order is interpreted according to the value + /// + public Tensor Input { get; set; } + + /// + /// An integer vector representing the shape of `input` + /// + public Tensor InputSizes { get; set; } + + /// + /// A 4-D tensor of shape + /// + public IVariableV1 Filter { get; set; } + + /// + /// An integer vector representing the tensor shape of `filter` + /// + public Tensor FilterSizes { get; set; } + + /// + /// A `Tensor`. Must have the same type as `filter`. + /// 4-D with shape `[batch, out_height, out_width, out_channels]`. + /// + public Tensor OutBackProp { get; set; } + + /// + /// The stride of the sliding window for each + /// dimension of `input`. The dimension order is determined by the value of + /// `data_format`, see below for details. + /// + public int[] Strides { get; set; } + + /// + /// A `string` from: `"SAME", "VALID", "EXPLICIT"`. + /// + public string Padding { get; set; } + + public int[] ExplicitPaddings { get; set; } = new int[0]; + + public bool UseCudnnOnGpu { get; set; } = true; + + public int[] Dilations { get; set; } = new int[] { 1, 1, 1 }; + + public Conv1dParams() + { + + } + } +} diff --git a/src/TensorFlowNET.Core/Operations/NnOps/ConvolutionInternal.cs b/src/TensorFlowNET.Core/Operations/NnOps/ConvolutionInternal.cs index b1a65ce8..67701430 100644 --- a/src/TensorFlowNET.Core/Operations/NnOps/ConvolutionInternal.cs +++ b/src/TensorFlowNET.Core/Operations/NnOps/ConvolutionInternal.cs @@ -41,8 +41,15 @@ namespace Tensorflow.Operations var filters_rank = filters.shape.rank; var inputs_rank = input.shape.rank; var num_spatial_dims = args.NumSpatialDims; - if (num_spatial_dims == Unknown) + if (args.Rank == 1) + { + // Special case: Conv1D + num_spatial_dims = 1; + } + else if (num_spatial_dims == Unknown) + { num_spatial_dims = filters_rank - 2; + } // Channel dimension. var num_batch_dims = inputs_rank - num_spatial_dims - 1; @@ -50,16 +57,16 @@ namespace Tensorflow.Operations throw new ValueError($"num_spatial_dims (input.shape.ndims - num_batch_dims - 1) must be one " + $"of 1, 2 or 3 but saw {num_spatial_dims}. num_batch_dims: {num_batch_dims}."); - var channel_index = num_batch_dims + num_spatial_dims; - var dilations = _get_sequence(args.DilationRate, num_spatial_dims, channel_index); - var strides = _get_sequence(args.Strides, num_spatial_dims, channel_index); - Tensor result = null; tf_with(ops.name_scope(name, default_name: null), scope => { name = scope; if (num_spatial_dims == 2) { + var channel_index = num_batch_dims + num_spatial_dims; + var dilations = _get_sequence(args.DilationRate, num_spatial_dims, channel_index).ToArray(); + var strides = _get_sequence(args.Strides, num_spatial_dims, channel_index).ToArray(); + result = gen_nn_ops.conv2d(new Conv2dParams { Input = input, @@ -72,13 +79,37 @@ namespace Tensorflow.Operations }); } else - throw new NotImplementedException(""); + { + var channel_first = data_format == "NCW"; + var spatial_start_dim = channel_first ? -2 : -3; + + var channel_index = channel_first ? 1 : 2; + var dilations = _get_sequence(args.DilationRate, 1, channel_index); + var strides = _get_sequence(args.Strides, 1, channel_index); + + strides.Insert(0, 1); + dilations.Insert(0, 1); + + var expanded = tf.expand_dims(input, spatial_start_dim); + + result = gen_nn_ops.conv2d(new Conv2dParams + { + Input = expanded, + Filter = filters, + Strides = strides.ToArray(), + Padding = padding, + DataFormat = channel_first ? "NCHW" : "NHWC", + Dilations = dilations.ToArray(), + Name = name + }); + result = tf.squeeze(result, squeeze_dims: spatial_start_dim); + } }); return result; } - int[] _get_sequence(int[] value, int n, int channel_index) + IList _get_sequence(int[] value, int n, int channel_index) { var seq = new List(); @@ -95,7 +126,7 @@ namespace Tensorflow.Operations seq.Add(1); } - return seq.ToArray(); + return seq; } } } diff --git a/src/TensorFlowNET.Core/Operations/nn_ops.cs b/src/TensorFlowNET.Core/Operations/nn_ops.cs index b449b0dc..468ba3b1 100644 --- a/src/TensorFlowNET.Core/Operations/nn_ops.cs +++ b/src/TensorFlowNET.Core/Operations/nn_ops.cs @@ -27,9 +27,11 @@ namespace Tensorflow public static ConvolutionInternal convolution_internal(string padding, int[] strides, int[] dilation_rate, + int rank, string name = null, string data_format = null) => new ConvolutionInternal(new ConvolutionalArgs { + Rank = rank, Padding = padding, Strides = strides, DilationRate = dilation_rate, diff --git a/src/TensorFlowNET.Keras/Layers/Convolution/Conv1D.cs b/src/TensorFlowNET.Keras/Layers/Convolution/Conv1D.cs new file mode 100644 index 00000000..d62b33a5 --- /dev/null +++ b/src/TensorFlowNET.Keras/Layers/Convolution/Conv1D.cs @@ -0,0 +1,28 @@ +/***************************************************************************** + Copyright 2018 The TensorFlow.NET Authors. All Rights Reserved. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +******************************************************************************/ + +using Tensorflow.Keras.ArgsDefinition; + +namespace Tensorflow.Keras.Layers +{ + public class Conv1D : Convolutional + { + public Conv1D(Conv1DArgs args) : base(args) + { + + } + } +} diff --git a/src/TensorFlowNET.Keras/Layers/Convolution/Convolutional.cs b/src/TensorFlowNET.Keras/Layers/Convolution/Convolutional.cs index 2139fd32..7a1644ec 100644 --- a/src/TensorFlowNET.Keras/Layers/Convolution/Convolutional.cs +++ b/src/TensorFlowNET.Keras/Layers/Convolution/Convolutional.cs @@ -93,6 +93,7 @@ namespace Tensorflow.Keras.Layers _convolution_op = nn_ops.convolution_internal(tf_padding, strides, dilation_rate, + rank, data_format: _tf_data_format, name: tf_op_name); diff --git a/src/TensorFlowNET.Keras/Layers/LayersApi.cs b/src/TensorFlowNET.Keras/Layers/LayersApi.cs index 6c3e3556..b7cefb66 100644 --- a/src/TensorFlowNET.Keras/Layers/LayersApi.cs +++ b/src/TensorFlowNET.Keras/Layers/LayersApi.cs @@ -67,6 +67,113 @@ namespace Tensorflow.Keras.Layers Name = name }); + /// + /// 1D convolution layer (e.g. temporal convolution). + /// This layer creates a convolution kernel that is convolved with the layer input over a single spatial(or temporal) dimension to produce a tensor of outputs.If use_bias is True, a bias vector is created and added to the outputs.Finally, if activation is not None, it is applied to the outputs as well. + /// + /// Integer, the dimensionality of the output space (i.e. the number of output filters in the convolution) + /// An integer specifying the width of the 1D convolution window. + /// An integer specifying the stride of the convolution window . Specifying any stride value != 1 is incompatible with specifying any dilation_rate value != 1. + /// one of "valid" or "same" (case-insensitive). "valid" means no padding. "same" results in padding evenly to the left/right or up/down of the input such that output has the same height/width dimension as the input. + /// A string, one of channels_last (default) or channels_first. The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch_size, height, width, channels) while channels_first corresponds to inputs with shape (batch_size, channels, height, width). It defaults to the image_data_format value found in your Keras config file at ~/.keras/keras.json. If you never set it, then it will be channels_last. + /// An integer specifying the dilation rate to use for dilated convolution.Currently, specifying any dilation_rate value != 1 is incompatible with specifying any stride value != 1. + /// A positive integer specifying the number of groups in which the input is split along the channel axis. Each group is convolved separately with filters / groups filters. The output is the concatenation of all the groups results along the channel axis. Input channels and filters must both be divisible by groups. + /// Activation function to use. If you don't specify anything, no activation is applied (see keras.activations). + /// Boolean, whether the layer uses a bias vector. + /// Initializer for the kernel weights matrix (see keras.initializers). + /// Initializer for the bias vector (see keras.initializers). + /// Regularizer function applied to the kernel weights matrix (see keras.regularizers). + /// Regularizer function applied to the bias vector (see keras.regularizers). + /// Regularizer function applied to the output of the layer (its "activation") (see keras.regularizers). + /// A tensor of rank 3 representing activation(conv1d(inputs, kernel) + bias). + public Conv1D Conv1D(int filters, + int? kernel_size = null, + int? strides = null, + string padding = "valid", + string data_format = null, + int? dilation_rate = null, + int groups = 1, + Activation activation = null, + bool use_bias = true, + IInitializer kernel_initializer = null, + IInitializer bias_initializer = null, + IRegularizer kernel_regularizer = null, + IRegularizer bias_regularizer = null, + IRegularizer activity_regularizer = null) + { + // Special case: Conv1D will be implemented as Conv2D with H=1, so we need to add a 1-sized dimension to the kernel. + // Lower-level logic handles the stride and dilation_rate, but the kernel_size needs to be set properly here. + + var kernel = (kernel_size == null) ? (1, 5) : (1, kernel_size.Value); + return new Conv1D(new Conv1DArgs + { + Rank = 1, + Filters = filters, + KernelSize = kernel, + Strides = strides == null ? 1 : strides, + Padding = padding, + DataFormat = data_format, + DilationRate = dilation_rate == null ? 1 : dilation_rate, + Groups = groups, + UseBias = use_bias, + KernelInitializer = kernel_initializer == null ? tf.glorot_uniform_initializer : kernel_initializer, + BiasInitializer = bias_initializer == null ? tf.zeros_initializer : bias_initializer, + KernelRegularizer = kernel_regularizer, + BiasRegularizer = bias_regularizer, + ActivityRegularizer = activity_regularizer, + Activation = activation ?? keras.activations.Linear + }); + } + + /// + /// 1D convolution layer (e.g. temporal convolution). + /// This layer creates a convolution kernel that is convolved with the layer input over a single spatial(or temporal) dimension to produce a tensor of outputs.If use_bias is True, a bias vector is created and added to the outputs.Finally, if activation is not None, it is applied to the outputs as well. + /// + /// Integer, the dimensionality of the output space (i.e. the number of output filters in the convolution) + /// An integer specifying the width of the 1D convolution window. + /// An integer specifying the stride of the convolution window . Specifying any stride value != 1 is incompatible with specifying any dilation_rate value != 1. + /// one of "valid" or "same" (case-insensitive). "valid" means no padding. "same" results in padding evenly to the left/right or up/down of the input such that output has the same height/width dimension as the input. + /// A string, one of channels_last (default) or channels_first. The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch_size, height, width, channels) while channels_first corresponds to inputs with shape (batch_size, channels, height, width). It defaults to the image_data_format value found in your Keras config file at ~/.keras/keras.json. If you never set it, then it will be channels_last. + /// An integer specifying the dilation rate to use for dilated convolution.Currently, specifying any dilation_rate value != 1 is incompatible with specifying any stride value != 1. + /// A positive integer specifying the number of groups in which the input is split along the channel axis. Each group is convolved separately with filters / groups filters. The output is the concatenation of all the groups results along the channel axis. Input channels and filters must both be divisible by groups. + /// Activation function to use. If you don't specify anything, no activation is applied (see keras.activations). + /// Boolean, whether the layer uses a bias vector. + /// Initializer for the kernel weights matrix (see keras.initializers). + /// Initializer for the bias vector (see keras.initializers). + /// A tensor of rank 3 representing activation(conv1d(inputs, kernel) + bias). + public Conv1D Conv1D(int filters, + int? kernel_size = null, + int? strides = null, + string padding = "valid", + string data_format = null, + int? dilation_rate = null, + int groups = 1, + string activation = null, + bool use_bias = true, + string kernel_initializer = "glorot_uniform", + string bias_initializer = "zeros") + { + // Special case: Conv1D will be implemented as Conv2D with H=1, so we need to add a 1-sized dimension to the kernel. + // Lower-level logic handles the stride and dilation_rate, but the kernel_size needs to be set properly here. + + var kernel = (kernel_size == null) ? (1, 5) : (1, kernel_size.Value); + return new Conv1D(new Conv1DArgs + { + Rank = 1, + Filters = filters, + KernelSize = kernel, + Strides = strides == null ? 1 : strides, + Padding = padding, + DataFormat = data_format, + DilationRate = dilation_rate == null ? 1 : dilation_rate, + Groups = groups, + UseBias = use_bias, + Activation = GetActivationByName(activation), + KernelInitializer = GetInitializerByName(kernel_initializer), + BiasInitializer = GetInitializerByName(bias_initializer) + }); + } + /// /// 2D convolution layer (e.g. spatial convolution over images). /// This layer creates a convolution kernel that is convolved with the layer input to produce a tensor of outputs. @@ -105,7 +212,7 @@ namespace Tensorflow.Keras.Layers { Rank = 2, Filters = filters, - KernelSize = kernel_size, + KernelSize = (kernel_size == null) ? (5, 5) : kernel_size, Strides = strides == null ? (1, 1) : strides, Padding = padding, DataFormat = data_format, @@ -150,10 +257,7 @@ namespace Tensorflow.Keras.Layers string activation = null, bool use_bias = true, string kernel_initializer = "glorot_uniform", - string bias_initializer = "zeros", - string kernel_regularizer = null, - string bias_regularizer = null, - string activity_regularizer = null) + string bias_initializer = "zeros") => new Conv2D(new Conv2DArgs { Rank = 2, @@ -204,7 +308,7 @@ namespace Tensorflow.Keras.Layers { Rank = 2, Filters = filters, - KernelSize = kernel_size, + KernelSize = (kernel_size == null) ? (5, 5) : kernel_size, Strides = strides == null ? (1, 1) : strides, Padding = output_padding, DataFormat = data_format, diff --git a/test/TensorFlowNET.Keras.UnitTest/Layers/Layers.Convolution.Test.cs b/test/TensorFlowNET.Keras.UnitTest/Layers/Layers.Convolution.Test.cs index 5e71ece6..46d1fc63 100644 --- a/test/TensorFlowNET.Keras.UnitTest/Layers/Layers.Convolution.Test.cs +++ b/test/TensorFlowNET.Keras.UnitTest/Layers/Layers.Convolution.Test.cs @@ -1,6 +1,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NumSharp; using Tensorflow; +using Tensorflow.Operations; using static Tensorflow.KerasApi; namespace TensorFlowNET.Keras.UnitTest @@ -8,6 +9,99 @@ namespace TensorFlowNET.Keras.UnitTest [TestClass] public class LayersConvolutionTest : EagerModeTestBase { + [TestMethod] + public void BasicConv1D() + { + var filters = 8; + + var conv = keras.layers.Conv1D(filters, activation: "linear"); + + var x = np.arange(256.0f).reshape(8, 8, 4); + var y = conv.Apply(x); + + Assert.AreEqual(3, y.shape.ndim); + Assert.AreEqual(x.shape[0], y.shape[0]); + Assert.AreEqual(x.shape[1] - 4, y.shape[1]); + Assert.AreEqual(filters, y.shape[2]); + } + + [TestMethod] + public void BasicConv1D_ksize() + { + var filters = 8; + + var conv = keras.layers.Conv1D(filters, kernel_size: 3, activation: "linear"); + + var x = np.arange(256.0f).reshape(8, 8, 4); + var y = conv.Apply(x); + + Assert.AreEqual(3, y.shape.ndim); + Assert.AreEqual(x.shape[0], y.shape[0]); + Assert.AreEqual(x.shape[1] - 2, y.shape[1]); + Assert.AreEqual(filters, y.shape[2]); + } + + [TestMethod] + public void BasicConv1D_ksize_same() + { + var filters = 8; + + var conv = keras.layers.Conv1D(filters, kernel_size: 3, padding: "same", activation: "linear"); + + var x = np.arange(256.0f).reshape(8, 8, 4); + var y = conv.Apply(x); + + Assert.AreEqual(3, y.shape.ndim); + Assert.AreEqual(x.shape[0], y.shape[0]); + Assert.AreEqual(x.shape[1], y.shape[1]); + Assert.AreEqual(filters, y.shape[2]); + } + + [TestMethod] + public void BasicConv1D_ksize_strides() + { + var filters = 8; + var conv = keras.layers.Conv1D(filters, kernel_size: 3, strides: 2, activation: "linear"); + + var x = np.arange(256.0f).reshape(8, 8, 4); + var y = conv.Apply(x); + + Assert.AreEqual(3, y.shape.ndim); + Assert.AreEqual(x.shape[0], y.shape[0]); + Assert.AreEqual(x.shape[1] - 5, y.shape[1]); + Assert.AreEqual(filters, y.shape[2]); + } + + [TestMethod] + public void BasicConv1D_ksize_dilations() + { + var filters = 8; + var conv = keras.layers.Conv1D(filters, kernel_size: 3, dilation_rate: 2, activation: "linear"); + + var x = np.arange(256.0f).reshape(8, 8, 4); + var y = conv.Apply(x); + + Assert.AreEqual(3, y.shape.ndim); + Assert.AreEqual(x.shape[0], y.shape[0]); + Assert.AreEqual(x.shape[1] - 4, y.shape[1]); + Assert.AreEqual(filters, y.shape[2]); + } + + [TestMethod] + public void BasicConv1D_ksize_dilation_same() + { + var filters = 8; + var conv = keras.layers.Conv1D(filters, kernel_size: 3, dilation_rate: 2, padding: "same", activation: "linear"); + + var x = np.arange(256.0f).reshape(8, 8, 4); + var y = conv.Apply(x); + + Assert.AreEqual(3, y.shape.ndim); + Assert.AreEqual(x.shape[0], y.shape[0]); + Assert.AreEqual(x.shape[1], y.shape[1]); + Assert.AreEqual(filters, y.shape[2]); + } + [TestMethod] public void BasicConv2D() {