Python numpy.equal() Examples

The following are 30 code examples for showing how to use numpy.equal(). 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 numpy , or try the search function .

Example 1
Project: neuropythy   Author: noahbenson   File: core.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def zdivide(a, b, null=0):
    '''
    zdivide(a, b) returns the quotient a / b as a numpy array object. Unlike numpy's divide function
      or a/b syntax, zdivide will thread over the earliest dimension possible; thus if a.shape is
      (4,2) and b.shape is 4, zdivide(a,b) is a equivalent to [ai*zinv(bi) for (ai,bi) in zip(a,b)].

    The optional argument null (default: 0) may be given to specify that zeros in the arary b should
    instead be replaced with the given value in the result. Note that if this value is not equal to
    0, then any sparse array passed as argument b must be reified.

    The zdivide function never raises an error due to divide-by-zero; if you desire this behavior,
    use the divide function instead.

    Note that zdivide(a,b, null=z) is not quite equivalent to a*zinv(b, null=z) unless z is 0; if z
    is not zero, then the same elements that are zet to z in zinv(b, null=z) are set to z in the
    result of zdivide(a,b, null=z) rather than the equivalent element of a times z.
    '''
    (a,b) = unbroadcast(a,b)
    return czdivide(a,b, null=null) 
Example 2
def test_equal():
    """Test for logical greater in onnx operators."""
    input1 = np.random.rand(1, 3, 4, 5).astype("float32")
    input2 = np.random.rand(1, 5).astype("float32")
    inputs = [helper.make_tensor_value_info("input1", TensorProto.FLOAT, shape=(1, 3, 4, 5)),
              helper.make_tensor_value_info("input2", TensorProto.FLOAT, shape=(1, 5))]

    outputs = [helper.make_tensor_value_info("output", TensorProto.FLOAT, shape=(1, 3, 4, 5))]

    nodes = [helper.make_node("Equal", ["input1", "input2"], ["output"])]

    graph = helper.make_graph(nodes,
                              "equal_test",
                              inputs,
                              outputs)

    greater_model = helper.make_model(graph)
    
    bkd_rep = mxnet_backend.prepare(greater_model)
    numpy_op = np.equal(input1, input2).astype(np.float32)
    output = bkd_rep.run([input1, input2])
    npt.assert_almost_equal(output[0], numpy_op) 
Example 3
Project: brainforge   Author: csxeba   File: recurrent.py    License: GNU General Public License v3.0 6 votes vote down vote up
def feedforward(self, X):
        output = super().feedforward(X)

        for t in range(1, self.time + 1):
            time_gate = np.equal(t % self.tick_array, 0.)
            Z = np.concatenate((self.inputs[t - 1], output), axis=-1)
            gated_W = self.weights * time_gate[None, :]
            gated_b = self.biases * time_gate
            output = self.activation.forward(Z.dot(gated_W) + gated_b)

            self.Zs.append(Z)
            self.gates.append([time_gate, gated_W])
            self.cache.append(output)

        if self.return_seq:
            self.output = np.stack(self.cache, axis=1)
        else:
            self.output = self.cache[-1]

        return self.output 
Example 4
Project: PoseWarper   Author: facebookresearch   File: eval_helpers.py    License: Apache License 2.0 6 votes vote down vote up
def VOCap(rec,prec):

    mpre = np.zeros([1,2+len(prec)])
    mpre[0,1:len(prec)+1] = prec
    mrec = np.zeros([1,2+len(rec)])
    mrec[0,1:len(rec)+1] = rec
    mrec[0,len(rec)+1] = 1.0

    for i in range(mpre.size-2,-1,-1):
        mpre[0,i] = max(mpre[0,i],mpre[0,i+1])

    i = np.argwhere( ~np.equal( mrec[0,1:], mrec[0,:mrec.shape[1]-1]) )+1
    i = i.flatten()

    # compute area under the curve
    ap = np.sum( np.multiply( np.subtract( mrec[0,i], mrec[0,i-1]), mpre[0,i] ) )

    return ap 
Example 5
Project: recruit   Author: Frank-qlu   File: testutils.py    License: Apache License 2.0 6 votes vote down vote up
def approx(a, b, fill_value=True, rtol=1e-5, atol=1e-8):
    """
    Returns true if all components of a and b are equal to given tolerances.

    If fill_value is True, masked values considered equal. Otherwise,
    masked values are considered unequal.  The relative error rtol should
    be positive and << 1.0 The absolute error atol comes into play for
    those elements of b that are very small or zero; it says how small a
    must be also.

    """
    m = mask_or(getmask(a), getmask(b))
    d1 = filled(a)
    d2 = filled(b)
    if d1.dtype.char == "O" or d2.dtype.char == "O":
        return np.equal(d1, d2).ravel()
    x = filled(masked_array(d1, copy=False, mask=m), fill_value).astype(float_)
    y = filled(masked_array(d2, copy=False, mask=m), 1).astype(float_)
    d = np.less_equal(umath.absolute(x - y), atol + rtol * umath.absolute(y))
    return d.ravel() 
Example 6
Project: recruit   Author: Frank-qlu   File: testutils.py    License: Apache License 2.0 6 votes vote down vote up
def almost(a, b, decimal=6, fill_value=True):
    """
    Returns True if a and b are equal up to decimal places.

    If fill_value is True, masked values considered equal. Otherwise,
    masked values are considered unequal.

    """
    m = mask_or(getmask(a), getmask(b))
    d1 = filled(a)
    d2 = filled(b)
    if d1.dtype.char == "O" or d2.dtype.char == "O":
        return np.equal(d1, d2).ravel()
    x = filled(masked_array(d1, copy=False, mask=m), fill_value).astype(float_)
    y = filled(masked_array(d2, copy=False, mask=m), 1).astype(float_)
    d = np.around(np.abs(x - y), decimal) <= 10.0 ** (-decimal)
    return d.ravel() 
Example 7
Project: recruit   Author: Frank-qlu   File: test_utils.py    License: Apache License 2.0 6 votes vote down vote up
def test_subclass_that_overrides_eq(self):
        # While we cannot guarantee testing functions will always work for
        # subclasses, the tests should ideally rely only on subclasses having
        # comparison operators, not on them being able to store booleans
        # (which, e.g., astropy Quantity cannot usefully do). See gh-8452.
        class MyArray(np.ndarray):
            def __eq__(self, other):
                return bool(np.equal(self, other).all())

            def __ne__(self, other):
                return not self == other

        a = np.array([1., 2.]).view(MyArray)
        b = np.array([2., 3.]).view(MyArray)
        assert_(type(a == a), bool)
        assert_(a == a)
        assert_(a != b)
        self._test_equal(a, a)
        self._test_not_equal(a, b)
        self._test_not_equal(b, a) 
Example 8
Project: recruit   Author: Frank-qlu   File: test_utils.py    License: Apache License 2.0 6 votes vote down vote up
def test_error_message(self):
        with pytest.raises(AssertionError) as exc_info:
            self._assert_func(np.array([1, 2]), np.array([[1, 2]]))
        msg = str(exc_info.value)
        msg2 = msg.replace("shapes (2L,), (1L, 2L)", "shapes (2,), (1, 2)")
        msg_reference = textwrap.dedent("""\

        Arrays are not equal

        (shapes (2,), (1, 2) mismatch)
         x: array([1, 2])
         y: array([[1, 2]])""")

        try:
            assert_equal(msg, msg_reference)
        except AssertionError:
            assert_equal(msg2, msg_reference) 
Example 9
Project: recruit   Author: Frank-qlu   File: test_ufunc.py    License: Apache License 2.0 6 votes vote down vote up
def test_NotImplemented_not_returned(self):
        # See gh-5964 and gh-2091. Some of these functions are not operator
        # related and were fixed for other reasons in the past.
        binary_funcs = [
            np.power, np.add, np.subtract, np.multiply, np.divide,
            np.true_divide, np.floor_divide, np.bitwise_and, np.bitwise_or,
            np.bitwise_xor, np.left_shift, np.right_shift, np.fmax,
            np.fmin, np.fmod, np.hypot, np.logaddexp, np.logaddexp2,
            np.logical_and, np.logical_or, np.logical_xor, np.maximum,
            np.minimum, np.mod,
            np.greater, np.greater_equal, np.less, np.less_equal,
            np.equal, np.not_equal]

        a = np.array('1')
        b = 1
        c = np.array([1., 2.])
        for f in binary_funcs:
            assert_raises(TypeError, f, a, b)
            assert_raises(TypeError, f, c, a) 
Example 10
Project: recruit   Author: Frank-qlu   File: test_umath.py    License: Apache License 2.0 6 votes vote down vote up
def test_ignore_object_identity_in_equal(self):
        # Check error raised when comparing identical objects whose comparison
        # is not a simple boolean, e.g., arrays that are compared elementwise.
        a = np.array([np.array([1, 2, 3]), None], dtype=object)
        assert_raises(ValueError, np.equal, a, a)

        # Check error raised when comparing identical non-comparable objects.
        class FunkyType(object):
            def __eq__(self, other):
                raise TypeError("I won't compare")

        a = np.array([FunkyType()])
        assert_raises(TypeError, np.equal, a, a)

        # Check identity doesn't override comparison mismatch.
        a = np.array([np.nan], dtype=object)
        assert_equal(np.equal(a, a), [False]) 
Example 11
Project: recruit   Author: Frank-qlu   File: defchararray.py    License: Apache License 2.0 6 votes vote down vote up
def equal(x1, x2):
    """
    Return (x1 == x2) element-wise.

    Unlike `numpy.equal`, this comparison is performed by first
    stripping whitespace characters from the end of the string.  This
    behavior is provided for backward-compatibility with numarray.

    Parameters
    ----------
    x1, x2 : array_like of str or unicode
        Input arrays of the same shape.

    Returns
    -------
    out : ndarray or bool
        Output array of bools, or a single bool if x1 and x2 are scalars.

    See Also
    --------
    not_equal, greater_equal, less_equal, greater, less
    """
    return compare_chararrays(x1, x2, '==', True) 
Example 12
Project: recruit   Author: Frank-qlu   File: defchararray.py    License: Apache License 2.0 6 votes vote down vote up
def greater_equal(x1, x2):
    """
    Return (x1 >= x2) element-wise.

    Unlike `numpy.greater_equal`, this comparison is performed by
    first stripping whitespace characters from the end of the string.
    This behavior is provided for backward-compatibility with
    numarray.

    Parameters
    ----------
    x1, x2 : array_like of str or unicode
        Input arrays of the same shape.

    Returns
    -------
    out : ndarray or bool
        Output array of bools, or a single bool if x1 and x2 are scalars.

    See Also
    --------
    equal, not_equal, less_equal, greater, less
    """
    return compare_chararrays(x1, x2, '>=', True) 
Example 13
Project: recruit   Author: Frank-qlu   File: defchararray.py    License: Apache License 2.0 6 votes vote down vote up
def less_equal(x1, x2):
    """
    Return (x1 <= x2) element-wise.

    Unlike `numpy.less_equal`, this comparison is performed by first
    stripping whitespace characters from the end of the string.  This
    behavior is provided for backward-compatibility with numarray.

    Parameters
    ----------
    x1, x2 : array_like of str or unicode
        Input arrays of the same shape.

    Returns
    -------
    out : ndarray or bool
        Output array of bools, or a single bool if x1 and x2 are scalars.

    See Also
    --------
    equal, not_equal, greater_equal, greater, less
    """
    return compare_chararrays(x1, x2, '<=', True) 
Example 14
Project: recruit   Author: Frank-qlu   File: defchararray.py    License: Apache License 2.0 6 votes vote down vote up
def greater(x1, x2):
    """
    Return (x1 > x2) element-wise.

    Unlike `numpy.greater`, this comparison is performed by first
    stripping whitespace characters from the end of the string.  This
    behavior is provided for backward-compatibility with numarray.

    Parameters
    ----------
    x1, x2 : array_like of str or unicode
        Input arrays of the same shape.

    Returns
    -------
    out : ndarray or bool
        Output array of bools, or a single bool if x1 and x2 are scalars.

    See Also
    --------
    equal, not_equal, greater_equal, less_equal, less
    """
    return compare_chararrays(x1, x2, '>', True) 
Example 15
Project: recruit   Author: Frank-qlu   File: defchararray.py    License: Apache License 2.0 6 votes vote down vote up
def less(x1, x2):
    """
    Return (x1 < x2) element-wise.

    Unlike `numpy.greater`, this comparison is performed by first
    stripping whitespace characters from the end of the string.  This
    behavior is provided for backward-compatibility with numarray.

    Parameters
    ----------
    x1, x2 : array_like of str or unicode
        Input arrays of the same shape.

    Returns
    -------
    out : ndarray or bool
        Output array of bools, or a single bool if x1 and x2 are scalars.

    See Also
    --------
    equal, not_equal, greater_equal, less_equal, greater
    """
    return compare_chararrays(x1, x2, '<', True) 
Example 16
Project: buzzard   Author: airware   File: test_footprint_precision.py    License: Apache License 2.0 6 votes vote down vote up
def test_spatial_to_raster(fp, env):
    if env < fp._significant_min:
        pytest.skip()
    rng = np.random.RandomState(42)
    eps = np.abs(fp.coords).max() * 10 ** -buzz.env.significant

    xy = np.dstack(fp.meshgrid_spatial)
    rxy = np.dstack(fp.meshgrid_raster)
    res = np.equal(
        rxy, fp.spatial_to_raster(xy),
    )
    assert np.all(res)
    res = np.equal(
        rxy, fp.spatial_to_raster(xy + (rng.rand(*xy.shape) * 2 - 1) * eps * LESS_ERROR),
    )
    assert np.all(res)
    res = np.equal(
        rxy, fp.spatial_to_raster(xy + (rng.rand(*xy.shape) * 2 - 1) * eps * MORE_ERROR),
    )
    assert not np.all(res) 
Example 17
Project: tf-pose   Author: SrikanthVelpuri   File: ScatterPlotItem.py    License: Apache License 2.0 6 votes vote down vote up
def updateSpots(self, dataSet=None):
        if dataSet is None:
            dataSet = self.data

        invalidate = False
        if self.opts['pxMode']:
            mask = np.equal(dataSet['sourceRect'], None)
            if np.any(mask):
                invalidate = True
                opts = self.getSpotOpts(dataSet[mask])
                sourceRect = self.fragmentAtlas.getSymbolCoords(opts)
                dataSet['sourceRect'][mask] = sourceRect

            self.fragmentAtlas.getAtlas() # generate atlas so source widths are available.

            dataSet['width'] = np.array(list(imap(QtCore.QRectF.width, dataSet['sourceRect'])))/2
            dataSet['targetRect'] = None
            self._maxSpotPxWidth = self.fragmentAtlas.max_width
        else:
            self._maxSpotWidth = 0
            self._maxSpotPxWidth = 0
            self.measureSpotSizes(dataSet)

        if invalidate:
            self.invalidate() 
Example 18
Project: tf-pose   Author: SrikanthVelpuri   File: ScatterPlotItem.py    License: Apache License 2.0 6 votes vote down vote up
def getSpotOpts(self, recs, scale=1.0):
        if recs.ndim == 0:
            rec = recs
            symbol = rec['symbol']
            if symbol is None:
                symbol = self.opts['symbol']
            size = rec['size']
            if size < 0:
                size = self.opts['size']
            pen = rec['pen']
            if pen is None:
                pen = self.opts['pen']
            brush = rec['brush']
            if brush is None:
                brush = self.opts['brush']
            return (symbol, size*scale, fn.mkPen(pen), fn.mkBrush(brush))
        else:
            recs = recs.copy()
            recs['symbol'][np.equal(recs['symbol'], None)] = self.opts['symbol']
            recs['size'][np.equal(recs['size'], -1)] = self.opts['size']
            recs['size'] *= scale
            recs['pen'][np.equal(recs['pen'], None)] = fn.mkPen(self.opts['pen'])
            recs['brush'][np.equal(recs['brush'], None)] = fn.mkBrush(self.opts['brush'])
            return recs 
Example 19
Project: pycolab   Author: deepmind   File: rendering.py    License: Apache License 2.0 6 votes vote down vote up
def render(self):
    """Derive an `Observation` from this `BaseObservationRenderer`'s "canvas".

    Reminders: the values in the returned `Observation` should be accessed in
    a *read-only* manner exclusively; furthermore, if any
    `BaseObservationRenderer` method is called after `render()`, the contents
    of the `Observation` returned in that `render()` call are *undefined*
    (i.e. not guaranteed to be anything---they could be blank, random garbage,
    whatever).

    Returns:
      An `Observation` whose data members are derived from the information
      presented to this `BaseObservationRenderer` since the last call to its
      `clear()` method.
    """
    for character, layer in six.iteritems(self._layers):
      np.equal(self._board, ord(character), out=layer)
    return Observation(board=self._board, layers=self._layers) 
Example 20
Project: lambda-packs   Author: ryfeus   File: testutils.py    License: MIT License 6 votes vote down vote up
def approx(a, b, fill_value=True, rtol=1e-5, atol=1e-8):
    """
    Returns true if all components of a and b are equal to given tolerances.

    If fill_value is True, masked values considered equal. Otherwise,
    masked values are considered unequal.  The relative error rtol should
    be positive and << 1.0 The absolute error atol comes into play for
    those elements of b that are very small or zero; it says how small a
    must be also.

    """
    m = mask_or(getmask(a), getmask(b))
    d1 = filled(a)
    d2 = filled(b)
    if d1.dtype.char == "O" or d2.dtype.char == "O":
        return np.equal(d1, d2).ravel()
    x = filled(masked_array(d1, copy=False, mask=m), fill_value).astype(float_)
    y = filled(masked_array(d2, copy=False, mask=m), 1).astype(float_)
    d = np.less_equal(umath.absolute(x - y), atol + rtol * umath.absolute(y))
    return d.ravel() 
Example 21
Project: lambda-packs   Author: ryfeus   File: testutils.py    License: MIT License 6 votes vote down vote up
def almost(a, b, decimal=6, fill_value=True):
    """
    Returns True if a and b are equal up to decimal places.

    If fill_value is True, masked values considered equal. Otherwise,
    masked values are considered unequal.

    """
    m = mask_or(getmask(a), getmask(b))
    d1 = filled(a)
    d2 = filled(b)
    if d1.dtype.char == "O" or d2.dtype.char == "O":
        return np.equal(d1, d2).ravel()
    x = filled(masked_array(d1, copy=False, mask=m), fill_value).astype(float_)
    y = filled(masked_array(d2, copy=False, mask=m), 1).astype(float_)
    d = np.around(np.abs(x - y), decimal) <= 10.0 ** (-decimal)
    return d.ravel() 
Example 22
Project: aospy   Author: spencerahill   File: longitude.py    License: Apache License 2.0 5 votes vote down vote up
def __eq__(self, other):
        if isinstance(other, Longitude):
            return (self.hemisphere == other.hemisphere and
                    self.longitude == other.longitude)
        else:
            return xr.apply_ufunc(np.equal, other, self) 
Example 23
Project: mmdetection   Author: open-mmlab   File: test_masks.py    License: Apache License 2.0 5 votes vote down vote up
def test_polygon_mask_iter():
    raw_masks = dummy_raw_polygon_masks((3, 28, 28))
    polygon_masks = PolygonMasks(raw_masks, 28, 28)
    for i, polygon_mask in enumerate(polygon_masks):
        assert np.equal(polygon_mask, raw_masks[i]).all() 
Example 24
Project: mmdetection   Author: open-mmlab   File: test_transform.py    License: Apache License 2.0 5 votes vote down vote up
def test_flip():
    # test assertion for invalid flip_ratio
    with pytest.raises(AssertionError):
        transform = dict(type='RandomFlip', flip_ratio=1.5)
        build_from_cfg(transform, PIPELINES)

    # test assertion for invalid direction
    with pytest.raises(AssertionError):
        transform = dict(
            type='RandomFlip', flip_ratio=1, direction='horizonta')
        build_from_cfg(transform, PIPELINES)

    transform = dict(type='RandomFlip', flip_ratio=1)
    flip_module = build_from_cfg(transform, PIPELINES)

    results = dict()
    img = mmcv.imread(
        osp.join(osp.dirname(__file__), '../data/color.jpg'), 'color')
    original_img = copy.deepcopy(img)
    results['img'] = img
    results['img2'] = copy.deepcopy(img)
    results['img_shape'] = img.shape
    results['ori_shape'] = img.shape
    # Set initial values for default meta_keys
    results['pad_shape'] = img.shape
    results['scale_factor'] = 1.0
    results['img_fields'] = ['img', 'img2']

    results = flip_module(results)
    assert np.equal(results['img'], results['img2']).all()

    flip_module = build_from_cfg(transform, PIPELINES)
    results = flip_module(results)
    assert np.equal(results['img'], results['img2']).all()
    assert np.equal(original_img, results['img']).all() 
Example 25
Project: mmdetection   Author: open-mmlab   File: test_transform.py    License: Apache License 2.0 5 votes vote down vote up
def test_pad():
    # test assertion if both size_divisor and size is None
    with pytest.raises(AssertionError):
        transform = dict(type='Pad')
        build_from_cfg(transform, PIPELINES)

    transform = dict(type='Pad', size_divisor=32)
    transform = build_from_cfg(transform, PIPELINES)
    results = dict()
    img = mmcv.imread(
        osp.join(osp.dirname(__file__), '../data/color.jpg'), 'color')
    original_img = copy.deepcopy(img)
    results['img'] = img
    results['img2'] = copy.deepcopy(img)
    results['img_shape'] = img.shape
    results['ori_shape'] = img.shape
    # Set initial values for default meta_keys
    results['pad_shape'] = img.shape
    results['scale_factor'] = 1.0
    results['img_fields'] = ['img', 'img2']

    results = transform(results)
    assert np.equal(results['img'], results['img2']).all()
    # original img already divisible by 32
    assert np.equal(results['img'], original_img).all()
    img_shape = results['img'].shape
    assert img_shape[0] % 32 == 0
    assert img_shape[1] % 32 == 0

    resize_transform = dict(
        type='Resize', img_scale=(1333, 800), keep_ratio=True)
    resize_module = build_from_cfg(resize_transform, PIPELINES)
    results = resize_module(results)
    results = transform(results)
    img_shape = results['img'].shape
    assert np.equal(results['img'], results['img2']).all()
    assert img_shape[0] % 32 == 0
    assert img_shape[1] % 32 == 0 
Example 26
Project: mmdetection   Author: open-mmlab   File: test_transform.py    License: Apache License 2.0 5 votes vote down vote up
def test_normalize():
    img_norm_cfg = dict(
        mean=[123.675, 116.28, 103.53],
        std=[58.395, 57.12, 57.375],
        to_rgb=True)
    transform = dict(type='Normalize', **img_norm_cfg)
    transform = build_from_cfg(transform, PIPELINES)
    results = dict()
    img = mmcv.imread(
        osp.join(osp.dirname(__file__), '../data/color.jpg'), 'color')
    original_img = copy.deepcopy(img)
    results['img'] = img
    results['img2'] = copy.deepcopy(img)
    results['img_shape'] = img.shape
    results['ori_shape'] = img.shape
    # Set initial values for default meta_keys
    results['pad_shape'] = img.shape
    results['scale_factor'] = 1.0
    results['img_fields'] = ['img', 'img2']

    results = transform(results)
    assert np.equal(results['img'], results['img2']).all()

    mean = np.array(img_norm_cfg['mean'])
    std = np.array(img_norm_cfg['std'])
    converted_img = (original_img[..., ::-1] - mean) / std
    assert np.allclose(results['img'], converted_img) 
Example 27
Project: mmdetection   Author: open-mmlab   File: test_nms.py    License: Apache License 2.0 5 votes vote down vote up
def test_nms_device_and_dtypes_gpu():
    """
    CommandLine:
        xdoctest -m tests/test_nms.py test_nms_device_and_dtypes_gpu
    """
    if not torch.cuda.is_available():
        import pytest
        pytest.skip('test requires GPU and torch+cuda')

    iou_thr = 0.6
    base_dets = np.array([[49.1, 32.4, 51.0, 35.9, 0.1],
                          [49.3, 32.9, 51.0, 35.3, 0.05],
                          [35.3, 11.5, 39.9, 14.5, 0.9],
                          [35.2, 11.7, 39.7, 15.7, 0.3]])

    base_expected_suppressed = np.array([[35.3, 11.5, 39.9, 14.5, 0.9],
                                         [49.1, 32.4, 51.0, 35.9, 0.1]])

    for device_id in range(torch.cuda.device_count()):
        print(f'Run NMS on device_id = {device_id!r}')
        # GPU can handle float32 but not float64
        dets = base_dets.astype(np.float32)
        expected_suppressed = base_expected_suppressed.astype(np.float32)
        suppressed, inds = nms(dets, iou_thr, device_id)
        assert dets.dtype == suppressed.dtype
        assert np.array_equal(suppressed, expected_suppressed)

        dets = torch.FloatTensor(base_dets).to(device_id)
        expected_suppressed = torch.FloatTensor(base_expected_suppressed).to(
            device_id)
        suppressed, inds = nms(dets, iou_thr)
        assert dets.dtype == suppressed.dtype
        assert torch.equal(suppressed, expected_suppressed) 
Example 28
Project: mmdetection   Author: open-mmlab   File: test_nms.py    License: Apache License 2.0 5 votes vote down vote up
def test_nms_match():
    iou_thr = 0.6
    # empty input
    empty_dets = np.array([])
    assert len(nms_match(empty_dets, iou_thr)) == 0

    # non empty ndarray input
    np_dets = np.array([[49.1, 32.4, 51.0, 35.9, 0.9],
                        [49.3, 32.9, 51.0, 35.3, 0.9],
                        [35.3, 11.5, 39.9, 14.5, 0.4],
                        [35.2, 11.7, 39.7, 15.7, 0.3]])
    np_groups = nms_match(np_dets, iou_thr)
    assert isinstance(np_groups[0], np.ndarray)
    assert len(np_groups) == 2
    nms_keep_inds = nms(np_dets, iou_thr)[1]
    assert set([g[0].item() for g in np_groups]) == set(nms_keep_inds.tolist())

    # non empty tensor input
    tensor_dets = torch.from_numpy(np_dets)
    tensor_groups = nms_match(tensor_dets, iou_thr)
    assert isinstance(tensor_groups[0], torch.Tensor)
    for i in range(len(tensor_groups)):
        assert np.equal(tensor_groups[i].numpy(), np_groups[i]).all()

    # input of wrong shape
    wrong_dets = np.zeros((2, 3))
    with pytest.raises(AssertionError):
        nms_match(wrong_dets, iou_thr) 
Example 29
Project: neuropythy   Author: noahbenson   File: core.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def zinv(x, null=0):
    '''
    zinv(x) yields 1/x if x is not close to 0 and 0 otherwise. Automatically threads over arrays and
      supports sparse-arrays.

    The optional argument null (default: 0) may be given to specify that zeros in the arary x should
    instead be replaced with the given value. Note that if this value is not equal to 0, then any
    sparse array passed to zinv must be reified.

    The zinv function never raises an error due to divide-by-zero; if you desire this behavior, use
    the inv function instead.
    '''
    if sps.issparse(x):
        if null != 0: return zinv(x.toarray(), null=null)
        x = x.copy()
        x.data = zinv(x.data)
        try: x.eliminate_zeros()
        except Exception: pass
        return x
    else:
        x = np.asarray(x)
        z = np.isclose(x, 0)
        r = np.logical_not(z) / (x + z)
        if null == 0: return r
        r[z] = null
        return r 
Example 30
Project: neuropythy   Author: noahbenson   File: core.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def czdivide(a, b, null=0):
    '''
    czdivide(a, b) returns the quotient a / b as a numpy array object. Like numpy's divide function
      or a/b syntax, czdivide will thread over the latest dimension possible. Unlike numpy's divide,
      czdivide works with sparse matrices. Additionally, czdivide multiplies a by the zinv of b, so
      divide-by-zero entries are replaced with 0 in the result.

    The optional argument null (default: 0) may be given to specify that zeros in the arary b should
    instead be replaced with the given value in the result. Note that if this value is not equal to
    0, then any sparse array passed as argument b must be reified.

    The czdivide function never raises an error due to divide-by-zero; if you desire this behavior,
    use the cdivide function instead.
    '''
    if null == 0:         return a.multiply(zinv(b)) if sps.issparse(a) else a * zinv(b)
    elif sps.issparse(b): b = b.toarray()
    else:                 b = np.asarray(b)
    z = np.isclose(b, 0)
    q = np.logical_not(z)
    zi = q / (b + z)
    if sps.issparse(a):
        r = a.multiply(zi).tocsr()
    else:
        r = np.asarray(a) * zi
    r[np.ones(a.shape, dtype=np.bool)*z] = null
    return r