Python numpy.expm1() Examples

The following are 30 code examples for showing how to use numpy.expm1(). 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: GraphicDesignPatternByPython   Author: Relph1119   File: test_matfuncs.py    License: MIT License 6 votes vote down vote up
def test_burkardt_3(self):
        # This example is due to Laub.
        # This matrix is ill-suited for the Taylor series approach.
        # As powers of A are computed, the entries blow up too quickly.
        exp1 = np.exp(1)
        exp39 = np.exp(39)
        A = np.array([
            [0, 1],
            [-39, -40],
            ], dtype=float)
        desired = np.array([
            [
                39/(38*exp1) - 1/(38*exp39),
                -np.expm1(-38) / (38*exp1)],
            [
                39*np.expm1(-38) / (38*exp1),
                -1/(38*exp1) + 39/(38*exp39)],
            ], dtype=float)
        actual = expm(A)
        assert_allclose(actual, desired) 
Example 2
Project: copulae   Author: DanielBok   File: frank.py    License: MIT License 6 votes vote down vote up
def ipsi(self, u, log=False):
        r = np.asarray(u) * self.params

        res = np.copy(r)
        res[np.isnan(r)] = np.nan
        em = np.expm1(-self.params)

        #  for small inputs, u <= 0.01
        small_mask = np.abs(r) <= 0.01 * abs(self.params)
        res[small_mask] = -np.log(np.expm1(-r[small_mask]) / em)

        big_mask = np.abs(r) > 0.01 * abs(self.params)
        e = np.exp(-self.params)
        mid_mask = (e > 0) & (np.abs(self.params - r) < 0.5)  # theta * (1 - u) < 0.5

        m1 = big_mask & mid_mask
        m2 = big_mask & ~mid_mask
        r[m1] = -np.log1p(e * np.expm1((self.params - r[m1])) / em)
        r[m2] = -np.log1p((np.exp(-r[m2]) - e) / em)

        return np.log(r) if log else r 
Example 3
Project: copulae   Author: DanielBok   File: frank.py    License: MIT License 6 votes vote down vote up
def random(self, n: int, seed: int = None):
        u = random_uniform(n, self.dim, seed)
        if abs(self.params) < 1e-7:
            return u

        if self.dim == 2:
            v = u[:, 1]
            a = -abs(self.params)
            v = -1 / a * np.log1p(-v * np.expm1(-a) / (np.exp(-a * u[:, 0]) * (v - 1) - v))
            u[:, 1] = 1 - v if self.params > 0 else v
            return u

        # alpha too large
        if log1mexp(self.params) == 0:
            return np.ones((n, self.dim))

        fr = random_log_series_ln1p(-self.params, n)[:, None]
        return self.psi(-np.log(u) / fr) 
Example 4
Project: arviz   Author: arviz-devs   File: stats.py    License: Apache License 2.0 6 votes vote down vote up
def _gpinv(probs, kappa, sigma):
    """Inverse Generalized Pareto distribution function."""
    # pylint: disable=unsupported-assignment-operation, invalid-unary-operand-type
    x = np.full_like(probs, np.nan)
    if sigma <= 0:
        return x
    ok = (probs > 0) & (probs < 1)
    if np.all(ok):
        if np.abs(kappa) < np.finfo(float).eps:
            x = -np.log1p(-probs)
        else:
            x = np.expm1(-kappa * np.log1p(-probs)) / kappa
        x *= sigma
    else:
        if np.abs(kappa) < np.finfo(float).eps:
            x[ok] = -np.log1p(-probs[ok])
        else:
            x[ok] = np.expm1(-kappa * np.log1p(-probs[ok])) / kappa
        x *= sigma
        x[probs == 0] = 0
        if kappa >= 0:
            x[probs == 1] = np.inf
        else:
            x[probs == 1] = -sigma / kappa
    return x 
Example 5
Project: mercari-solution   Author: pjankiewicz   File: test_end_to_end.py    License: MIT License 6 votes vote down vote up
def _test(vectorizer, model, n_rows):
    tr = load_train('tests/train_10k.tsv')
    tr, va = train_test_split(tr)
    te = pd.read_csv('tests/test_10k_corrupted.tsv', sep="\t")
    if n_rows is not None:
        if n_rows == 'random':
            n_rows = np.random.randint(1, te.shape[0])
            te = te.sample(n=n_rows)
    mat_tr = vectorizer.fit_transform(tr, tr.price)
    mat_te = vectorizer.transform(te.copy())
    mat_va = vectorizer.transform(va)
    model.fit(mat_tr, np.log1p(tr.price))
    assert rmsle(np.expm1(model.predict(mat_va)), va.price) < 0.85
    te_preds = np.expm1(model.predict(mat_te))
    assert te_preds.shape[0] == te.shape[0]
    assert np.all(np.isfinite(te_preds))
    assert te_preds.min() >= -1, "min price is {}".format(te_preds.min())
    assert te_preds.max() <= 3000, "max price is {}".format(te_preds.max()) 
Example 6
def bdtrc(k, n, p):
    if (k < 0):
        return (1.0)

    if (k == n):
        return (0.0)
    dn = n - k
    if (k == 0):
        if (p < .01):
            dk = -np.expm1(dn * np.log1p(-p))
        else:
            dk = 1.0 - np.exp(dn * np.log(1.0 - p))
    else:
        dk = k + 1
        dk = betainc(dk, dn, p)
    return dk 
Example 7
Project: paramz   Author: sods   File: transformations.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def finv(self, f):
        return np.where(f>_lim_val, f, np.log(np.expm1(f))) 
Example 8
Project: paramz   Author: sods   File: transformations.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def gradfactor(self, f, df):
        return df*np.where(f>_lim_val, 1.,  - np.expm1(-f)) 
Example 9
Project: paramz   Author: sods   File: transformations.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def log_jacobian(self, model_param):
        return np.where(model_param>_lim_val, model_param, np.log(np.expm1(model_param))) - model_param 
Example 10
Project: paramz   Author: sods   File: transformations.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def log_jacobian_grad(self, model_param):
        return 1./(np.expm1(model_param)) 
Example 11
Project: lambda-packs   Author: ryfeus   File: _discrete_distns.py    License: MIT License 5 votes vote down vote up
def _cdf(self, x, p):
        k = floor(x)
        return -expm1(log1p(-p)*k) 
Example 12
Project: lambda-packs   Author: ryfeus   File: _discrete_distns.py    License: MIT License 5 votes vote down vote up
def _stats(self, lambda_):
        mu = 1/(exp(lambda_)-1)
        var = exp(-lambda_)/(expm1(-lambda_))**2
        g1 = 2*cosh(lambda_/2.0)
        g2 = 4+2*cosh(lambda_)
        return mu, var, g1, g2 
Example 13
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 14
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.expm1 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.expm1(x, sig='f')
        return numpy.expm1(x) 
Example 15
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 = expm1(%(x)s);" % locals() 
Example 16
Project: onnx-tensorflow   Author: onnx   File: test_node.py    License: Apache License 2.0 5 votes vote down vote up
def _elu(self, x):
    # f(x) = alpha * (exp(x) - 1.) for x < 0,
    # f(x) = x for x >= 0
    if x < 0.:
      return np.expm1(x)
    return x 
Example 17
Project: Mastering-Elasticsearch-7.0   Author: PacktPublishing   File: test_function_transformer.py    License: MIT License 5 votes vote down vote up
def test_check_inverse():
    X_dense = np.array([1, 4, 9, 16], dtype=np.float64).reshape((2, 2))

    X_list = [X_dense,
              sparse.csr_matrix(X_dense),
              sparse.csc_matrix(X_dense)]

    for X in X_list:
        if sparse.issparse(X):
            accept_sparse = True
        else:
            accept_sparse = False
        trans = FunctionTransformer(func=np.sqrt,
                                    inverse_func=np.around,
                                    accept_sparse=accept_sparse,
                                    check_inverse=True,
                                    validate=True)
        assert_warns_message(UserWarning,
                             "The provided functions are not strictly"
                             " inverse of each other. If you are sure you"
                             " want to proceed regardless, set"
                             " 'check_inverse=False'.",
                             trans.fit, X)

        trans = FunctionTransformer(func=np.expm1,
                                    inverse_func=np.log1p,
                                    accept_sparse=accept_sparse,
                                    check_inverse=True,
                                    validate=True)
        Xt = assert_no_warnings(trans.fit_transform, X)
        assert_allclose_dense_sparse(X, trans.inverse_transform(Xt))

    # check that we don't check inverse when one of the func or inverse is not
    # provided.
    trans = FunctionTransformer(func=np.expm1, inverse_func=None,
                                check_inverse=True, validate=True)
    assert_no_warnings(trans.fit, X_dense)
    trans = FunctionTransformer(func=None, inverse_func=np.expm1,
                                check_inverse=True, validate=True)
    assert_no_warnings(trans.fit, X_dense) 
Example 18
Project: trax   Author: google   File: math_ops.py    License: Apache License 2.0 5 votes vote down vote up
def expm1(x):
  return _scalar(tf.math.expm1, x, True) 
Example 19
Project: chainer   Author: chainer   File: test_exponential_m1.py    License: MIT License 5 votes vote down vote up
def forward(self, inputs, device):
        x, = inputs
        return functions.expm1(x), 
Example 20
Project: chainer   Author: chainer   File: test_exponential_m1.py    License: MIT License 5 votes vote down vote up
def forward_expected(self, inputs):
        x, = inputs
        expected = numpy.expm1(x)
        expected = utils.force_array(expected)
        return expected, 
Example 21
Project: chainer   Author: chainer   File: test_elu.py    License: MIT License 5 votes vote down vote up
def forward_expected(self, inputs):
        x, = inputs
        expected = x.astype(numpy.float64, copy=True)
        for i in numpy.ndindex(x.shape):
            if x[i] < 0:
                expected[i] = self.alpha * numpy.expm1(expected[i])
        return expected.astype(x.dtype), 
Example 22
Project: chainer   Author: chainer   File: test_activation.py    License: MIT License 5 votes vote down vote up
def func(self, xp, a):
        if xp is numpy:
            y = a.copy()
            negzero_indices = y <= 0
            y[negzero_indices] = self.alpha * numpy.expm1(y[negzero_indices])
            return y
        elif self.alpha_range is Unspecified:
            return xp.elu(a)
        else:
            return xp.elu(a, self.alpha) 
Example 23
Project: chainer   Author: chainer   File: exponential_m1.py    License: MIT License 5 votes vote down vote up
def label(self):
        return 'expm1' 
Example 24
Project: chainer   Author: chainer   File: exponential_m1.py    License: MIT License 5 votes vote down vote up
def forward_gpu(self, x):
        self.retain_outputs((0,))
        return cuda.cupy.expm1(x[0]), 
Example 25
Project: chainer   Author: chainer   File: exponential_m1.py    License: MIT License 5 votes vote down vote up
def expm1(x):
    """Elementwise exponential minus one function.

    Args:
        x (:class:`~chainer.Variable` or :ref:`ndarray`): Input variable.

    Returns:
        ~chainer.Variable: Output variable.
    """
    return Expm1().apply((x,))[0] 
Example 26
Project: chainer   Author: chainer   File: elu.py    License: MIT License 5 votes vote down vote up
def forward_cpu(self, inputs):
        if self.alpha < 0:
            self.retain_inputs((0,))
        x, = inputs
        y = x.copy()
        negzero_indices = y <= 0
        y[negzero_indices] = self.alpha * numpy.expm1(y[negzero_indices])
        self.retain_outputs((0,))
        return y, 
Example 27
Project: chainer   Author: chainer   File: elu.py    License: MIT License 5 votes vote down vote up
def forward_gpu(self, inputs):
        if self.alpha < 0:
            self.retain_inputs((0,))
        x, = inputs
        y = cuda.elementwise(
            'T x, T alpha', 'T y',
            'y = x > 0 ? x : (T)(alpha * expm1(x))',
            'elu_fwd')(x, self.alpha)
        self.retain_outputs((0,))
        return y, 
Example 28
Project: GraphicDesignPatternByPython   Author: Relph1119   File: _discrete_distns.py    License: MIT License 5 votes vote down vote up
def _cdf(self, x, p):
        k = floor(x)
        return -expm1(log1p(-p)*k) 
Example 29
Project: GraphicDesignPatternByPython   Author: Relph1119   File: _discrete_distns.py    License: MIT License 5 votes vote down vote up
def _stats(self, lambda_):
        mu = 1/(exp(lambda_)-1)
        var = exp(-lambda_)/(expm1(-lambda_))**2
        g1 = 2*cosh(lambda_/2.0)
        g2 = 4+2*cosh(lambda_)
        return mu, var, g1, g2 
Example 30
Project: bayesian-coresets   Author: trevorcampbell   File: model_poiss.py    License: MIT License 5 votes vote down vote up
def grad_log_likelihood(Z, th, idx=None):
  x = Z[:, :-1]
  y = Z[:, -1]
  m = compute_m(th, x)
  g = np.zeros(y.shape[0])
  g[:] = y
  mnz = m[m>1e-100]
  ynz = y[m>1e-100]
  g[m > 1e-100] = ((1.-ynz/mnz)*np.expm1(-mnz))
  if idx is None:
    return g[:, np.newaxis]*x
  return g*x[:, idx]