本文整理汇总了Python中numpy.exp2方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.exp2方法的具体用法?Python numpy.exp2怎么用?Python numpy.exp2使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.exp2方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import exp2 [as 别名]
def __init__(self, h5_filename, resolution, channels=3, buffer_size_mb=512):
rlog2 = int(np.floor(np.log2(resolution)))
assert resolution == 2 ** rlog2
self.resolution = resolution
self.channels = channels
self.h5_file = h5py.File(h5_filename, 'w', libver='latest')
self.h5_lods = []
self.lods = []
self.buffers = []
self.buffer_sizes = []
self.metadata = {}
for lod in range(rlog2, -1, -1):
r = 2 ** lod; c = channels
bytes_per_item = c * (r ** 2)
chunk_size = int(np.ceil(128.0 / bytes_per_item))
buffer_size = int(np.ceil(float(buffer_size_mb) * np.exp2(20) / bytes_per_item))
lod = self.h5_file.create_dataset('%dx%d' % (r,r), shape=(0,c,r,r), dtype=np.uint8,
maxshape=(None,c,r,r), chunks=(chunk_size,c,r,r), compression='gzip', compression_opts=4)
self.metadata['%dx%d' % (r, r)] = []
self.h5_lods.append(lod)
self.lods.append('%dx%d' % (r, r))
self.buffers.append(np.zeros((buffer_size,c,r,r), dtype=np.uint8))
self.buffer_sizes.append(0)
print('HDF5 Exporter will use following LODs', self.lods)
示例2: robust_outer_product
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import exp2 [as 别名]
def robust_outer_product(vec_1, vec_2):
"""
Calculates a 'robust' outer product of two vectors that may or may not
contain very small values.
Parameters
----------
vec_1 : 1D ndarray
vec_2 : 1D ndarray
Returns
-------
outer_prod : 2D ndarray. The outer product of vec_1 and vec_2
"""
mantissa_1, exponents_1 = np.frexp(vec_1)
mantissa_2, exponents_2 = np.frexp(vec_2)
new_mantissas = mantissa_1[None, :] * mantissa_2[:, None]
new_exponents = exponents_1[None, :] + exponents_2[:, None]
return new_mantissas * np.exp2(new_exponents)
示例3: __init__
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import exp2 [as 别名]
def __init__(self, h5_filename, resolution, channels=3):
rlog2 = int(np.floor(np.log2(resolution)))
assert resolution == 2 ** rlog2
self.resolution = resolution
self.channels = channels
self.h5_file = h5py.File(h5_filename, 'w')
self.h5_lods = []
self.buffers = []
self.buffer_sizes = []
for lod in xrange(rlog2, -1, -1):
r = 2 ** lod; c = channels
bytes_per_item = c * (r ** 2)
chunk_size = int(np.ceil(128.0 / bytes_per_item))
buffer_size = int(np.ceil(512.0 * np.exp2(20) / bytes_per_item))
lod = self.h5_file.create_dataset('data%dx%d' % (r,r), shape=(0,c,r,r), dtype=np.uint8,
maxshape=(None,c,r,r), chunks=(chunk_size,c,r,r), compression='gzip', compression_opts=4)
self.h5_lods.append(lod)
self.buffers.append(np.zeros((buffer_size,c,r,r), dtype=np.uint8))
self.buffer_sizes.append(0)
示例4: inspect
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import exp2 [as 别名]
def inspect(h5_filename):
print '%-20s%s' % ('HDF5 filename', h5_filename)
file_size = os.stat(h5_filename).st_size
print '%-20s%.2f GB' % ('Total size', float(file_size) / np.exp2(30))
h5 = h5py.File(h5_filename, 'r')
lods = sorted([value for key, value in h5.iteritems() if key.startswith('data')], key=lambda lod: -lod.shape[3])
shapes = [lod.shape for lod in lods]
shape = shapes[0]
h5.close()
print '%-20s%d' % ('Total images', shape[0])
print '%-20s%dx%d' % ('Resolution', shape[3], shape[2])
print '%-20s%d' % ('Color channels', shape[1])
print '%-20s%.2f KB' % ('Size per image', float(file_size) / shape[0] / np.exp2(10))
if len(lods) != int(np.log2(shape[3])) + 1:
print 'Warning: The HDF5 file contains incorrect number of LODs'
if any(s[0] != shape[0] for s in shapes):
print 'Warning: The HDF5 file contains inconsistent number of images in different LODs'
print 'Perhaps the dataset creation script was terminated abruptly?'
#----------------------------------------------------------------------------
示例5: report
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import exp2 [as 别名]
def report(self):
"""Return metrics calculated by the model."""
# if we haven't initialized yet, just return a dummy object
if not hasattr(self, "trainer"):
return {}
output = {k: v.avg for k, v in self.meters.items()}
if "nll_loss" in self.meters:
# special case, we used sentence averaging so ppl comes from nll_loss
output["ppl"] = np.exp2(self.meters["nll_loss"].avg)
else:
# normal case, just use loss
output["ppl"] = np.exp2(self.meters["loss"].avg)
# Fairseq trainer metrics we'll pass up the way
trainer_metrics = {"ups", "wps", "gnorm", "clip"}
if self.is_training:
for k in trainer_metrics:
output[k] = self.trainer.meters[k].avg
# for display purposes
output = {k: round_sigfigs(v, 4) for k, v in output.items()}
return output
示例6: __init__
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import exp2 [as 别名]
def __init__(self, h5_filename, resolution, channels=3):
rlog2 = int(np.floor(np.log2(resolution)))
assert resolution == 2 ** rlog2
self.resolution = resolution
self.channels = channels
self.h5_file = h5py.File(h5_filename, 'w')
self.h5_lods = []
self.buffers = []
self.buffer_sizes = []
for lod in range(rlog2, -1, -1):
r = 2 ** lod; c = channels
bytes_per_item = c * (r ** 2)
chunk_size = int(np.ceil(128.0 / bytes_per_item))
buffer_size = int(np.ceil(512.0 * np.exp2(20) / bytes_per_item))
#change to channel last
lod = self.h5_file.create_dataset('data%dx%d' % (r,r), shape=(0,r,r,c), dtype=np.uint8,
maxshape=(None,r,r,c), chunks=(chunk_size,r,r,c), compression='gzip', compression_opts=4)
self.h5_lods.append(lod)
self.buffers.append(np.zeros((buffer_size,r,r,c), dtype=np.uint8))
self.buffer_sizes.append(0)
示例7: __init__
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import exp2 [as 别名]
def __init__(self, h5_filename, resolution, channels=3):
rlog2 = int(np.floor(np.log2(resolution)))
assert resolution == 2 ** rlog2
self.resolution = resolution
self.channels = channels
self.h5_file = h5py.File(h5_filename, 'w')
self.h5_lods = []
self.buffers = []
self.buffer_sizes = []
for lod in xrange(rlog2, -1, -1):
r = 2 ** lod;
c = channels
bytes_per_item = c * (r ** 2)
chunk_size = int(np.ceil(128.0 / bytes_per_item))
buffer_size = int(np.ceil(512.0 * np.exp2(20) / bytes_per_item))
lod = self.h5_file.create_dataset('data%dx%d' % (r, r), shape=(0, c, r, r), dtype=np.uint8,
maxshape=(None, c, r, r), chunks=(chunk_size, c, r, r),
compression='gzip', compression_opts=4)
self.h5_lods.append(lod)
self.buffers.append(np.zeros((buffer_size, c, r, r), dtype=np.uint8))
self.buffer_sizes.append(0)
示例8: inspect
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import exp2 [as 别名]
def inspect(h5_filename):
print('%-20s%s' % ('HDF5 filename', h5_filename))
file_size = os.stat(h5_filename).st_size
print('%-20s%.2f GB' % ('Total size', float(file_size) / np.exp2(30)))
h5 = h5py.File(h5_filename, 'r')
lods = sorted([value for key, value in h5.iteritems() if key.startswith('data')], key=lambda lod: -lod.shape[3])
shapes = [lod.shape for lod in lods]
shape = shapes[0]
h5.close()
print('%-20s%d' % ('Total images', shape[0]))
print('%-20s%dx%d' % ('Resolution', shape[3], shape[2]))
print('%-20s%d' % ('Color channels', shape[1]))
print('%-20s%.2f KB' % ('Size per image', float(file_size) / shape[0] / np.exp2(10)))
if len(lods) != int(np.log2(shape[3])) + 1:
print('Warning: The HDF5 file contains incorrect number of LODs')
if any(s[0] != shape[0] for s in shapes):
print('Warning: The HDF5 file contains inconsistent number of images in different LODs')
print('Perhaps the dataset creation script was terminated abruptly?')
# ----------------------------------------------------------------------------
示例9: exp2
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import exp2 [as 别名]
def exp2(x):
x = to_potential(x)
if is_const_potential(x): return PotentialConstant(np.exp2(x.c))
else: return ConstantPowerPotential(2.0, x)
示例10: _fractal_correlation_get_r
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import exp2 [as 别名]
def _fractal_correlation_get_r(r, signal, dist):
if isinstance(r, str):
if r == "nolds":
sd = np.std(signal, ddof=1)
min_r, max_r, factor = 0.1 * sd, 0.5 * sd, 1.03
r_n = int(np.floor(np.log(1.0 * max_r / min_r) / np.log(factor)))
r_vals = np.array([min_r * (factor ** i) for i in range(r_n + 1)])
elif r == "Corr_Dim":
r_min, r_max = np.min(dist[np.where(dist > 0)]), np.exp(np.floor(np.log(np.max(dist))))
n_r = np.int(np.floor(np.log(r_max / r_min))) + 1
ones = -1 * np.ones([n_r])
r_vals = r_max * np.exp(ones * np.arange(n_r) - ones)
elif r == "boon2008":
r_min, r_max = np.min(dist[np.where(dist > 0)]), np.max(dist)
r_vals = r_min + np.arange(1, 65) * ((r_max - r_min) / 64)
if isinstance(r, int):
dist_range = np.max(dist) - np.min(dist)
r_min, r_max = (np.min(dist) + 0.025 * dist_range), (np.min(dist) + 0.5 * dist_range)
r_vals = np.exp2(np.linspace(np.log2(r_min), np.log2(r_max), r, endpoint=True))
return r_vals
示例11: expspace
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import exp2 [as 别名]
def expspace(start, stop, num=50, base=1):
"""Exponential range.
Creates a list of integer values of a given length from start to stop, spread by an exponential function.
Parameters
----------
start : int
Minimum range values.
stop : int
Maximum range values.
num : int
Number of samples to generate. Default is 50. Must be non-negative.
base : float
If 1, will use ``np.exp()``, if 2 will use ``np.exp2()``.
Returns
-------
array
An array of integer values spread by the exponential function.
Examples
---------
>>> import neurokit2 as nk
>>> nk.expspace(start=4, stop=100, num=10) #doctest: +ELLIPSIS
array([ 4, 6, 8, 12, 17, 24, 34, 49, 70, 100])
"""
if base == 1:
seq = np.exp(np.linspace(np.log(start), np.log(stop), num, endpoint=True))
else:
seq = np.exp2(np.linspace(np.log2(start), np.log2(stop), num, endpoint=True)) # pylint: disable=E1111
# Round and convert to int
seq = np.round(seq).astype(np.int)
return seq
示例12: test_exp2_values
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import exp2 [as 别名]
def test_exp2_values(self):
x = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]
y = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for dt in ['f', 'd', 'g']:
xf = np.array(x, dtype=dt)
yf = np.array(y, dtype=dt)
assert_almost_equal(np.exp2(yf), xf)
示例13: test_log1p_compiler_shenanigans
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import exp2 [as 别名]
def test_log1p_compiler_shenanigans(self):
# Check if log1p is behaving on 32 bit intel systems.
assert_(np.isfinite(np.log1p(np.exp2(-53))))
示例14: eval_per_query
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import exp2 [as 别名]
def eval_per_query(self, y, y_pred):
"""
This method helps compute the DCG score per query. It is called by
the eval function which averages and aggregates the scores
for each query.
Parameters
----------
y: numpy array
Represents the labels of instances corresponding to one query in
the dataset (ground truth).
y_pred: numpy array.
Represents the predicted document scores obtained during the model
scoring phase for that query.
Returns
-------
dcg: float
Represents the DCG score for one query.
"""
idx_y_pred_sorted = np.argsort(y_pred)[::-1]
if self.cutoff is not None:
idx_y_pred_sorted = idx_y_pred_sorted[:self.cutoff]
discount = np.log2(np.arange(2, idx_y_pred_sorted.size + 2))
if self.implementation == "flat":
gain = y[idx_y_pred_sorted]
elif self.implementation == "exp":
gain = np.exp2(y[idx_y_pred_sorted]) - 1.0
dcg = (gain / discount).sum()
return dcg
示例15: exp2
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import exp2 [as 别名]
def exp2(x, out=None, where=None, **kwargs):
"""
Calculate `2**p` for all `p` in the input tensor.
Parameters
----------
x : array_like
Input values.
out : Tensor, None, or tuple of tensor and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or `None`,
a freshly-allocated tensor is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
Values of True indicate to calculate the ufunc at that position, values
of False indicate to leave the value in the output alone.
**kwargs
Returns
-------
out : Tensor
Element-wise 2 to the power `x`.
See Also
--------
power
Examples
--------
>>> import mars.tensor as mt
>>> mt.exp2([2, 3]).execute()
array([ 4., 8.])
"""
op = TensorExp2(**kwargs)
return op(x, out=out, where=where)