本文整理汇总了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
示例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
示例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
示例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
示例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()
示例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
示例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)
示例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
示例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)
示例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)
示例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
示例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
示例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)
示例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
示例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