# 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 , or try the search function .

Example 1
```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
```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)

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

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
```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
```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
```def _test(vectorizer, model, n_rows):
tr, va = train_test_split(tr)
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
```def finv(self, f):
return np.where(f>_lim_val, f, np.log(np.expm1(f))) ```
Example 8
```def gradfactor(self, f, df):
return df*np.where(f>_lim_val, 1.,  - np.expm1(-f)) ```
Example 9
```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
```def log_jacobian_grad(self, model_param):
return 1./(np.expm1(model_param)) ```
Example 11
```def _cdf(self, x, p):
k = floor(x)
return -expm1(log1p(-p)*k) ```
Example 12
```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
```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.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
```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
```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
```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
```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
```def expm1(x):
return _scalar(tf.math.expm1, x, True) ```
Example 19
```def forward(self, inputs, device):
x, = inputs
return functions.expm1(x), ```
Example 20
```def forward_expected(self, inputs):
x, = inputs
expected = numpy.expm1(x)
expected = utils.force_array(expected)
return expected, ```
Example 21
```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
```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
```def label(self):
return 'expm1' ```
Example 24
```def forward_gpu(self, x):
self.retain_outputs((0,))
return cuda.cupy.expm1(x[0]), ```
Example 25
```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
```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
```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
```def _cdf(self, x, p):
k = floor(x)
return -expm1(log1p(-p)*k) ```
Example 29
```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
```def grad_log_likelihood(Z, th, idx=None):