def _random_from_output_spec()

in source/python/neuropod/utils/randomify.py [0:0]


def _random_from_output_spec(output_spec, output_prefix="OUTPUT_API"):
    """Adds random matrix generators based on the output spec. Symbolic dimensions in shape definition are respected."""
    node_name_mapping = dict()

    # Arbitrary choice of the number of elements in a variable size dimension: 1 to 100
    def toss_random_dim():
        return np.random.randint(1, 100)

    symbol_value = defaultdict(toss_random_dim)

    with tf.name_scope(output_prefix):

        for tensor_spec in output_spec:
            name = tensor_spec["name"]

            symbolic_shape = tensor_spec["shape"]

            # Randomize variable sized dimensions.
            resolved_shape = tuple()
            for d in symbolic_shape:
                if isinstance(d, string_types):
                    resolved_shape += (symbol_value[d],)
                elif d is None:
                    resolved_shape += (toss_random_dim(),)
                else:
                    resolved_shape += (d,)

            numpy_dtype = tensor_spec["dtype"]
            tf_dtype = tf.as_dtype(get_dtype(numpy_dtype))

            if numpy_dtype != "string":
                # Integers need `maxval=` to be specified explicitly. Also, random_uniform does not support all
                # integer types.
                if tf_dtype.is_integer:
                    output_tensor = tf.cast(
                        tf.random_uniform(
                            shape=resolved_shape,
                            maxval=tf_dtype.max,
                            dtype=tf.int64,
                            name=name,
                        )
                        % tf_dtype.max,
                        tf_dtype,
                    )
                else:
                    output_tensor = tf.random_uniform(
                        shape=resolved_shape, dtype=tf_dtype, name=name
                    )
            else:
                # We just convert random floats to strings
                output_tensor = tf.as_string(
                    tf.random_uniform(shape=resolved_shape, dtype=tf.float32, name=name)
                )

            node_name_mapping[name] = output_tensor.name

    return node_name_mapping