當前位置: 首頁>>代碼示例>>Python>>正文


Python numpy.around方法代碼示例

本文整理匯總了Python中numpy.around方法的典型用法代碼示例。如果您正苦於以下問題:Python numpy.around方法的具體用法?Python numpy.around怎麽用?Python numpy.around使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在numpy的用法示例。


在下文中一共展示了numpy.around方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: float_prep

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import around [as 別名]
def float_prep(array, around):
    """
    Rounds floats to a common value and build positive zeros to prevent hash conflicts.
    """
    if isinstance(array, (list, np.ndarray)):
        # Round array
        array = np.around(array, around)
        # Flip zeros
        array[np.abs(array) < 5 ** (-(around + 1))] = 0

    elif isinstance(array, (float, int)):
        array = round(array, around)
        if array == -0.0:
            array = 0.0
    else:
        raise TypeError("Type '{}' not recognized".format(type(array).__name__))

    return array 
開發者ID:MolSSI,項目名稱:QCElemental,代碼行數:20,代碼來源:molecule.py

示例2: minimize_mask

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import around [as 別名]
def minimize_mask(bbox, mask, mini_shape):
    """Resize masks to a smaller version to reduce memory load.
    Mini-masks can be resized back to image scale using expand_masks()
    See inspect_data.ipynb notebook for more details.
    """
    mini_mask = np.zeros(mini_shape + (mask.shape[-1],), dtype=bool)
    for i in range(mask.shape[-1]):
        # Pick slice and cast to bool in case load_mask() returned wrong dtype
        m = mask[:, :, i].astype(bool)
        y1, x1, y2, x2 = bbox[i][:4]
        m = m[y1:y2, x1:x2]
        if m.size == 0:
            raise Exception("Invalid bounding box with area of zero")
        # Resize with bilinear interpolation
        m = resize(m, mini_shape)
        mini_mask[:, :, i] = np.around(m).astype(np.bool)
    return mini_mask 
開發者ID:dataiku,項目名稱:dataiku-contrib,代碼行數:19,代碼來源:utils.py

示例3: expand_mask

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import around [as 別名]
def expand_mask(bbox, mini_mask, image_shape):
    """Resizes mini masks back to image size. Reverses the change
    of minimize_mask().
    See inspect_data.ipynb notebook for more details.
    """
    mask = np.zeros(image_shape[:2] + (mini_mask.shape[-1],), dtype=bool)
    for i in range(mask.shape[-1]):
        m = mini_mask[:, :, i]
        y1, x1, y2, x2 = bbox[i][:4]
        h = y2 - y1
        w = x2 - x1
        # Resize with bilinear interpolation
        m = resize(m, (h, w))
        mask[y1:y2, x1:x2, i] = np.around(m).astype(np.bool)
    return mask


# TODO: Build and use this function to reduce code duplication 
開發者ID:dataiku,項目名稱:dataiku-contrib,代碼行數:20,代碼來源:utils.py

示例4: build_coco_results

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import around [as 別名]
def build_coco_results(dataset, image_ids, rois, class_ids, scores, masks):
    """Arrange resutls to match COCO specs in http://cocodataset.org/#format
    """
    # If no results, return an empty list
    if rois is None:
        return []

    results = []
    for image_id in image_ids:
        # Loop through detections
        for i in range(rois.shape[0]):
            class_id = class_ids[i]
            score = scores[i]
            bbox = np.around(rois[i], 1)
            mask = masks[:, :, i]

            result = {
                "image_id": image_id,
                "category_id": dataset.get_source_class_id(class_id, "coco"),
                "bbox": [bbox[1], bbox[0], bbox[3] - bbox[1], bbox[2] - bbox[0]],
                "score": score,
                "segmentation": maskUtils.encode(np.asfortranarray(mask))
            }
            results.append(result)
    return results 
開發者ID:dataiku,項目名稱:dataiku-contrib,代碼行數:27,代碼來源:coco.py

示例5: almost

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import around [as 別名]
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() 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:19,代碼來源:testutils.py

示例6: test_numpy_round

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import around [as 別名]
def test_numpy_round(self):
        values = [[[-3.2, 2.2], [0, -4.8213], [3.123, 123.12],
                   [-1566.213, 88.88], [-12, 94.5]],
                  [[-5.82, 3.5], [6.21, -73.272], [-9.087, 23.12],
                   [272.212, -99.99], [23, -76.5]]]
        evalues = [[[float(np.around(i)) for i in j] for j in k]
                   for k in values]
        p = Panel(values, items=['Item1', 'Item2'],
                  major_axis=date_range('1/1/2000', periods=5),
                  minor_axis=['A', 'B'])
        expected = Panel(evalues, items=['Item1', 'Item2'],
                         major_axis=date_range('1/1/2000', periods=5),
                         minor_axis=['A', 'B'])
        result = np.round(p)
        assert_panel_equal(expected, result)

        msg = "the 'out' parameter is not supported"
        with pytest.raises(ValueError, match=msg):
            np.round(p, out=p)

    # removing Panel before NumPy enforces, so just ignore 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:23,代碼來源:test_panel.py

示例7: test_reindex_nearest

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import around [as 別名]
def test_reindex_nearest():
    s = Series(np.arange(10, dtype='int64'))
    target = [0.1, 0.9, 1.5, 2.0]
    actual = s.reindex(target, method='nearest')
    expected = Series(np.around(target).astype('int64'), target)
    assert_series_equal(expected, actual)

    actual = s.reindex_like(actual, method='nearest')
    assert_series_equal(expected, actual)

    actual = s.reindex_like(actual, method='nearest', tolerance=1)
    assert_series_equal(expected, actual)
    actual = s.reindex_like(actual, method='nearest',
                            tolerance=[1, 2, 3, 4])
    assert_series_equal(expected, actual)

    actual = s.reindex(target, method='nearest', tolerance=0.2)
    expected = Series([0, 1, np.nan, 2], target)
    assert_series_equal(expected, actual)

    actual = s.reindex(target, method='nearest',
                       tolerance=[0.3, 0.01, 0.4, 3])
    expected = Series([0, np.nan, np.nan, 2], target)
    assert_series_equal(expected, actual) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:26,代碼來源:test_alter_index.py

示例8: make_tif

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import around [as 別名]
def make_tif(path, tloffset=(0, 0), reso=(0.25, -0.25), rsize=(20, 10),
             proj=SRS[0]['wkt'], channel_count=1, dtype=gdal.GDT_Float32):
    """Create a tiff files and return info about it"""
    tl = ROOT_TL + tloffset
    reso = np.asarray(reso)
    fp = buzz.Footprint(tl=tl, rsize=rsize, size=np.abs(reso * rsize))
    x, y = fp.meshgrid_spatial
    x = np.abs(x) - abs(ROOT_TL[0])
    y = abs(ROOT_TL[1]) - np.abs(y)
    x *= 15
    y *= 15
    a = x / 2 + y / 2
    a = np.around(a).astype('float32')
    driver = gdal.GetDriverByName('GTiff')
    dataset = driver.Create(path, rsize[0], rsize[1], channel_count, dtype)
    dataset.SetGeoTransform(fp.gt)
    dataset.SetProjection(proj)
    for i in range(channel_count):
        dataset.GetRasterBand(i + 1).WriteArray(a)
        dataset.GetRasterBand(i + 1).SetNoDataValue(-32000.)
    dataset.FlushCache()
    return path, fp, a 
開發者ID:airware,項目名稱:buzzard,代碼行數:24,代碼來源:tools.py

示例9: testAroundExecution

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import around [as 別名]
def testAroundExecution(self):
        data = np.random.randn(10, 20)
        x = tensor(data, chunk_size=3)

        t = x.round(2)

        res = self.executor.execute_tensor(t, concat=True)[0]
        expected = np.around(data, decimals=2)

        np.testing.assert_allclose(res, expected)

        data = sps.random(10, 20, density=.2)
        x = tensor(data, chunk_size=3)

        t = x.round(2)

        res = self.executor.execute_tensor(t, concat=True)[0]
        expected = np.around(data.toarray(), decimals=2)

        np.testing.assert_allclose(res.toarray(), expected) 
開發者ID:mars-project,項目名稱:mars,代碼行數:22,代碼來源:test_arithmetic_execution.py

示例10: _get_random_proposals

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import around [as 別名]
def _get_random_proposals(self, current_best, num_samples):
		# get uniform samples first
		uniform_samples = []
		for var_index, full_var_dict in enumerate(self.var_dicts):
			var_dict = full_var_dict[self.var_names[var_index]]
			sampled_values = self.random_number_generator.generate(var_dict, size = (self.var_sizes[var_index], self.total_size * num_samples))
			uniform_samples.extend(sampled_values)
		uniform_samples = np.array(uniform_samples).transpose()

		proposals = np.array(uniform_samples)

		num_narrows = int(0.25 * num_samples) + 1
		for sd in [0.03, 0.01, 0.003, 0.001, 0.0003]:
			# also get some samples around the current best
			# TODO: this only works for floats!!
			gauss_samples = current_best + np.random.normal(0., sd * self.var_p_ranges, size = (self.total_size * num_narrows, len(current_best)))
			gauss_samples = np.where(gauss_samples < self.var_p_lows, self.var_p_lows, gauss_samples)
			gauss_samples = np.where(self.var_p_highs < gauss_samples, self.var_p_highs, gauss_samples)

			proposals = np.concatenate([proposals, gauss_samples])
		return np.array(proposals) 
開發者ID:aspuru-guzik-group,項目名稱:phoenics,代碼行數:23,代碼來源:sampler.py

示例11: encode

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import around [as 別名]
def encode(self, buf):

        # normalise input
        arr = ensure_ndarray(buf).view(self.dtype)

        # apply scaling
        precision = 10. ** -self.digits
        exp = math.log(precision, 10)
        if exp < 0:
            exp = int(math.floor(exp))
        else:
            exp = int(math.ceil(exp))
        bits = math.ceil(math.log(10. ** -exp, 2))
        scale = 2. ** bits
        enc = np.around(scale * arr) / scale

        # cast dtype
        enc = enc.astype(self.astype, copy=False)

        return enc 
開發者ID:zarr-developers,項目名稱:numcodecs,代碼行數:22,代碼來源:quantize.py

示例12: encode

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import around [as 別名]
def encode(self, buf):

        # normalise input
        arr = ensure_ndarray(buf).view(self.dtype)

        # flatten to simplify implementation
        arr = arr.reshape(-1, order='A')

        # compute scale offset
        enc = (arr - self.offset) * self.scale

        # round to nearest integer
        enc = np.around(enc)

        # convert dtype
        enc = enc.astype(self.astype, copy=False)

        return enc 
開發者ID:zarr-developers,項目名稱:numcodecs,代碼行數:20,代碼來源:fixedscaleoffset.py

示例13: _load

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import around [as 別名]
def _load(self, filename):
        data = np.loadtxt(filename, delimiter=',').astype(np.int64)
        data[:, 0:2] = data[:, 0:2] - data[:, 0:2].min()
        num_nodes = data[:, 0:2].max() - data[:, 0:2].min() + 1
        delta = datetime.timedelta(days=14).total_seconds()
        # The source code is not released, but the paper indicates there're
        # totally 137 samples. The cutoff below has exactly 137 samples.
        time_index = np.around(
            (data[:, 3] - data[:, 3].min())/delta).astype(np.int64)
        for i in range(time_index.max()):
            g = DGLGraph()
            g.add_nodes(num_nodes)
            row_mask = time_index <= i
            edges = data[row_mask][:, 0:2]
            rate = data[row_mask][:, 2]
            g.add_edges(edges[:, 0], edges[:, 1])
            g.edata['h'] = rate.reshape(-1, 1)
            self.graphs.append(g) 
開發者ID:dmlc,項目名稱:dgl,代碼行數:20,代碼來源:bitcoinotc.py

示例14: minimize_mask

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import around [as 別名]
def minimize_mask(bbox, mask, mini_shape):
    """Resize masks to a smaller version to reduce memory load.
    Mini-masks can be resized back to image scale using expand_masks()

    See inspect_data.ipynb notebook for more details.
    """
    mini_mask = np.zeros(mini_shape + (mask.shape[-1],), dtype=bool)
    for i in range(mask.shape[-1]):
        # Pick slice and cast to bool in case load_mask() returned wrong dtype
        m = mask[:, :, i].astype(bool)
        y1, x1, y2, x2 = bbox[i][:4]
        m = m[y1:y2, x1:x2]
        if m.size == 0:
            raise Exception("Invalid bounding box with area of zero")
        # Resize with bilinear interpolation
        m = resize(m, mini_shape)
        mini_mask[:, :, i] = np.around(m).astype(np.bool)
    return mini_mask 
開發者ID:dmechea,項目名稱:PanopticSegmentation,代碼行數:20,代碼來源:utils.py

示例15: expand_mask

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import around [as 別名]
def expand_mask(bbox, mini_mask, image_shape):
    """Resizes mini masks back to image size. Reverses the change
    of minimize_mask().

    See inspect_data.ipynb notebook for more details.
    """
    mask = np.zeros(image_shape[:2] + (mini_mask.shape[-1],), dtype=bool)
    for i in range(mask.shape[-1]):
        m = mini_mask[:, :, i]
        y1, x1, y2, x2 = bbox[i][:4]
        h = y2 - y1
        w = x2 - x1
        # Resize with bilinear interpolation
        m = resize(m, (h, w))
        mask[y1:y2, x1:x2, i] = np.around(m).astype(np.bool)
    return mask


# TODO: Build and use this function to reduce code duplication 
開發者ID:dmechea,項目名稱:PanopticSegmentation,代碼行數:21,代碼來源:utils.py


注:本文中的numpy.around方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。