Python numpy.exp2() Examples

The following are 30 code examples for showing how to use numpy.exp2(). 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: chainer-stylegan   Author: pfnet-research   File: folder_to_multisize_hdf5.py    License: MIT License 6 votes vote down vote up
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) 
Example 2
Project: pylogit   Author: timothyb0912   File: choice_calcs.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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) 
Example 3
Project: celeba-hq-modified   Author: willylulu   File: h5tool.py    License: MIT License 6 votes vote down vote up
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) 
Example 4
Project: celeba-hq-modified   Author: willylulu   File: h5tool.py    License: MIT License 6 votes vote down vote up
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?'

#---------------------------------------------------------------------------- 
Example 5
Project: neural_chat   Author: natashamjaques   File: fairseq.py    License: MIT License 6 votes vote down vote up
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 
Example 6
Project: Keras-progressive_growing_of_gans   Author: MSC-BUAA   File: h5tool.py    License: MIT License 6 votes vote down vote up
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) 
Example 7
Project: progressive_growing_of_gans_tensorflow   Author: zhangqianhui   File: h5tool.py    License: MIT License 6 votes vote down vote up
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) 
Example 8
Project: progressive_growing_of_gans_tensorflow   Author: zhangqianhui   File: h5tool.py    License: MIT License 6 votes vote down vote up
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?')


# ---------------------------------------------------------------------------- 
Example 9
Project: neuropythy   Author: noahbenson   File: core.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def exp2(x):
    x = to_potential(x)
    if is_const_potential(x): return PotentialConstant(np.exp2(x.c))
    else:                     return ConstantPowerPotential(2.0, x) 
Example 10
Project: NeuroKit   Author: neuropsychology   File: fractal_correlation.py    License: MIT License 5 votes vote down vote up
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 
Example 11
Project: NeuroKit   Author: neuropsychology   File: expspace.py    License: MIT License 5 votes vote down vote up
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 
Example 12
Project: recruit   Author: Frank-qlu   File: test_umath.py    License: Apache License 2.0 5 votes vote down vote up
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) 
Example 13
Project: recruit   Author: Frank-qlu   File: test_regression.py    License: Apache License 2.0 5 votes vote down vote up
def test_log1p_compiler_shenanigans(self):
        # Check if log1p is behaving on 32 bit intel systems.
        assert_(np.isfinite(np.log1p(np.exp2(-53)))) 
Example 14
Project: rankeval   Author: hpclab   File: dcg.py    License: Mozilla Public License 2.0 5 votes vote down vote up
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 
Example 15
Project: mars   Author: mars-project   File: exp2.py    License: Apache License 2.0 5 votes vote down vote up
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) 
Example 16
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_umath.py    License: MIT License 5 votes vote down vote up
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) 
Example 17
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_regression.py    License: MIT License 5 votes vote down vote up
def test_log1p_compiler_shenanigans(self):
        # Check if log1p is behaving on 32 bit intel systems.
        assert_(np.isfinite(np.log1p(np.exp2(-53)))) 
Example 18
Project: D-VAE   Author: muhanzhang   File: test_var.py    License: MIT License 5 votes vote down vote up
def test_numpy_method():
    # This type of code is used frequently by PyMC3 users
    x = tt.dmatrix('x')
    data = np.random.rand(5, 5)
    x.tag.test_value = data
    for fct in [np.arccos, np.arccosh, np.arcsin, np.arcsinh,
                np.arctan, np.arctanh, np.ceil, np.cos, np.cosh, np.deg2rad,
                np.exp, np.exp2, np.expm1, np.floor, np.log,
                np.log10, np.log1p, np.log2, np.rad2deg,
                np.sin, np.sinh, np.sqrt, np.tan, np.tanh, np.trunc]:
        y = fct(x)
        f = theano.function([x], y)
        utt.assert_allclose(np.nan_to_num(f(data)),
                            np.nan_to_num(fct(data))) 
Example 19
Project: D-VAE   Author: muhanzhang   File: basic.py    License: MIT License 5 votes vote down vote up
def impl(self, x):
        # If x is an int8 or uint8, numpy.exp2 will compute the result in
        # half-precision (float16), where we want float32.
        x_dtype = str(getattr(x, 'dtype', ''))
        if x_dtype in ('int8', 'uint8'):
            return numpy.exp2(x, sig='f')
        return numpy.exp2(x) 
Example 20
Project: D-VAE   Author: muhanzhang   File: basic.py    License: MIT License 5 votes vote down vote up
def grad(self, inputs, gout):
        (x,) = inputs
        (gz,) = gout
        if x.type in complex_types:
            raise NotImplementedError()
        if self(x).type in discrete_types:
            if x.type in discrete_types:
                return [x.zeros_like(dtype=theano.config.floatX)]
            else:
                return [x.zeros_like()]

        return gz * exp2(x) * log(numpy.cast[x.type](2)), 
Example 21
Project: D-VAE   Author: muhanzhang   File: basic.py    License: MIT License 5 votes vote down vote up
def c_code(self, node, name, inputs, outputs, sub):
        (x,) = inputs
        (z,) = outputs
        if node.inputs[0].type in complex_types:
            raise NotImplementedError('type not supported', type)
        return "%(z)s = exp2(%(x)s);" % locals() 
Example 22
Project: tmtoolkit   Author: WZBSocialScienceCenter   File: tm_gensim.py    License: Apache License 2.0 5 votes vote down vote up
def _get_model_perplexity(model, eval_corpus):
    n_words = sum(cnt for document in eval_corpus for _, cnt in document)
    bound = model.bound(eval_corpus)
    perwordbound = bound / n_words

    return np.exp2(-perwordbound) 
Example 23
Project: vnpy_crypto   Author: birforce   File: test_umath.py    License: MIT License 5 votes vote down vote up
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) 
Example 24
Project: vnpy_crypto   Author: birforce   File: test_regression.py    License: MIT License 5 votes vote down vote up
def test_log1p_compiler_shenanigans(self):
        # Check if log1p is behaving on 32 bit intel systems.
        assert_(np.isfinite(np.log1p(np.exp2(-53)))) 
Example 25
Project: Computable   Author: ktraunmueller   File: test_umath.py    License: MIT License 5 votes vote down vote up
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) 
Example 26
Project: Computable   Author: ktraunmueller   File: test_regression.py    License: MIT License 5 votes vote down vote up
def test_log1p_compiler_shenanigans(self):
        # Check if log1p is behaving on 32 bit intel systems.
        assert_(np.isfinite(np.log1p(np.exp2(-53)))) 
Example 27
Project: Computable   Author: ktraunmueller   File: test_matfuncs.py    License: MIT License 5 votes vote down vote up
def test_briggs_helper_function(self):
        np.random.seed(1234)
        for a in np.random.randn(10) + 1j * np.random.randn(10):
            for k in range(5):
                x_observed = _matfuncs_inv_ssq._briggs_helper_function(a, k)
                x_expected = a ** np.exp2(-k) - 1
                assert_allclose(x_observed, x_expected) 
Example 28
Project: Mastering-Elasticsearch-7.0   Author: PacktPublishing   File: test_umath.py    License: MIT License 5 votes vote down vote up
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) 
Example 29
Project: Mastering-Elasticsearch-7.0   Author: PacktPublishing   File: test_regression.py    License: MIT License 5 votes vote down vote up
def test_log1p_compiler_shenanigans(self):
        # Check if log1p is behaving on 32 bit intel systems.
        assert_(np.isfinite(np.log1p(np.exp2(-53)))) 
Example 30
Project: trax   Author: google   File: math_ops.py    License: Apache License 2.0 5 votes vote down vote up
def logaddexp2(x1, x2):
  amax = maximum(x1, x2)
  delta = x1 - x2
  return array_ops.where(
      isnan(delta),
      x1 + x2,  # NaNs or infinities of the same sign.
      amax + log1p(exp2(-abs(delta))) / np.log(2))