How to use the coremltools.proto.NeuralNetwork_pb2 function in coremltools

To help you get started, we’ve selected a few coremltools examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github apple / coremltools / coremltools / models / neural_network.py View on Github external
--------
        add_sequence_repeat, add_elementwise
        """
        spec = self.spec
        nn_spec = self.nn_spec

        # Add a new inner-product layer
        spec_layer = nn_spec.layers.add()
        spec_layer.name = name
        spec_layer.input.append(input_name)
        spec_layer.output.append(output_name)
        spec_layer_params = spec_layer.upsample
        spec_layer_params.scalingFactor.append(scaling_factor_h)
        spec_layer_params.scalingFactor.append(scaling_factor_w)
        if mode == 'NN':
            spec_layer_params.mode = _NeuralNetwork_pb2.UpsampleLayerParams.InterpolationMode.Value('NN')
        elif mode == 'BILINEAR':
            spec_layer_params.mode = _NeuralNetwork_pb2.UpsampleLayerParams.InterpolationMode.Value('BILINEAR')
        else:
            raise ValueError("Unsupported upsampling mode %s" % mode)   
github apple / turicreate / src / unity / python / turicreate / toolkits / _mxnet / _mxnet_to_coreml / _add_pooling.py View on Github external
add_convolution, add_pooling, add_activation
    """

    spec = builder.spec
    nn_spec = builder.nn_spec

    # Add a new layer
    spec_layer = nn_spec.layers.add()
    spec_layer.name = name
    spec_layer.input.append(input_name)
    spec_layer.output.append(output_name)
    spec_layer_params = spec_layer.pooling

    # Set the parameters
    spec_layer_params.type = \
                _NeuralNetwork_pb2.PoolingLayerParams.PoolingType.Value(layer_type)

    if padding_type == 'VALID':
        height_border = spec_layer_params.valid.paddingAmounts.borderAmounts.add()
        height_border.startEdgeSize = padding_top
        height_border.endEdgeSize = padding_bottom
        width_border = spec_layer_params.valid.paddingAmounts.borderAmounts.add()
        width_border.startEdgeSize = padding_left
        width_border.endEdgeSize = padding_right
    elif padding_type == 'SAME':
        if not (same_padding_asymmetry_mode == 'BOTTOM_RIGHT_HEAVY' or  same_padding_asymmetry_mode == 'TOP_LEFT_HEAVY'):
            raise ValueError("Invalid value %d of same_padding_asymmetry_mode parameter" % same_padding_asymmetry_mode)
        spec_layer_params.same.asymmetryMode = _NeuralNetwork_pb2.SamePadding.SamePaddingMode.Value(same_padding_asymmetry_mode)
    elif padding_type == 'INCLUDE_LAST_PIXEL':
        if padding_top != padding_bottom or padding_left != padding_right:
            raise ValueError("Only symmetric padding is supported with the INCLUDE_LAST_PIXEL padding type")
        spec_layer_params.includeLastPixel.paddingAmounts.append(padding_top)
github tf-coreml / tf-coreml / tfcoreml / optimizations / _optimize.py View on Github external
def _evaluate_unary(layer, x):
  params = layer.unary
  x = x * params.scale + params.shift
  op_type = _NeuralNetwork_pb2.UnaryFunctionLayerParams.Operation.Name(
      params.type)
  if op_type == 'SQRT':
    return np.sqrt(x)
  elif op_type == 'RSQRT':
    return 1/np.sqrt(x + params.epsilon)
  elif op_type == 'INVERSE':
    return 1/(x + params.epsilon)
  elif op_type == 'POWER':
    return x ** params.alpha
  elif op_type == 'EXP':
    return np.exp(x)
  elif op_type == 'LOG':
    return np.log(x)
  elif op_type == 'ABS':
    return np.abs(x)
  elif op_type == 'THRESHOLD':
github tf-coreml / tf-coreml / utils / _infer_shapes_nn_mlmodel.py View on Github external
def _slice(layer, shape_dict):
    params = layer.slice
    Seq, Batch, C, H, W = shape_dict[layer.input[0]]
    start = params.startIndex
    end = params.endIndex
    stride = params.stride
    axis = _NeuralNetwork_pb2.SliceLayerParams.SliceAxis.Name(params.axis)
    if axis == 'CHANNEL_AXIS': N = C
    if axis == 'HEIGHT_AXIS': N = H
    if axis == 'WIDTH_AXIS': N = W
    if end < 0: end = end + N
    end = min(end, N)
    if start > N-1:
        L = 0
    else:
        L = np.floor((end - 1 - start)/stride) + 1
        if L<0 : L = 0
    if axis == 'CHANNEL_AXIS': C = L
    if axis == 'HEIGHT_AXIS': H = L
    if axis == 'WIDTH_AXIS': W = L
    shape_dict[layer.output[0]] = (Seq, Batch, int(C), int(H), int(W))
github apple / coremltools / coremltools / converters / nnssa / coreml / ssa_converter.py View on Github external
def _convert_custom_layer(self, node):
        """ Add custom layer
        """
        params = NeuralNetwork_pb2.CustomLayerParams()
        params.className = node.op
        params.description = "Custom layer that corresponds to the TensorFlow op {}".format(node.op)
        builder = self._get_builder()
        layer = builder.add_custom(name=node.name,
                                   input_names=node.inputs,
                                   output_names=[node.name],
                                   custom_proto_spec=params)

        if node.op not in self.custom_shape_functions:
            raise ValueError('Custom Shape Function for {} not provided!'.format(node.op))
        shapes.propagate_single_layer(layer, self.tensor_shapes, custom_shape_function=self.custom_shape_functions[node.op])
github tf-coreml / tf-coreml / tfcoreml / _layers_common.py View on Github external
else:
      func = context.custom_conversion_functions[op.name]

    # Fill up values of any constant inputs that this op receives
    constant_inputs = {}
    for inp_ in op.inputs:
      if inp_.name in context.consts:
        constant_inputs[inp_.name] = context.consts[inp_.name]
      elif inp_.op.type == 'Identity' and inp_.op.inputs[0].name in context.consts:
        constant_inputs[inp_.op.inputs[0].name] = context.consts[inp_.op.inputs[0].name]

    kwargs = {"op": op, "nn_builder": context.builder, "context": context, "constant_inputs": constant_inputs}
    func(**kwargs)

  else:
    params = NeuralNetwork_pb2.CustomLayerParams()
    params.className = op.type
    params.description = "Custom layer that corresponds to the TensorFlow op {}".format(op.type, )
    inputs = [inp.name for inp in op.inputs]
    outputs = [out.name for out in op.outputs]
    context.builder.add_custom(name=op.name,
                            input_names=inputs,
                            output_names=outputs,
                            custom_proto_spec=params)
  for out in op.outputs:
    context.translated[out.name] = True
  context.ops_converted_to_custom_layers.append(op)
github apple / turicreate / src / external / coremltools_wrap / coremltools / coremltools / models / _infer_shapes_nn_mlmodel.py View on Github external
def _reduce(layer, shape_dict):
    params = layer.reduce
    Seq, Batch, C, H, W = shape_dict[layer.input[0]]     
    
    axis = _NeuralNetwork_pb2.ReduceLayerParams.ReduceAxis.Name(params.axis)
    if axis == 'CHW':
        C = H = W = 1
    elif axis == 'HW':
        H = W = 1
    elif axis == 'C':
        C = 1
    elif axis == 'H':
        H = 1
    elif axis == 'W':
        W = 1                
    
    shape_dict[layer.output[0]] = (Seq, Batch, int(C), int(H), int(W))
github tf-coreml / tf-coreml / tfcoreml / optimizations / _optimize.py View on Github external
def _evaluate_slice(layer, x, shape):
  params = layer.slice
  start_index = params.startIndex
  end_index = params.endIndex
  strides = params.stride
  axis = _NeuralNetwork_pb2.SliceLayerParams.SliceAxis.Name(params.axis)
  x = np.reshape(x, shape)
  if axis == 'CHANNEL_AXIS':
    x = x[start_index:end_index:strides,:,:]
  elif axis == 'HEIGHT_AXIS':
    x = x[:,start_index:end_index:strides,:]
  elif axis == 'WIDTH_AXIS':
    x = x[:,:,start_index:end_index:strides]
  else:
    raise ValueError('Axis in slice layer not recognized: %s' % (axis))
  new_shape = list(x.shape)
  return x.flatten(), new_shape
github apple / coremltools / coremltools / models / neural_network / builder.py View on Github external
nn_spec = self.nn_spec

        # Add a new layer
        spec_layer = nn_spec.layers.add()
        spec_layer.name = name
        spec_layer.input.append(input_name)
        spec_layer.output.append(output_name)

        spec_layer_params = spec_layer.reshape
        spec_layer_params.targetShape.extend(target_shape)
        if mode == 0:
            spec_layer_params.mode = \
                    _NeuralNetwork_pb2.ReshapeLayerParams.ReshapeOrder.Value('CHANNEL_FIRST')
        else:
            spec_layer_params.mode = \
                    _NeuralNetwork_pb2.ReshapeLayerParams.ReshapeOrder.Value('CHANNEL_LAST')
                    
        if len(target_shape) != 4 and len(target_shape) != 3:
            raise ValueError("Length of the 'target-shape' parameter must be equal to 3 or 4")
github apple / coremltools / coremltools / models / neural_network / builder.py View on Github external
--------
        add_sequence_repeat, add_elementwise
        """
        spec = self.spec
        nn_spec = self.nn_spec

        # Add a new inner-product layer
        spec_layer = nn_spec.layers.add()
        spec_layer.name = name
        spec_layer.input.append(input_name)
        spec_layer.output.append(output_name)
        spec_layer_params = spec_layer.upsample
        spec_layer_params.scalingFactor.append(scaling_factor_h)
        spec_layer_params.scalingFactor.append(scaling_factor_w)
        if mode == 'NN':
            spec_layer_params.mode = _NeuralNetwork_pb2.UpsampleLayerParams.InterpolationMode.Value('NN')
        elif mode == 'BILINEAR':
            spec_layer_params.mode = _NeuralNetwork_pb2.UpsampleLayerParams.InterpolationMode.Value('BILINEAR')
        else:
            raise ValueError("Unsupported upsampling mode %s" % mode)