当前位置: 首页>>代码示例>>Python>>正文


Python numpy.all方法代码示例

本文整理汇总了Python中numpy.all方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.all方法的具体用法?Python numpy.all怎么用?Python numpy.all使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在numpy的用法示例。


在下文中一共展示了numpy.all方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: is_pos_def

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import all [as 别名]
def is_pos_def(self, A):
        """
        Check for positive definiteness.

        Parameters
        ---------
        A : array
            square symmetric matrix.

        Returns
        -------
        bool
            whether matrix is positive-definite.
            Warning! Returns false for arrays containing inf or NaN.


        """
        # Check for valid numbers
        if np.any(np.isnan(A)) or np.any(np.isinf(A)):
            return False

        else:
            return np.all(np.real(np.linalg.eigvals(A)) > 0) 
开发者ID:wmkouw,项目名称:libTLDA,代码行数:25,代码来源:suba.py

示例2: test_one_hot

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import all [as 别名]
def test_one_hot():
    """Check if one_hot returns correct label matrices."""
    # Generate label vector
    y = np.hstack((np.ones((10,))*0,
                   np.ones((10,))*1,
                   np.ones((10,))*2))

    # Map to matrix
    Y, labels = one_hot(y)

    # Check for only 0's and 1's
    assert len(np.setdiff1d(np.unique(Y), [0, 1])) == 0

    # Check for correct labels
    assert np.all(labels == np.unique(y))

    # Check correct shape of matrix
    assert Y.shape[0] == y.shape[0]
    assert Y.shape[1] == len(labels) 
开发者ID:wmkouw,项目名称:libTLDA,代码行数:21,代码来源:test_util.py

示例3: test_region_init

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import all [as 别名]
def test_region_init():
    region = Region(
        name='test',
        description='region description',
        west_bound=0.,
        east_bound=5,
        south_bound=0,
        north_bound=90.,
        do_land_mask=True
    )
    assert region.name == 'test'
    assert region.description == 'region description'
    assert isinstance(region.mask_bounds, tuple)
    assert len(region.mask_bounds) == 1
    assert isinstance(region.mask_bounds[0], BoundsRect)
    assert np.all(region.mask_bounds[0] ==
                  (Longitude(0.), Longitude(5), 0, 90.))
    assert region.do_land_mask is True 
开发者ID:spencerahill,项目名称:aospy,代码行数:20,代码来源:test_region.py

示例4: find_match

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import all [as 别名]
def find_match(self, pred, gt):
    '''
    Match component to balls.
    '''
    batch_size, n_frames_input, n_components, _ = pred.shape
    diff = pred.reshape(batch_size, n_frames_input, n_components, 1, 2) - \
               gt.reshape(batch_size, n_frames_input, 1, n_components, 2)
    diff = np.sum(np.sum(diff ** 2, axis=-1), axis=1)
    # Direct indices
    indices = np.argmin(diff, axis=2)
    ambiguous = np.zeros(batch_size, dtype=np.int8)
    for i in range(batch_size):
      _, counts = np.unique(indices[i], return_counts=True)
      if not np.all(counts == 1):
        ambiguous[i] = 1
    return indices, ambiguous 
开发者ID:jthsieh,项目名称:DDPAE-video-prediction,代码行数:18,代码来源:metrics.py

示例5: test_bounds

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import all [as 别名]
def test_bounds(self):
        """
        Test that out-of-bounds coordinates return NaN reddening, and that
        in-bounds coordinates do not return NaN reddening.
        """

        for mode in (['random_sample', 'random_sample_per_pix',
                      'median', 'samples', 'mean']):
            # Draw random coordinates, both above and below dec = -30 degree line
            n_pix = 1000
            ra = -180. + 360.*np.random.random(n_pix)
            dec = -75. + 90.*np.random.random(n_pix)    # 45 degrees above/below
            c = coords.SkyCoord(ra, dec, frame='icrs', unit='deg')

            ebv_calc = self._bayestar(c, mode=mode)

            nan_below = np.isnan(ebv_calc[dec < -35.])
            nan_above = np.isnan(ebv_calc[dec > -25.])
            pct_nan_above = np.sum(nan_above) / float(nan_above.size)

            # print r'{:s}: {:.5f}% nan above dec=-25 deg.'.format(mode, 100.*pct_nan_above)

            self.assertTrue(np.all(nan_below))
            self.assertTrue(pct_nan_above < 0.05) 
开发者ID:gregreen,项目名称:dustmaps,代码行数:26,代码来源:test_bayestar.py

示例6: map_values

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import all [as 别名]
def map_values(values, pos, target_pos, dtype=None, nan=dat.CPG_NAN):
    """Maps `values` array at positions `pos` to `target_pos`.

    Inserts `nan` for uncovered positions.
    """
    assert len(values) == len(pos)
    assert np.all(pos == np.sort(pos))
    assert np.all(target_pos == np.sort(target_pos))

    values = values.ravel()
    pos = pos.ravel()
    target_pos = target_pos.ravel()
    idx = np.in1d(pos, target_pos)
    pos = pos[idx]
    values = values[idx]
    if not dtype:
        dtype = values.dtype
    target_values = np.empty(len(target_pos), dtype=dtype)
    target_values.fill(nan)
    idx = np.in1d(target_pos, pos).nonzero()[0]
    assert len(idx) == len(values)
    assert np.all(target_pos[idx] == pos)
    target_values[idx] = values
    return target_values 
开发者ID:kipoi,项目名称:models,代码行数:26,代码来源:dataloader_m.py

示例7: image_to_cortex

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import all [as 别名]
def image_to_cortex(self, image,
                        surface='midgray', hemi=None, affine=Ellipsis, method=None, fill=0,
                        dtype=None, weights=None):
        '''
        sub.image_to_cortex(image) is equivalent to the tuple
          (sub.lh.from_image(image), sub.rh.from_image(image)).
        sub.image_to_cortex(image, surface) uses the given surface (see also cortex.surface).
        '''
        if hemi is None: hemi = 'both'
        hemi = hemi.lower()
        if hemi in ['both', 'lr', 'all', 'auto']:
            return tuple(
                [self.image_to_cortex(image, surface=surface, hemi=h, affine=affine,
                                      method=method, fill=fill, dtype=dtype, weights=weights)
                 for h in ['lh', 'rh']])
        else:
            hemi = getattr(self, hemi)
            return hemi.from_image(image, surface=surface, affine=affine,
                                   method=method, fill=fill, dtype=dtype, weights=weights) 
开发者ID:noahbenson,项目名称:neuropythy,代码行数:21,代码来源:core.py

示例8: get_constraint_value

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import all [as 别名]
def get_constraint_value(self, applyMultiframePrior=True):
        """
        Compute all partial Structure Factor (SQs).

        :Parameters:
            #. applyMultiframePrior (boolean): Whether to apply subframe weight
               and prior to the total. This will only have an effect when used
               frame is a subframe and in case subframe weight and prior is
               defined.

        :Returns:
            #. SQs (dictionary): The SQs dictionnary, where keys are the
               element wise intra and inter molecular SQs and values are
               the computed SQs.
        """
        if self.data is None:
            LOGGER.warn("data must be computed first using 'compute_data' method.")
            return {}
        return self._get_constraint_value(self.data, applyMultiframePrior=applyMultiframePrior) 
开发者ID:bachiraoun,项目名称:fullrmc,代码行数:21,代码来源:StructureFactorConstraints.py

示例9: getImgIds

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import all [as 别名]
def getImgIds(self, imgIds=[], catIds=[]):
        '''
        Get img ids that satisfy given filter conditions.
        :param imgIds (int array) : get imgs for given ids
        :param catIds (int array) : get imgs with all given cats
        :return: ids (int array)  : integer array of img ids
        '''
        imgIds = imgIds if type(imgIds) == list else [imgIds]
        catIds = catIds if type(catIds) == list else [catIds]

        if len(imgIds) == len(catIds) == 0:
            ids = self.imgs.keys()
        else:
            ids = set(imgIds)
            for i, catId in enumerate(catIds):
                if i == 0 and len(ids) == 0:
                    ids = set(self.catToImgs[catId])
                else:
                    ids &= set(self.catToImgs[catId])
        return list(ids) 
开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:22,代码来源:coco.py

示例10: annToRLE

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import all [as 别名]
def annToRLE(self, ann):
        """
        Convert annotation which can be polygons, uncompressed RLE to RLE.
        :return: binary mask (numpy 2D array)
        """
        t = self.imgs[ann['image_id']]
        h, w = t['height'], t['width']
        segm = ann['segmentation']
        if type(segm) == list:
            # polygon -- a single object might consist of multiple parts
            # we merge all parts into one mask rle code
            # rles = maskUtils.frPyObjects(segm, h, w)
            # rle = maskUtils.merge(rles)
            raise NotImplementedError("maskUtils disabled!")
        elif type(segm['counts']) == list:
            # uncompressed RLE
            # rle = maskUtils.frPyObjects(segm, h, w)
            raise NotImplementedError("maskUtils disabled!")
        else:
            # rle
            rle = ann['segmentation']
        return rle 
开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:24,代码来源:coco.py

示例11: test_module_input_grads

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import all [as 别名]
def test_module_input_grads():
    a = mx.sym.Variable('a', __layout__='NC')
    b = mx.sym.Variable('b', __layout__='NC')
    c = mx.sym.Variable('c', __layout__='NC')

    c = a + 2 * b + 3 * c
    net = mx.mod.Module(c, data_names=['b', 'c', 'a'], label_names=None,
                        context=[mx.cpu(0), mx.cpu(1)])
    net.bind(data_shapes=[['b', (5, 5)], ['c', (5, 5)], ['a', (5, 5)]],
             label_shapes=None, inputs_need_grad=True)
    net.init_params()

    net.forward(data_batch=mx.io.DataBatch(data=[nd.ones((5, 5)),
                                                 nd.ones((5, 5)),
                                                 nd.ones((5, 5))]))
    net.backward(out_grads=[nd.ones((5, 5))])
    input_grads = net.get_input_grads()
    b_grad = input_grads[0].asnumpy()
    c_grad = input_grads[1].asnumpy()
    a_grad = input_grads[2].asnumpy()
    assert np.all(a_grad == 1), a_grad
    assert np.all(b_grad == 2), b_grad
    assert np.all(c_grad == 3), c_grad 
开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:25,代码来源:test_module.py

示例12: test_module_reshape

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import all [as 别名]
def test_module_reshape():
    data = mx.sym.Variable('data')
    sym = mx.sym.FullyConnected(data, num_hidden=20, name='fc')

    dshape = (7, 20)
    mod = mx.mod.Module(sym, ('data',), None, context=[mx.cpu(0), mx.cpu(1)])
    mod.bind(data_shapes=[('data', dshape)])
    mod.init_params()
    mod.init_optimizer(optimizer_params={'learning_rate': 1})

    mod.forward(mx.io.DataBatch(data=[mx.nd.ones(dshape)],
                                label=None))
    mod.backward([mx.nd.ones(dshape)])
    mod.update()
    assert mod.get_outputs()[0].shape == dshape
    assert (mod.get_params()[0]['fc_bias'].asnumpy() == -1).all()

    dshape = (14, 20)
    mod.reshape(data_shapes=[('data', dshape)])
    mod.forward(mx.io.DataBatch(data=[mx.nd.ones(dshape)],
                                label=None))
    mod.backward([mx.nd.ones(dshape)])
    mod.update()
    assert mod.get_outputs()[0].shape == dshape
    assert (mod.get_params()[0]['fc_bias'].asnumpy() == -3).all() 
开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:27,代码来源:test_module.py

示例13: test_sparse_nd_setitem

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import all [as 别名]
def test_sparse_nd_setitem():
    def check_sparse_nd_setitem(stype, shape, dst):
        x = mx.nd.zeros(shape=shape, stype=stype)
        x[:] = dst
        dst_nd = mx.nd.array(dst) if isinstance(dst, (np.ndarray, np.generic)) else dst
        assert np.all(x.asnumpy() == dst_nd.asnumpy() if isinstance(dst_nd, NDArray) else dst)

    shape = rand_shape_2d()
    for stype in ['row_sparse', 'csr']:
        # ndarray assignment
        check_sparse_nd_setitem(stype, shape, rand_ndarray(shape, 'default'))
        check_sparse_nd_setitem(stype, shape, rand_ndarray(shape, stype))
        # numpy assignment
        check_sparse_nd_setitem(stype, shape, np.ones(shape))
    # scalar assigned to row_sparse NDArray
    check_sparse_nd_setitem('row_sparse', shape, 2) 
开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:18,代码来源:test_sparse_ndarray.py

示例14: _project_to_map

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import all [as 别名]
def _project_to_map(map, vertex, wt=None, ignore_points_outside_map=False):
  """Projects points to map, returns how many points are present at each
  location."""
  num_points = np.zeros((map.size[1], map.size[0]))
  vertex_ = vertex[:, :2] - map.origin
  vertex_ = np.round(vertex_ / map.resolution).astype(np.int)
  if ignore_points_outside_map:
    good_ind = np.all(np.array([vertex_[:,1] >= 0, vertex_[:,1] < map.size[1],
                                vertex_[:,0] >= 0, vertex_[:,0] < map.size[0]]),
                      axis=0)
    vertex_ = vertex_[good_ind, :]
    if wt is not None:
      wt = wt[good_ind, :]
  if wt is None:
    np.add.at(num_points, (vertex_[:, 1], vertex_[:, 0]), 1)
  else:
    assert(wt.shape[0] == vertex.shape[0]), \
      'number of weights should be same as vertices.'
    np.add.at(num_points, (vertex_[:, 1], vertex_[:, 0]), wt)
  return num_points 
开发者ID:ringringyi,项目名称:DOTA_models,代码行数:22,代码来源:map_utils.py

示例15: raw_valid_fn_vec

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import all [as 别名]
def raw_valid_fn_vec(self, xyt):
    """Returns if the given set of nodes is valid or not."""
    height = self.traversible.shape[0]
    width = self.traversible.shape[1]
    x = np.round(xyt[:,[0]]).astype(np.int32)
    y = np.round(xyt[:,[1]]).astype(np.int32)
    is_inside = np.all(np.concatenate((x >= 0, y >= 0,
                                       x < width, y < height), axis=1), axis=1)
    x = np.minimum(np.maximum(x, 0), width-1)
    y = np.minimum(np.maximum(y, 0), height-1)
    ind = np.ravel_multi_index((y,x), self.traversible.shape)
    is_traversible = self.traversible.ravel()[ind]

    is_valid = np.all(np.concatenate((is_inside[:,np.newaxis], is_traversible),
                                     axis=1), axis=1)
    return is_valid 
开发者ID:ringringyi,项目名称:DOTA_models,代码行数:18,代码来源:nav_env.py


注:本文中的numpy.all方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。