Python numpy.type() Examples

The following are 12 code examples of numpy.type(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module numpy , or try the search function .
Example #1
Source File: types.py    From ngraph-onnx with Apache License 2.0 6 votes vote down vote up
def get_bool_nodes(nodes):   # type: (Tuple[NgraphNode, ...]) -> Tuple[NgraphNode, ...]
    """Convert each input node to bool data type if necessary.

    :param nodes: Input nodes to be converted.
    :return: Converted nodes.
    """
    bool_nodes = []
    for node in nodes:
        if not node.get_element_type() == NgraphType.boolean:
            bool_nodes.append(ng.convert(node, bool))
            logger.warning('Converting node of type: <{}> to bool.'.format(get_dtype(
                node.get_element_type())))
        else:
            bool_nodes.append(node)

    return tuple(bool_nodes) 
Example #2
Source File: quantization.py    From mmcv with Apache License 2.0 6 votes vote down vote up
def quantize(arr, min_val, max_val, levels, dtype=np.int64):
    """Quantize an array of (-inf, inf) to [0, levels-1].

    Args:
        arr (ndarray): Input array.
        min_val (scalar): Minimum value to be clipped.
        max_val (scalar): Maximum value to be clipped.
        levels (int): Quantization levels.
        dtype (np.type): The type of the quantized array.

    Returns:
        tuple: Quantized array.
    """
    if not (isinstance(levels, int) and levels > 1):
        raise ValueError(
            f'levels must be a positive integer, but got {levels}')
    if min_val >= max_val:
        raise ValueError(
            f'min_val ({min_val}) must be smaller than max_val ({max_val})')

    arr = np.clip(arr, min_val, max_val) - min_val
    quantized_arr = np.minimum(
        np.floor(levels * arr / (max_val - min_val)).astype(dtype), levels - 1)

    return quantized_arr 
Example #3
Source File: quantization.py    From mmcv with Apache License 2.0 6 votes vote down vote up
def dequantize(arr, min_val, max_val, levels, dtype=np.float64):
    """Dequantize an array.

    Args:
        arr (ndarray): Input array.
        min_val (scalar): Minimum value to be clipped.
        max_val (scalar): Maximum value to be clipped.
        levels (int): Quantization levels.
        dtype (np.type): The type of the dequantized array.

    Returns:
        tuple: Dequantized array.
    """
    if not (isinstance(levels, int) and levels > 1):
        raise ValueError(
            f'levels must be a positive integer, but got {levels}')
    if min_val >= max_val:
        raise ValueError(
            f'min_val ({min_val}) must be smaller than max_val ({max_val})')

    dequantized_arr = (arr + 0.5).astype(dtype) * (max_val -
                                                   min_val) / levels + min_val

    return dequantized_arr 
Example #4
Source File: sparse.py    From tenpy with GNU General Public License v3.0 5 votes vote down vote up
def charge_sector(self, value):
        if type(value) == int and value == 0:
            value = self.leg.chinfo.make_valid()  # zero charges
        elif value is not None:
            value = self.leg.chinfo.make_valid(value)
        self._charge_sector = value
        if value is not None:
            self._mask = np.all(self.leg.to_qflat() == value[np.newaxis, :], axis=1)
            self.shape = tuple([np.sum(self._mask)] * 2)
        else:
            chi2 = self.leg.ind_len
            self.shape = (chi2, chi2)
            self._mask = np.ones([chi2], dtype=np.bool) 
Example #5
Source File: types.py    From ngraph-onnx with Apache License 2.0 5 votes vote down vote up
def onnx_tensor_type_to_numpy_type(data_type):  # type: (Any) -> np.dtype
    """Return ONNX TensorProto type mapped into numpy dtype.

    :param data_type: The type we want to convert from.
    :return: Converted numpy dtype.
    """
    if type(data_type) is int:
        return TENSOR_TYPE_TO_NP_TYPE[data_type]
    elif type(data_type) is str:
        return TENSOR_TYPE_TO_NP_TYPE[TensorProto.DataType.Value(data_type)]
    else:
        raise ValueError('Unsupported data type representation (%s).', str(type(data_type))) 
Example #6
Source File: types.py    From ngraph-onnx with Apache License 2.0 5 votes vote down vote up
def np_dtype_to_tensor_type_name(data_type):  # type: (np.dtype) -> str
    """Return TensorProto type name respective to provided numpy dtype.

    :param data_type: Numpy dtype we want to convert.
    :return: String representation of TensorProto type name.
    """
    return TensorProto.DataType.Name(NP_TYPE_TO_TENSOR_TYPE[data_type]) 
Example #7
Source File: types.py    From ngraph-onnx with Apache License 2.0 5 votes vote down vote up
def np_dtype_to_tensor_type(data_type):  # type: (np.type) -> int
    """Return TensorProto type for provided numpy dtype.

    :param data_type: Numpy data type object.
    :return: TensorProto.DataType enum value for corresponding type.
    """
    return NP_TYPE_TO_TENSOR_TYPE[data_type] 
Example #8
Source File: box_space.py    From rlgraph with Apache License 2.0 5 votes vote down vote up
def __repr__(self):
        return "{}({} {} {}{})".format(
            type(self).__name__.title(), self.shape, str(self.dtype), "; +batch" if self.has_batch_rank else
            "", "; +time" if self.has_time_rank else ""
        ) 
Example #9
Source File: image.py    From perceptron-benchmark with Apache License 2.0 5 votes vote down vote up
def load_mnist_image(shape=(28, 28), dtype=np.float32,
            bounds=(0, 1), data_format='channels_last',
            fname='mnist0.png', normalize=False):
    """Return the sample mnist image for testing

    Parameters
    ----------
    shape : list of integers
        The shape of the returned image.
    dype : np.type
        The type for loading the image
    bounds : float tuple
        the range of loaded image before normalization
    data_format : str
        "channels_first" or "channels_last"
    fname : str
        The name of sample image
    normalize : Bool
        Whether the image is needed to be normalized.
    """
    from PIL import Image

    path = os.path.join(os.path.dirname(__file__), 'images/%s' % fname)
    image = Image.open(path)
    image = np.asarray(image, dtype=dtype)
    if(data_format == 'channels_first'):
        image = image.reshape([1]+list(shape))
    else:
        image = image.reshape(list(shape)+[1])

    if bounds != (0, 255):
        image /= 255.

    return image 
Example #10
Source File: sparse.py    From tenpy with GNU General Public License v3.0 4 votes vote down vote up
def from_guess_with_pipe(cls, npc_matvec, v0_guess, labels_split=None, dtype=None):
        """Create a `FlatLinearOperator`` from a `matvec` function acting on multiple legs.

        This function creates a wrapper `matvec` function to allow acting on a "vector" with
        multiple legs. The wrapper combines the legs into a :class:`~tenpy.linalg.charges.LegPipe`
        before calling the actual `matvec` function, and splits them again in the end.

        Parameters
        ----------
        npc_matvec : function
            Function to calculate the action of the linear operator on an npc vector
            with the given split labels `labels_split`.
            Has to return an npc vector with the same legs.
        v0_guess : :class:`~tenpy.linalg.np_conserved.Array`
            Initial guess/starting vector which can be applied to `npc_matvec`.
        labels_split : None | list of str
            Labels of v0_guess in the order in which they are to be combined into a
            :class:`~tenpy.linalg.charges.LegPipe`. ``None`` defaults to
            ``v0_guess.get_leg_labels()``.
        dtype : np.dtype | None
            The data type of the arrays. ``None`` defaults to dtype of `v0_guess` (!).

        Returns
        -------
        lin_op : cls
            Instance of the class to be used as linear operator
        guess_flat : np.ndarray
            Numpy vector representing the guess `v0_guess`.
        """
        if dtype is None:
            dtype = v0_guess.dtype
        if labels_split is None:
            labels_split = v0_guess.get_leg_labels()
        v0_combined = v0_guess.combine_legs(labels_split, qconj=+1)
        if v0_combined.rank != 1:
            raise ValueError("`labels_split` must contain all the legs of `v0_guess`")
        pipe = v0_combined.legs[0]
        pipe_label = v0_combined.get_leg_labels()[0]
        res = cls(npc_matvec, pipe, dtype, v0_combined.qtotal, pipe_label)
        res._labels_split = labels_split
        res._npc_matvec_multileg = npc_matvec
        res.npc_matvec = res._npc_matvec_wrapper  # activate the wrapper
        guess_flat = res.npc_to_flat(v0_combined)
        return res, guess_flat 
Example #11
Source File: box_space.py    From rlgraph with Apache License 2.0 4 votes vote down vote up
def __init__(self, low, high, shape=None, add_batch_rank=False, add_time_rank=False, time_major=False,
                 dtype=np.float32):
        """
        Args:
            low (any): The lower bound (see Valid Inputs for more information).
            high (any): The upper bound (see Valid Inputs for more information).
            shape (tuple): The shape of this space.
            dtype (np.type): The data type (as numpy type) for this Space.
                Allowed are: np.int8,16,32,64, np.float16,32,64 and np.bool_.

        Valid inputs:
            BoxSpace(0.0, 1.0) # low and high are given as scalars and shape is assumed to be ()
                -> single scalar between low and high.
            BoxSpace(-1.0, 1.0, (3,4)) # low and high are scalars, and shape is provided -> nD array
                where all(!) elements are between low and high.
            BoxSpace(np.array([-1.0,-2.0]), np.array([2.0,4.0])) # low and high are arrays of the same shape
                (no shape given!) -> nD array where each dimension has different bounds.
        """
        super(BoxSpace, self).__init__(add_batch_rank=add_batch_rank, add_time_rank=add_time_rank,
                                       time_major=time_major)

        self.dtype = dtype

        # Determine the shape.
        if shape is None:
            if isinstance(low, (int, float, bool)):
                self._shape = ()
            else:
                self._shape = np.shape(low)
        else:
            assert isinstance(shape, (tuple, list)), "ERROR: `shape` must be None or a tuple/list."
            self._shape = tuple(shape)

        # Determine the bounds.
        # False if bounds are individualized (each dimension has its own lower and upper bounds and we can get
        # the single values from self.low and self.high), or a tuple of the globally valid low/high values that apply
        # to all values in all dimensions.
        # 0D Space.
        if self._shape == ():
            if isinstance(low, np.ndarray):
                assert low.shape == (), "ERROR: If shape == (), `low` must be scalar!"
                low = np.asscalar(low)
            if isinstance(high, np.ndarray):
                assert high.shape == (), "ERROR: If shape == (), `high` must be scalar!"
                high = np.asscalar(high)
            self.global_bounds = (low, high)
        # nD Space (n > 0). Bounds can be single number or individual bounds.
        else:
            # Low/high values are given individually per item.
            if isinstance(low, (list, tuple, np.ndarray)):
                self.global_bounds = False
            # Only one low/high value. Use these as generic bounds for all values.
            else:
                assert np.isscalar(low) and np.isscalar(high)
                self.global_bounds = (low, high)

        self.low = np.array(low)
        self.high = np.array(high)
        assert self.low.shape == self.high.shape 
Example #12
Source File: image.py    From perceptron-benchmark with Apache License 2.0 4 votes vote down vote up
def load_cifar_image(shape=(32, 32), dtype=np.float32,
            bounds=(0, 1), data_format='channels_last',
            fname='cifar0.png', normalize=True):
    """Return the sample mnist image for testing

    Parameters
    ----------
    shape : list of integers
        The shape of the returned image.
    dype : np.type
        The type for loading the image
    bounds : float tuple
        the range of loaded image before normalization
    data_format : str
        "channels_first" or "channels_last"
    fname : str
        The name of sample image
    normalize : Bool
        Whether the image is needed to be normalized.
    """
    from PIL import Image

    path = os.path.join(os.path.dirname(__file__), 'images/%s' % fname)
    image = Image.open(path)
    image = np.asarray(image, dtype=dtype)
    if(data_format == 'channels_first'):
        image = image.reshape([3]+list(shape))
    else:
        image = image.reshape(list(shape)+[3])

    if bounds != (0, 255):
        image /= 255.

    if(normalize):
        mean = np.array([0.485, 0.456, 0.406]).reshape(3,1,1)
        std = np.array([0.225, 0.225, 0.225]).reshape(3,1,1)
        image = image - mean
        image = image / std

    image = np.asarray(image, dtype=dtype)

    return image