Python numpy.exp2() Examples

The following are 30 code examples of numpy.exp2(). 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 also want to check out all available functions/classes of the module numpy , or try the search function .
Example #1
Source File: h5tool.py    From Keras-progressive_growing_of_gans with 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 #2
Source File: folder_to_multisize_hdf5.py    From chainer-stylegan with 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 #3
Source File: fairseq.py    From neural_chat with 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 #4
Source File: choice_calcs.py    From pylogit with 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 #5
Source File: h5tool.py    From progressive_growing_of_gans_tensorflow with 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 #6
Source File: h5tool.py    From progressive_growing_of_gans_tensorflow with 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 #7
Source File: h5tool.py    From celeba-hq-modified with 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
Source File: h5tool.py    From celeba-hq-modified with 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
Source File: GA.py    From scikit-opt with MIT License 5 votes vote down vote up
def __init__(self, func, n_dim,
                 size_pop=50, max_iter=200,
                 prob_mut=0.001,
                 lb=-1, ub=1,
                 constraint_eq=tuple(), constraint_ueq=tuple(),
                 precision=1e-7):
        super().__init__(func, n_dim, size_pop, max_iter, prob_mut, constraint_eq, constraint_ueq)

        self.lb, self.ub = np.array(lb) * np.ones(self.n_dim), np.array(ub) * np.ones(self.n_dim)
        self.precision = np.array(precision) * np.ones(self.n_dim)  # works when precision is int, float, list or array

        # Lind is the num of genes of every variable of func(segments)
        Lind_raw = np.log2((self.ub - self.lb) / self.precision + 1)
        self.Lind = np.ceil(Lind_raw).astype(int)

        # if precision is integer:
        # if Lind_raw is integer, which means the number of all possible value is 2**n, no need to modify
        # if Lind_raw is decimal, we need ub_extend to make the number equal to 2**n,
        self.int_mode_ = (self.precision % 1 == 0) & (Lind_raw % 1 != 0)
        self.int_mode = np.any(self.int_mode_)
        if self.int_mode:
            self.ub_extend = np.where(self.int_mode_
                                      , self.lb + (np.exp2(self.Lind) - 1) * self.precision
                                      , self.ub)

        self.len_chrom = sum(self.Lind)

        self.crtbp() 
Example #10
Source File: test_umath.py    From mxnet-lambda with 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 #11
Source File: autoparams.py    From talos with MIT License 5 votes vote down vote up
def neurons(self, min_neuron=8, max_neuron=None, steps=None):

        '''`max` and `steps` has to be either `None` or
        integer value at the same time.'''

        if max_neuron is None and steps is None:
            values = [int(np.exp2(i)) for i in range(3, 11)]
        else:
            values = list(range(min_neuron, max_neuron, steps))

        self._append_params('first_neuron', values) 
Example #12
Source File: autoparams.py    From talos with MIT License 5 votes vote down vote up
def batch_size(self, min_size=8, max_size=None, steps=None):

        '''`max_size` and `steps` has to be either `None` or
        integer value at the same time.'''

        if max_size is None and steps is None:
            values = [int(np.exp2(i/2)) for i in range(3, 15)]
        else:
            values = list(range(min_size, max_size, steps))

        self._append_params('batch_size', values) 
Example #13
Source File: autoparams.py    From talos with MIT License 5 votes vote down vote up
def epochs(self, min_epochs=50, max_epochs=None, steps=None):

        '''`max_epochs` and `steps` has to be either `None` or
        integer value at the same time.'''

        if max_epochs is None and steps is None:
            values = [int(np.exp2(i/2))+50 for i in range(3, 15)]
        else:
            values = list(range(min_epochs, max_epochs, steps))

        self._append_params('epochs', values) 
Example #14
Source File: multicomplex.py    From numdifftools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def exp2(self):
        return np.exp(self * np.log(2)) 
Example #15
Source File: volumes.py    From diluvian with MIT License 5 votes vote down vote up
def resolution(self):
        return self.orig_resolution * np.exp2([0, self.zoom_level, self.zoom_level]) 
Example #16
Source File: volumes.py    From diluvian with MIT License 5 votes vote down vote up
def __init__(
        self,
        root_path,
        datasets,
        bounds=None,
        resolution=None,
        translation=None,
    ):

        self._dtype_map = {
            "UINT8": np.uint8,
            "UINT16": np.uint16,
            "UINT32": np.uint32,
            "UINT64": np.uint64,
            "INT8": np.int8,
            "INT16": np.int16,
            "INT32": np.int32,
            "INT64": np.int64,
            "FLOAT32": np.float32,
            "FLOAT64": np.float64,
        }
        self.bounds = bounds
        self.resolution = resolution
        self.translation = translation

        self.scale = np.exp2(np.array([0, 0, 0])).astype(np.int64)
        self.data_shape = (np.array([0, 0, 0]), self.bounds / self.scale)

        # Initialization of data sources done in setter methods
        self.root_path = root_path
        self.image_config = datasets.get("image", None)
        self.mask_config = datasets.get("mask", None)
        self.label_config = datasets.get("label", None) 
Example #17
Source File: multicomplex.py    From numdifftools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def logaddexp2(self, other):
        other = self._coerce(other)
        return self + np.log2(1 + np.exp2(other - self)) 
Example #18
Source File: test_regression.py    From coffeegrindsize with 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 #19
Source File: Metrics.py    From slates_semisynth_expts with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def computeMetric(self, query_id, ranking):
        relevanceList=self.dataset.relevances[query_id][ranking]
        gain=numpy.exp2(relevanceList)-1.0
        dcg=numpy.dot(self.discountParams[0:numpy.shape(gain)[0]], gain)
        return dcg 
Example #20
Source File: test_exponential.py    From heat with MIT License 5 votes vote down vote up
def test_exp2(self):
        elements = 10
        tmp = np.exp2(torch.arange(elements, dtype=torch.float64))
        comparison = ht.array(tmp)

        # exponential of float32
        float32_tensor = ht.arange(elements, dtype=ht.float32)
        float32_exp2 = ht.exp2(float32_tensor)
        self.assertIsInstance(float32_exp2, ht.DNDarray)
        self.assertEqual(float32_exp2.dtype, ht.float32)
        self.assertTrue(ht.allclose(float32_exp2, comparison.astype(ht.float32)))

        # exponential of float64
        float64_tensor = ht.arange(elements, dtype=ht.float64)
        float64_exp2 = ht.exp2(float64_tensor)
        self.assertIsInstance(float64_exp2, ht.DNDarray)
        self.assertEqual(float64_exp2.dtype, ht.float64)
        self.assertTrue(ht.allclose(float64_exp2, comparison))

        # exponential of ints, automatic conversion to intermediate floats
        int32_tensor = ht.arange(elements, dtype=ht.int32)
        int32_exp2 = ht.exp2(int32_tensor)
        self.assertIsInstance(int32_exp2, ht.DNDarray)
        self.assertEqual(int32_exp2.dtype, ht.float32)
        self.assertTrue(ht.allclose(int32_exp2, ht.float32(comparison)))

        # exponential of longs, automatic conversion to intermediate floats
        int64_tensor = ht.arange(elements, dtype=ht.int64)
        int64_exp2 = int64_tensor.exp2()
        self.assertIsInstance(int64_exp2, ht.DNDarray)
        self.assertEqual(int64_exp2.dtype, ht.float64)
        self.assertTrue(ht.allclose(int64_exp2, comparison))

        # check exceptions
        with self.assertRaises(TypeError):
            ht.exp2([1, 2, 3])
        with self.assertRaises(TypeError):
            ht.exp2("hello world") 
Example #21
Source File: test_basic_test.py    From heat with MIT License 5 votes vote down vote up
def test_assert_func_equal(self):
        # Testing with random values
        shape = (5, 3, 2, 9)

        self.assert_func_equal(shape, heat_func=ht.exp, numpy_func=np.exp, low=-10, high=10)

        self.assert_func_equal(shape, heat_func=ht.exp2, numpy_func=np.exp2, low=-10, high=10)

        # np.random.randn eventually creates values < 0 which will result in math.nan.
        # Because math.nan != math.nan this would always produce an exception.
        self.assert_func_equal(
            shape, heat_func=ht.log, numpy_func=np.log, data_types=[np.int32, np.int64], low=1
        )

        with self.assertRaises(AssertionError):
            self.assert_func_equal(shape, heat_func=ht.exp, numpy_func=np.exp2, low=-10, high=10)

        with self.assertRaises(ValueError):
            self.assert_func_equal(np.ones(shape), heat_func=np.exp, numpy_func=np.exp)

        with self.assertRaises(ValueError):
            self.assert_func_equal(
                shape,
                heat_func=ht.exp,
                numpy_func=np.exp,
                low=-100,
                high=100,
                data_types=[np.object],
            ) 
Example #22
Source File: test_regression.py    From mxnet-lambda with 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 #23
Source File: core.py    From neuropythy with 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 #24
Source File: text_alignment_tests.py    From policy_diffusion with MIT License 5 votes vote down vote up
def section_speed_test():

    input_sizes = [np.exp2(p) for p in range(2,9)]

    average_local_times = []
    average_section_times = []
    for input_size in input_sizes:
        print input_size
        v1 = [np.random.randint(0,10,input_size)]
        v2 = [np.random.randint(0,10,input_size)]

        cut1 = random.randint(0,len(v1))
        cut2 = random.randint(cut1,len(v2))
        cut3 = random.randint(cut2,len(v2))
        w1 = [v1[0][:cut1], v1[0][cut1:cut2], v1[0][cut2:cut3]]

        local_times = []
        section_times = []
        for i in range(2):
            t1 = time.time()
            f = LocalAligner()
            f.align(v1,v2)
            local_times.append(time.time()-t1)

            t2 = time.time()
            f = LocalAligner()
            f.align(w1,v2)
            section_times.append(time.time()-t2)
    
        average_local_times.append(np.mean(local_times))
        average_section_times.append(np.mean(section_times))
    
    plt.plot(input_sizes,average_section_times, color = 'b', label = 'section local alignment')
    plt.plot(input_sizes,average_local_times, color='r', label = 'local alignment')
    plt.legend(loc='upper right')
    plt.xlabel('input size')
    plt.ylim(0,0.02)
    plt.show() 
Example #25
Source File: text_alignment_tests.py    From policy_diffusion with MIT License 5 votes vote down vote up
def generic_doc_speed_test(algorithm):
    '''
    compares speed of algorithm to local alignment algorithm
    '''
    
    input_sizes = [np.exp2(p) for p in range(2,7)]

    average_alg_times = []
    average_local_times = []
    for input_size in input_sizes:
        print input_size
        v1 = [np.random.randint(0,10,input_size)]
        v2 = [np.random.randint(0,10,input_size)]
        local_times = []
        alg_times = []
        f = LocalAligner()
        g = algorithm()
        for i in range(2):
            t1 = time.time()
            f.align(v1,v2)
            local_times.append(time.time()-t1)
            
            t2 = time.time()
            g.align(v1,v2)
            alg_times.append(time.time()-t2)
    
        average_local_times.append(np.mean(local_times))
        average_alg_times.append(np.mean(alg_times))
    
    return average_local_times, average_alg_times 
Example #26
Source File: text_alignment_tests.py    From policy_diffusion with MIT License 5 votes vote down vote up
def LocalAligner_speed_test():
    
    input_sizes = [np.exp2(p) for p in range(2,7)]

    average_our_times = []
    average_package_times = []
    for input_size in input_sizes:
        print input_size
        v1 = [np.random.randint(0,10,input_size)]
        v2 = [np.random.randint(0,10,input_size)]
        our_times = []
        package_times = []
        f = LocalAligner()
        for i in range(2):
            t1 = time.time()
            f.align(v1,v2)
            our_times.append(time.time()-t1)
            
            t2 = time.time()
            seqToAlign(v1,v2)
            package_times.append(time.time()-t2)
    
        average_our_times.append(np.mean(our_times))
        average_package_times.append(np.mean(package_times))
    
    plt.plot(input_sizes,average_package_times, color = 'b', label = 'package')
    plt.plot(input_sizes,average_our_times, color='r', label = 'our implementation')
    plt.legend(loc='upper right')
    plt.xlabel('input size')
    plt.ylim(0,0.02)
    plt.show() 
Example #27
Source File: ops.py    From MyGrad with MIT License 5 votes vote down vote up
def backward_var(self, grad, index, **kwargs):
        return grad * np.exp2(self.variables[index].data) * np.log(2) 
Example #28
Source File: ops.py    From MyGrad with MIT License 5 votes vote down vote up
def __call__(self, a):
        """ f(a) -> 2^a

            Parameters
            ----------
            a : mygrad.Tensor

            Returns
            -------
            numpy.ndarray"""
        self.variables = (a,)
        return np.exp2(a.data) 
Example #29
Source File: test_regression.py    From pySINDy with 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
Source File: test_umath.py    From pySINDy with 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)