Compute the shape of a conv given input shapes in canonical order.
770649
def _conv_shape_tuple(self, lhs_shape, rhs_shape, strides, pads):
    """"""
    if isinstance(pads, str):
      pads = padtype_to_pads(lhs_shape[2:], rhs_shape[2:], strides, pads)
    if len(pads) != len(lhs_shape) - 2:
      msg = 'Wrong number of explicit pads for conv: expected {}, got {}.'
      raise TypeError(msg.format(len(lhs_shape) - 2, len(pads)))
    lhs_padded = onp.add(lhs_shape[2:], onp.add(*zip(*pads)))
    out_space = onp.floor_divide(
        onp.subtract(lhs_padded, rhs_shape[2:]), strides) + 1
    out_space = onp.maximum(0, out_space)
    out_shape = (lhs_shape[0], rhs_shape[0]) + tuple(out_space)
    return tuple(out_shape)
770272
def shape(self):
        ""
        keys = self.keys()
        if self.ndims == 1:
            return (len(keys), 1)
        return len(set(k[0] for k in keys)), len(set(k[1] for k in keys))
992985
public static INDArray convn(INDArray input, INDArray kernel, Type type, int[] axes) {
        return Nd4j.getConvolution().convn(input, kernel, type, axes);
    }
1188982
def discriminator(self, inputs, outputs):
        
        l = tf.concat([inputs, outputs], 3)
        with argscope(Conv2D, kernel_size=4, strides=2, activation=BNLReLU):
            l = (LinearWrap(l)
                 .Conv2D('conv0', NF, activation=tf.nn.leaky_relu)
                 .Conv2D('conv1', NF * 2)
                 .Conv2D('conv2', NF * 4)
                 .Conv2D('conv3', NF * 8, strides=1, padding='VALID')
                 .Conv2D('convlast', 1, strides=1, padding='VALID', activation=tf.identity)())
        return l
987847
def calculate_convolution_output_shapes(operator):
    '''
    
    '''
    check_input_and_output_numbers(operator, input_count_range=1, output_count_range=1)

    params = operator.raw_operator.convolution

    input_shape = operator.inputs[0].type.shape
    operator.outputs[0].type.shape = [0, 0, 0, 0]  # Initialize output shape. It will be modified below.
    output_shape = operator.outputs[0].type.shape

    # Adjust N-axis
    output_shape[0] = input_shape[0]

    # Adjust C-axis
    output_shape[1] = params.outputChannels

    # Set up default and non-default parameters
    dilations = [1, 1]
    if len(params.dilationFactor) > 0:
        dilations = [params.dilationFactor[0], params.dilationFactor[1]]
    kernel_shape = [3, 3]
    if len(params.kernelSize) > 0:
        kernel_shape = params.kernelSize
    strides = [1, 1]
    if len(params.stride) > 0:
        strides = params.stride
    specified_output_shape = [0, 0]  # Only used with convolution transpose
    if params.isDeconvolution and len(params.outputShape) > 0:
        specified_output_shape = list(int(i) for i in params.outputShape)
    pad_mode = params.WhichOneof('ConvolutionPaddingType')
    if pad_mode == 'valid' and len(params.valid.paddingAmounts.borderAmounts) > 0:
        pad_amounts = params.valid.paddingAmounts.borderAmounts
        pad_heads = [pad_amounts[0].startEdgeSize, pad_amounts[1].startEdgeSize]
        pad_tails = [pad_amounts[0].endEdgeSize, pad_amounts[1].endEdgeSize]
    else:
        # Padding amounts are useless for same padding and valid padding uses [0, 0] by default.
        pad_heads = [0, 0]
        pad_tails = [0, 0]

    # Adjust H- and W-axes
    for i in range(2):
        if params.isDeconvolution:
            output_shape[i + 2] = calculate_convolution_transpose_1D_output_shape(
                input_shape[i + 2], kernel_shape[i], dilations[i], strides[i],
                pad_mode, pad_heads[i], pad_tails[i], specified_output_shape[i])
        else:
            output_shape[i + 2] = calculate_convolution_and_pooling_1D_output_shape(
                input_shape[i + 2], kernel_shape[i], dilations[i], strides[i],
                pad_mode, pad_heads[i], pad_tails[i])
196678
def _kernel_shape(self, input_shape):
    """"""
    kernel_size_iter = iter(self._kernel_size)
    return [self._filters if c == 'O' else
            input_shape[self._lhs_spec.index('C')] if c == 'I' else
            next(kernel_size_iter) for c in self._rhs_spec]
210279
def conv2d(x_input, w_matrix):
    """"""
    return tf.nn.conv2d(x_input, w_matrix, strides=[1, 1, 1, 1], padding='SAME')
912511
def reshape(self, shape: tf.TensorShape) -> 'TensorFluent':
        '''
        '''
        t = tf.reshape(self.tensor, shape)
        scope = self.scope.as_list()
        batch = self.batch
        return TensorFluent(t, scope, batch=batch)
1094509
def _pooling_output_shape(input_shape, pool_size=(2, 2),
                          strides=None, padding='VALID'):
  """"""
  dims = (1,) + pool_size + (1,)  # NHWC
  spatial_strides = strides or (1,) * len(pool_size)
  strides = (1,) + spatial_strides + (1,)
  pads = padtype_to_pads(input_shape, dims, strides, padding)
  operand_padded = onp.add(input_shape, onp.add(*zip(*pads)))
  t = onp.floor_divide(onp.subtract(operand_padded, dims), strides) + 1
  return tuple(t)
892347
def calculate_gru_output_shapes(operator):
    '''
    
    '''
    check_input_and_output_numbers(operator, input_count_range=[1, 2], output_count_range=[1, 2])
    check_input_and_output_types(operator, good_input_types=[FloatTensorType])

    input_shape = operator.inputs[0].type.shape

    if len(input_shape) not in [2, 4]:
        raise RuntimeError('Input must be a [N, C]- or [N, C, 1, 1]-tensor')

    if operator.type == 'gru':
        params = operator.raw_operator.gru
    elif operator.type == 'simpleRecurrent':
        params = operator.raw_operator.simpleRecurrent
    else:
        raise RuntimeError('Only GRU and SimpleRNN are supported')

    # The following line is more accurate but it may break some tests
    # output_shape = ['None', params.outputVectorSize] if params.params.sequenceOutput else [2, params.outputVectorSize]
    output_shape = [input_shape[0] if params.sequenceOutput else 'None', params.outputVectorSize]  # 'None' should be 1
    state_shape = [1, params.outputVectorSize]

    # TODO: Changing input shapes of an operator is dangerous, this should be move to Topology's _fix_shapes function
    if len(operator.inputs) > 1:
        Y_h_in = operator.inputs[1]  # The initial hidden state of a single sequence
        Y_h_in.type.shape = state_shape

    operator.outputs[0].type.shape = output_shape
    if len(operator.outputs) > 1:
        operator.outputs[1].type.shape = state_shape
657036
def gather_indices_2d(x, block_shape, block_stride):
  """"""
  # making an identity matrix kernel
  kernel = tf.eye(block_shape[0] * block_shape[1])
  kernel = reshape_range(kernel, 0, 1, [block_shape[0], block_shape[1], 1])
  # making indices [1, h, w, 1] to appy convs
  x_shape = common_layers.shape_list(x)
  indices = tf.range(x_shape[2] * x_shape[3])
  indices = tf.reshape(indices, [1, x_shape[2], x_shape[3], 1])
  indices = tf.nn.conv2d(
      tf.cast(indices, tf.float32),
      kernel,
      strides=[1, block_stride[0], block_stride[1], 1],
      padding="VALID")
  # making indices [num_blocks, dim] to gather
  dims = common_layers.shape_list(indices)[:3]
  if all([isinstance(dim, int) for dim in dims]):
    num_blocks = functools.reduce(operator.mul, dims, 1)
  else:
    num_blocks = tf.reduce_prod(dims)
  indices = tf.reshape(indices, [num_blocks, -1])
  return tf.cast(indices, tf.int32)
216042
def subseparable_conv_block(inputs, filters, dilation_rates_and_kernel_sizes,
                            **kwargs):
  """"""
  return conv_block_internal(subseparable_conv, inputs, filters,
                             dilation_rates_and_kernel_sizes, **kwargs)
1254879
def ConvDiagonalGRU(units, kernel_size=(3, 3)):
  """"""

  def BuildConv():
    return layers.Conv(filters=units, kernel_size=kernel_size, padding='SAME')

  return layers.GeneralGRUCell(
      candidate_transform=BuildConv,
      memory_transform=DiagonalGate,
      gate_nonlinearity=layers.HardSigmoid,
      candidate_nonlinearity=layers.HardTanh)
114739
def conv3x3(in_planes, out_planes, stride=1):
    ""
    return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
                     padding=1, bias=True)
504105
def _scale_shape(dshape, scale = (1,1,1)):
    """"""
    nshape = np.round(np.array(dshape) * np.array(scale))
    return tuple(nshape.astype(np.int))
185868
def get_output_shapes(self):
        """"""
        outputs = self.execs[0].outputs
        shapes = [out.shape for out in outputs]

        concat_shapes = []
        for key, the_shape, axis in zip(self.symbol.list_outputs(), shapes, self.output_layouts):
            the_shape = list(the_shape)
            if axis >= 0:
                the_shape[axis] = self.batch_size
            concat_shapes.append((key, tuple(the_shape)))
        return concat_shapes
1076689
function conv2(image, kernel) {
    var out = new Float64Array( height * width  )
    var acc = 0
    , row, col, i, j, k
    for ( row = 0; row < height; row++ ) {
      for ( col = 0; col < width; col++ ) {
        for ( i = -1; i <= 1; i++ ) {
          for ( j = -1; j <= 1; j++ ) {
            if( row+i >= 0 && col+j >= 0 &&
                row+i < height && col+j < width) {
              k = image[ (row + i) * width + (col + j)]
              acc += k * kernel[ (1 + i) * 3 + (1 + j)]
            }
          }
        }
        out[ row * width + col] = acc
        acc = 0
      }
    }
    return out
  }