Python numbers.Number() Examples

The following are 30 code examples for showing how to use numbers.Number(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module numbers , or try the search function .

Example 1
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: utils.py    License: Apache License 2.0 6 votes vote down vote up
def get_numeric_list(values, typ, expected_len=None):
    if isinstance(values, numbers.Number):
        if expected_len is not None:
            return [typ(values)] * expected_len
        else:
            return [typ(values)]
    elif isinstance(values, (list, tuple)):
        if expected_len is not None:
            assert len(values) == expected_len
        try:
            ret = [typ(value) for value in values]
            return ret
        except(ValueError):
            print("Need iterable with numeric elements, received: %s" %str(values))
            sys.exit(1)
    else:
        raise ValueError("Unaccepted value type, values=%s" %str(values)) 
Example 2
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: symbol.py    License: Apache License 2.0 6 votes vote down vote up
def __rdiv__(self, other):
        """x.__rdiv__(y) <=> y/x

        Only `NDArray` is supported for now.

        Example
        -------
        >>> x = mx.nd.ones((2,3))*3
        >>> y = mx.nd.ones((2,3))
        >>> x.__rdiv__(y).asnumpy()
        array([[ 0.33333334,  0.33333334,  0.33333334],
               [ 0.33333334,  0.33333334,  0.33333334]], dtype=float32)
        """
        if isinstance(other, Number):
            return _internal._RDivScalar(self, scalar=other)
        else:
            raise TypeError('type %s not supported' % str(type(other))) 
Example 3
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: symbol.py    License: Apache License 2.0 6 votes vote down vote up
def __rmod__(self, other):
        """x.__rmod__(y) <=> y%x

        Only `NDArray` is supported for now.

        Example
        -------
        >>> x = mx.nd.ones((2,3))*3
        >>> y = mx.nd.ones((2,3))
        >>> x.__rmod__(y).asnumpy()
        array([[ 1.,  1.,  1.,
               [ 1.,  1.,  1., dtype=float32)
        """
        if isinstance(other, Number):
            return _internal._RModScalar(self, scalar=other)
        else:
            raise TypeError('type %s not supported' % str(type(other))) 
Example 4
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: symbol.py    License: Apache License 2.0 6 votes vote down vote up
def __len__(self):
        """Get number of outputs for the symbol.

        Example
        -------
        >>> a = mx.sym.var('a')
        >>> b = mx.sym.var('b')
        >>> c = a + b
        >>> len(c)

        Returns
        -------
        len(self): Number of outputs
            Number of outputs
        """
        output_count = mx_uint()
        check_call(_LIB.MXSymbolGetNumOutputs(self.handle, ctypes.byref(output_count)))
        return output_count.value 
Example 5
Project: torch-toolbox   Author: PistonY   File: transforms.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(
            self,
            degrees,
            resample='BILINEAR',
            expand=False,
            center=None):
        if isinstance(degrees, numbers.Number):
            if degrees < 0:
                raise ValueError(
                    "If degrees is a single number, it must be positive.")
            self.degrees = (-degrees, degrees)
        else:
            if len(degrees) != 2:
                raise ValueError(
                    "If degrees is a sequence, it must be of len 2.")
            self.degrees = degrees

        self.resample = resample
        self.expand = expand
        self.center = center 
Example 6
Project: torch-toolbox   Author: PistonY   File: transforms.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(
        self, p=0.5, scale=(
            0.02, 0.33), ratio=(
            0.3, 3.3), value=0, inplace=False):
        assert isinstance(value, (numbers.Number, str, tuple, list))
        if (scale[0] > scale[1]) or (ratio[0] > ratio[1]):
            warnings.warn("range should be of kind (min, max)")
        if scale[0] < 0 or scale[1] > 1:
            raise ValueError("range of scale should be between 0 and 1")
        if p < 0 or p > 1:
            raise ValueError(
                "range of random erasing probability should be between 0 and 1")

        self.p = p
        self.scale = scale
        self.ratio = ratio
        self.value = value
        self.inplace = inplace 
Example 7
Project: torch-toolbox   Author: PistonY   File: functional.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def class_balanced_weight(beta, samples_per_class):
    assert 0 <= beta < 1, 'Wrong rang of beta {}'.format(beta)
    if not isinstance(samples_per_class, np.ndarray):
        if isinstance(samples_per_class, (list, tuple)):
            samples_per_class = np.array(samples_per_class)
        elif torch.is_tensor(samples_per_class):
            samples_per_class = samples_per_class.numpy()
        else:
            raise NotImplementedError(
                'Type of samples_per_class should be {}, {} or {} but got {}'.format(
                    (list, tuple), np.ndarray, torch.Tensor, type(samples_per_class)))
    assert isinstance(samples_per_class, np.ndarray) \
        and isinstance(beta, numbers.Number)

    balanced_matrix = (1 - beta) / (1 - np.power(beta, samples_per_class))
    return torch.Tensor(balanced_matrix) 
Example 8
Project: EXOSIMS   Author: dsavransky   File: PlanetPopulation.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def gen_mass(self, n):
        """Generate planetary mass values in units of Earth mass.
        
        The prototype provides a log-uniform distribution between the minimum and 
        maximum values.
        
        Args:
            n (integer):
                Number of samples to generate
                
        Returns:
            astropy Quantity array:
                Planet mass values in units of Earth mass.
        
        """
        n = self.gen_input_check(n)
        Mpr = self.Mprange.to('earthMass').value
        Mp = np.exp(np.random.uniform(low=np.log(Mpr[0]), high=np.log(Mpr[1]), 
                size=n))*u.earthMass
        
        return Mp 
Example 9
Project: insightface   Author: deepinsight   File: image_iter.py    License: MIT License 6 votes vote down vote up
def next_sample(self):
        """Helper function for reading in next sample."""
        #set total batch size, for example, 1800, and maximum size for each people, for example 45
        if self.seq is not None:
          while True:
            if self.cur >= len(self.seq):
                raise StopIteration
            idx = self.seq[self.cur]
            self.cur += 1
            if self.imgrec is not None:
              s = self.imgrec.read_idx(idx)
              header, img = recordio.unpack(s)
              label = header.label
              if not isinstance(label, numbers.Number):
                label = label[0]
              return label, img, None, None
            else:
              label, fname, bbox, landmark = self.imglist[idx]
              return label, self.read_image(fname), bbox, landmark
        else:
            s = self.imgrec.read()
            if s is None:
                raise StopIteration
            header, img = recordio.unpack(s)
            return header.label, img, None, None 
Example 10
Project: insightface   Author: deepinsight   File: image_iter.py    License: MIT License 6 votes vote down vote up
def next_sample(self):
        """Helper function for reading in next sample."""
        #set total batch size, for example, 1800, and maximum size for each people, for example 45
        if self.seq is not None:
          while True:
            if self.cur >= len(self.seq):
                raise StopIteration
            idx = self.seq[self.cur]
            self.cur += 1
            if self.imgrec is not None:
              s = self.imgrec.read_idx(idx)
              header, img = recordio.unpack(s)
              label = header.label
              if not isinstance(label, numbers.Number):
                label = label[0]
              return label, img, None, None
            else:
              label, fname, bbox, landmark = self.imglist[idx]
              return label, self.read_image(fname), bbox, landmark
        else:
            s = self.imgrec.read()
            if s is None:
                raise StopIteration
            header, img = recordio.unpack(s)
            return header.label, img, None, None 
Example 11
Project: DPC   Author: TengdaHan   File: augmentation.py    License: MIT License 6 votes vote down vote up
def _check_input(self, value, name, center=1, bound=(0, float('inf')), clip_first_on_zero=True):
        if isinstance(value, numbers.Number):
            if value < 0:
                raise ValueError("If {} is a single number, it must be non negative.".format(name))
            value = [center - value, center + value]
            if clip_first_on_zero:
                value[0] = max(value[0], 0)
        elif isinstance(value, (tuple, list)) and len(value) == 2:
            if not bound[0] <= value[0] <= value[1] <= bound[1]:
                raise ValueError("{} values should be between {}".format(name, bound))
        else:
            raise TypeError("{} should be a single number or a list/tuple with lenght 2.".format(name))

        # if value is 0 or (1., 1.) for brightness/contrast/saturation
        # or (0., 0.) for hue, do nothing
        if value[0] == value[1] == center:
            value = None
        return value 
Example 12
Project: Fast_Seg   Author: lxtGH   File: image_utils.py    License: Apache License 2.0 6 votes vote down vote up
def random_crop(img, gt, size):
    if isinstance(size, numbers.Number):
        size = (int(size), int(size))
    else:
        size = size

    h, w = img.shape[:2]
    crop_h, crop_w = size[0], size[1]

    if h > crop_h:
        x = random.randint(0, h - crop_h + 1)
        img = img[x:x + crop_h, :, :]
        gt = gt[x:x + crop_h, :]

    if w > crop_w:
        x = random.randint(0, w - crop_w + 1)
        img = img[:, x:x + crop_w, :]
        gt = gt[:, x:x + crop_w]

    return img, gt 
Example 13
Project: DDPAE-video-prediction   Author: jthsieh   File: video_transforms.py    License: MIT License 5 votes vote down vote up
def __init__(self, size):
    if isinstance(size, numbers.Number):
      self.size = (int(size), int(size))
    else:
      self.size = size 
Example 14
Project: DDPAE-video-prediction   Author: jthsieh   File: video_transforms.py    License: MIT License 5 votes vote down vote up
def __init__(self, padding, fill=0):
    assert isinstance(padding, numbers.Number)
    assert isinstance(fill, numbers.Number) or isinstance(fill, str) or isinstance(fill, tuple)
    self.padding = padding
    self.fill = fill 
Example 15
Project: DDPAE-video-prediction   Author: jthsieh   File: video_transforms.py    License: MIT License 5 votes vote down vote up
def __init__(self, size, padding=0):
    if isinstance(size, numbers.Number):
      self.size = (int(size), int(size))
    else:
      self.size = size
    self.padding = padding 
Example 16
Project: DeepLab_v3_plus   Author: songdejia   File: transform.py    License: MIT License 5 votes vote down vote up
def __init__(self, size, padding=0):
        if isinstance(size, numbers.Number):
            self.size = (int(size), int(size))
        else:
            self.size = size # h, w
        self.padding = padding 
Example 17
Project: DeepLab_v3_plus   Author: songdejia   File: transform.py    License: MIT License 5 votes vote down vote up
def __init__(self, size):
        if isinstance(size, numbers.Number):
            self.size = (int(size), int(size))
        else:
            self.size = size 
Example 18
Project: DeepLab_v3_plus   Author: songdejia   File: transform.py    License: MIT License 5 votes vote down vote up
def __init__(self, size):
        if isinstance(size, numbers.Number):
            self.size = (int(size), int(size))
        else:
            self.size = size#512 
Example 19
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: utils.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, size):
        if isinstance(size, numbers.Number):
            self.size = (int(size), int(size))
        else:
            self.size = size 
Example 20
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: recordio.py    License: Apache License 2.0 5 votes vote down vote up
def pack(header, s):
    """Pack a string into MXImageRecord.

    Parameters
    ----------
    header : IRHeader
        Header of the image record.
        ``header.label`` can be a number or an array. See more detail in ``IRHeader``.
    s : str
        Raw image string to be packed.

    Returns
    -------
    s : str
        The packed string.

    Examples
    --------
    >>> label = 4 # label can also be a 1-D array, for example: label = [1,2,3]
    >>> id = 2574
    >>> header = mx.recordio.IRHeader(0, label, id, 0)
    >>> with open(path, 'r') as file:
    ...     s = file.read()
    >>> packed_s = mx.recordio.pack(header, s)
    """
    header = IRHeader(*header)
    if isinstance(header.label, numbers.Number):
        header = header._replace(flag=0)
    else:
        label = np.asarray(header.label, dtype=np.float32)
        header = header._replace(flag=label.size, label=0)
        s = label.tostring() + s
    s = struct.pack(_IR_FORMAT, *header) + s
    return s 
Example 21
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: symbol.py    License: Apache License 2.0 5 votes vote down vote up
def __add__(self, other):
        """x.__add__(y) <=> x+y

        Scalar input is supported.
        Broadcasting is not supported. Use `broadcast_add` instead. """
        if isinstance(other, Symbol):
            return _internal._Plus(self, other)
        if isinstance(other, Number):
            return _internal._PlusScalar(self, scalar=other)
        else:
            raise TypeError('type %s not supported' % str(type(other))) 
Example 22
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: symbol.py    License: Apache License 2.0 5 votes vote down vote up
def __sub__(self, other):
        """x.__sub__(y) <=> x-y

        Scalar input is supported.
        Broadcasting is not supported. Use `broadcast_sub` instead. """
        if isinstance(other, Symbol):
            return _internal._Minus(self, other)
        if isinstance(other, Number):
            return _internal._MinusScalar(self, scalar=other)
        else:
            raise TypeError('type %s not supported' % str(type(other))) 
Example 23
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: symbol.py    License: Apache License 2.0 5 votes vote down vote up
def __mul__(self, other):
        """x.__mul__(y) <=> x*y

        Scalar input is supported.
        Broadcasting is not supported. Use `broadcast_mul` instead. """
        if isinstance(other, Symbol):
            return _internal._Mul(self, other)
        if isinstance(other, Number):
            return _internal._MulScalar(self, scalar=other)
        else:
            raise TypeError('type %s not supported' % str(type(other))) 
Example 24
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: symbol.py    License: Apache License 2.0 5 votes vote down vote up
def __div__(self, other):
        """x.__div__(y) <=> x/y

        Scalar input is supported.
        Broadcasting is not supported. Use `broadcast_div` instead. """
        if isinstance(other, Symbol):
            return _internal._Div(self, other)
        if isinstance(other, Number):
            return _internal._DivScalar(self, scalar=other)
        else:
            raise TypeError('type %s not supported' % str(type(other))) 
Example 25
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: symbol.py    License: Apache License 2.0 5 votes vote down vote up
def __mod__(self, other):
        """x.__mod__(y) <=> x%y

        Scalar input is supported.
        Broadcasting is not supported. Use `broadcast_mod` instead. """
        if isinstance(other, Symbol):
            return _internal._Mod(self, other)
        if isinstance(other, Number):
            return _internal._ModScalar(self, scalar=other)
        else:
            raise TypeError('type %s not supported' % str(type(other))) 
Example 26
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: symbol.py    License: Apache License 2.0 5 votes vote down vote up
def hypot(left, right):
    """Given the "legs" of a right triangle, returns its hypotenuse.

    Equivalent to :math:`\\sqrt(left^2 + right^2)`, element-wise.
    Both inputs can be Symbol or scalar number. Broadcasting is not supported.

    Parameters
    ---------
    left : Symbol or scalar
        First leg of the triangle(s).
    right : Symbol or scalar
        Second leg of the triangle(s).

    Returns
    -------
    Symbol or scalar
        The hypotenuse of the triangle(s)

    Examples
    --------
    >>> mx.sym.hypot(3, 4)
    5.0
    >>> x = mx.sym.Variable('x')
    >>> y = mx.sym.Variable('y')
    >>> z = mx.sym.hypot(x, 4)
    >>> z.eval(x=mx.nd.array([3,5,2]))[0].asnumpy()
    array([ 5.,  6.40312433,  4.47213602], dtype=float32)
    >>> z = mx.sym.hypot(x, y)
    >>> z.eval(x=mx.nd.array([3,4]), y=mx.nd.array([10,2]))[0].asnumpy()
    array([ 10.44030666,   4.47213602], dtype=float32)
    """
    if isinstance(left, Symbol) and isinstance(right, Symbol):
        return _internal._Hypot(left, right)
    if isinstance(left, Symbol) and isinstance(right, Number):
        return _internal._HypotScalar(left, scalar=right)
    if isinstance(left, Number) and isinstance(right, Symbol):
        return _internal._HypotScalar(right, scalar=left)
    if isinstance(left, Number) and isinstance(right, Number):
        return _numpy.hypot(left, right)
    else:
        raise TypeError('types (%s, %s) not supported' % (str(type(left)), str(type(right)))) 
Example 27
Project: ACAN   Author: miraiaroha   File: transforms.py    License: MIT License 5 votes vote down vote up
def __init__(self, size):
        if isinstance(size, numbers.Number):
            self.size = (int(size), int(size))
        else:
            self.size = size 
Example 28
Project: ACAN   Author: miraiaroha   File: transforms.py    License: MIT License 5 votes vote down vote up
def __init__(self, size, slide):
        if isinstance(size, numbers.Number):
            self.size = (int(size), int(size))
        else:
            self.size = size
        if isinstance(slide, numbers.Number):
            self.slide = (float(slide), float(slide))
        else:
            self.slide = slide 
Example 29
Project: tsn-pytorch   Author: yjxiong   File: transforms.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, size):
        if isinstance(size, numbers.Number):
            self.size = (int(size), int(size))
        else:
            self.size = size 
Example 30
Project: PHATE   Author: KrishnaswamyLab   File: utils.py    License: GNU General Public License v2.0 5 votes vote down vote up
def check_positive(**params):
    """Check that parameters are positive as expected

    Raises
    ------
    ValueError : unacceptable choice of parameters
    """
    for p in params:
        if not isinstance(params[p], numbers.Number) or params[p] <= 0:
            raise ValueError("Expected {} > 0, got {}".format(p, params[p]))