Python Scipy Exponential – Helpful Tutorial

In this Python tutorial, we will learn the use of “Python Scipy Exponential” and we will cover its use with the help of multiple examples. Moreover, we will cover the following topics.

  • Python Scipy Exponential
  • Python Scipy Exponential Integral
  • Python Scipy Exponential Curve Fit
  • Python Scipy Exponential Matrix
  • Python Scipy Exponential Regression
  • Python Scipy Exponential Interpolation

Also, check the latest related Python tutorial: Python Scipy Kdtree

Python Scipy Exponential

The scipy.stats.expon represents the continuous random variable. It has different kinds of functions of exponential distribution like CDF, PDF, median, etc.

It has two important parameters loc for the mean and scale for standard deviation, as we know we control the shape and location of distribution using these parameters.

The syntax is given below.

scipy.stats.expon.method_name(x,q,loc,scale,size)

Where parameters are:

  • x(float or float of array_data): It is used to specify the random variable.
  • q(float or float of array_data): It represents the probabilities.
  • loc: It is used to specify the mean, by default it is 0.
  • scale: It is used to specify the standard deviation, by default it is 1.
  • size: It is used to specify the output shape.

The above parameters are the common parameter of all the methods in the object scipy.stats.expon(). The methods are given below.

  • scipy.stats.expon.CDF(): It is used for the cumulative distribution function.
  • scipy.stats.expon.PDF(): It is used for the probability density function.
  • scipy.stats.expon.rvs(): To get the random variates.
  • scipy.stats.expon.stats(): It is used to get the standard deviation, mean, kurtosis, and skew.
  • scipy.stats.expon.logPDF(): It is used to get the log related to the probability density function.
  • scipy.stats.expon.logCDF(): It is used to find the log related to the cumulative distribution function.
  • scipy.stats.expon.sf(): It is used to get the values of the survival function.
  • scipy.stats.expon.isf(): It is used to get the values of the inverse survival function.
  • scipy.stats.expon.logsf(): It is used to find the log related to the survival function.
  • scipy.stats.expon.mean(): It is used to find the mean related to the normal distribution.
  • scipy.stats.expon.median(): It is used to find the median related to the normal distribution.
  • scipy.stats.expon.var(): It is used to find the variance related to the distribution.
  • scipy.stats.expon.std(): It is used to find the standard deviation related to the distribution

Let’s take an example by using one of the methods mentioned above to know how to use the methods with parameters.

Import the required libraries using the below code.

from scipy.stats import expon
import numpy as np
import matplotlib.pyplot as plt

Create an array containing the 30 values using the below code.

array_data = np.arange(-1,30,0.1)

Now plot the probability density function by accessing the method PDF() of an object expon of the module scipy.stats using the below code.

expon_PDF_data = expon.pdf(array_data,0,2)
plt.plot(array_data,expon_PDF_data,'bo')
plt.show()
Scipy Exponential
Scipy Exponential

This is how to use the method expon() of Python SciPy.

READ:  How NumPy Filter 2D Array by Condition in Python [6 Methods]

Read: Scipy Find Peaks

Python Scipy Exponential Integral

The Python Scipy contains a method expi() within the module scipy.special that is used for exponential integrals. The exponential integral Ei is a specific function on the complex plane in mathematics. It’s defined as a single definite integral of the ratio of an exponential function to its input.

The syntax is given below.

scipy.special.expi(x, out=None)

Where parameters are:

  • x(array_data): It is an argument with a real or complex value.
  • out(ndarray): For the function results, there is an optional output array.

The method expi() returns ndarray or scalar.

Let’s take an example by following the below steps:

Import the required libraries using the below python code.

import numpy as np
from scipy import special

Create an array and pass this array to the method expi() for exponential integral as shown in the below code.

array_data = np.array([4, 1, 2, 3])
special.expi(array_data)

again provide the negative array using the below code.

array_data = np.array([4, 1, 2, 3])
-special.expi(-array_data)
Python Scipy Exponential Integral
Python Scipy Exponential Integral

This is how to use the method expi() of Python SciPy for exponential integral.

Read: Python Scipy Special

Python Scipy Exponential Curve Fit

The Python SciPy has a method curve_fit() in a module scipy.optimize that fit a function to data using non-linear least squares. So here in this section, we will create an exponential function and pass this function to a method curve_fit() to fit the generated data.

The syntax is given below.

scipy.optimize.curve_fit(f, xdata, ydata, sigma=None, p0=None, absolute_sigma=True, bounds=(- inf, inf), check_finite=True, jac=None, method=None)

Where parameters are:

  • f(callable): The model function is represented by f(x,…) The first input must be the independent variable, and the following arguments must be the parameters to fit.
  • xdata(array_data): The independent variable is used to compare the data.
  • ydata(array_data): The dependent data is an M-dimensional array.
  • p0(array_data): For the parameters, this is the first guess. If none is specified, all of the initial values will be one.
  • sigma(M*M array): This approach determines the unpredictability in ydata. We get r = ydata – f(xdata, *popt) when we employ the formula r = ydata – f(xdata, *popt) to calculate residuals.f(xdata, *popt) to calculate residuals, we get r = ydata – f(xdata, *popt).
  • absolute_sigma(boolean): If True, sigma is employed in a strict meaning, and the parameter covariance pcov is generated to reflect these stringent values.
  • check_finite(boolean): If True, check the input arrays for nans of infs and throw a ValueError if they exist.
  • bounds(tuple array_data): The lower and upper boundaries of parameters are not supplied by default. The members of the tuple must either be an array or a scalar with the same length as the number of parameters.
  • method: Optimisation method to employ. For further information, see least squares. If boundaries are provided, the default is ‘trf’ for unconstrained issues and ‘lm’ for confined problems. The method ‘lm’ will not work if the number of observations is less than the number of variables; instead, use ‘dogbox’ or ‘trf’.
  • jac(string, callable, none): The model function’s Jacobian matrix in terms of parameters is generated as a dense array-like structure with the signature jac(x,…). The sigma provided will be used to scale it.
READ:  NumPy random number between two values in Python [3 Methods]

Let’s take an example by following the below steps:

Import the required libraries using the below python code.

import numpy as np
from scipy import optimize
import matplotlib.pyplot as plt
%matplotlib inline

Define an exponential function using the below code.

def expfunc(x, y, z, s):
    return y * np.exp(-z * x) + s

Define the data so that it can be fitted with noise and fit for the function expfunc parameters and also limit the optimization to a certain area using the below code.

x_data = np.linspace(0, 5, 60)
y_data = expfunc(x_data, 3.1, 2.3, 1.0)
random_numgen = np.random.default_rng()
noise_y = 0.3 * random_numgen.normal(size=x_data.size)
data_y = y_data + noise_y
plt.plot(x_data, data_y, 'b-', label='data')

p_opt, p_cov = optimize.curve_fit(expfunc, x_data, data_y)
plt.plot(x_data, expfunc(x_data, *p_opt), 'r-',
         label='fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple(p_opt))
Python Scipy Exponential Curve Fit
Python Scipy Exponential Curve Fit

This is how to use the method curve_fit() of Python SciPy.

Read: Python Scipy Matrix + Examples

Python Scipy Exponential Matrix

The Python SciPy module scipy.linalg contains a method expm() that uses Pade approximation to compute the matrix exponential.

The syntax is given below.

scipy.linalg.expm(A)

Where parameter A accepts the matrix of the type array.

The method expm() returns exponential of matrix A of type ndarray.

Let’s take an example by following the below steps:

Import the required libraries using the below python code.

from scipy import linalg
import numpy as np

Create a matrix and compute the exponential of that matrix using the below code.

mat = np.array([[4.0, 2.0], [6.0, -2.0]])
linalg.expm(2j*mat)
Python Scipy Exponential Matrix
Python Scipy Exponential Matrix

This is how to use the method expm() of Python, SciPy to compute the matrix exponential.

Read: Scipy Normal Distribution

Python Scipy Exponential Regression

An exponential model can be used to calculate orthogonal distance regression. The Python SciPy has a method exponential() within the module scipy.odr for that.

The Syntax is given below.

scipy.odr.exponential = <scipy.odr._models._ExponentialModel object>

The above method doesn’t accept any parameters, we can use it directly with the data.

Let’s take an example by following the below steps:

Import the required libraries using the below python code.

import numpy as np
from scipy import odr

Generate x and y data using the below code.

x_data = np.linspace(0.0, 8.0)
y_data = -20.0 + np.exp(0.8*x_data)

Fit the data using the method odr() of SciPy.

odr_data = odr.Data(x_data, y_data)

Now pass the exponential model that is odr.exponential and the data to a method ODR() for creating the odr object using the below code.

obj_odr = odr.ODR(odr_data, odr.exponential)

Execute the regression method of the above-created object using the below code.

result = obj_odr.run()
print(result.beta)
Python Scipy Exponential Regression
Python Scipy Exponential Regression

This is how to use the method odr() of Python SciPy for the exponential model to calculate orthogonal distance regression.

READ:  Attributeerror: Module 'tensorflow' has no attribute 'sparse_tensor_to_dense'

Read: Scipy Ndimage Rotate

Python Scipy Exponential Interpolation

Python SciPy contains a method interp1d() that takes arrays of values x and y to approximate a function f: y = f (x). Here we will pass the exponential function or values to the method interp1d().

The syntax is given below.

scipy.interpolate.interp1d(x, y, axis=- 1, kind='linear', copy=True, fill_value=nan, bounds_error=None, assume_sorted=False)

Where parameters are:

  • x(array_data): A one-dimensional array of real values.
  • y(array_data): A real-valued N-D array. Along the interpolation axis, the length of y must equal the length of x.
  • axis(int): Interpolate along the y-axis specified. The last axis of y is used for interpolation.
  • kind(int, str): As a string or an integer, specifies the type of interpolation to employ and the order of the spline interpolator to apply.
  • copy(boolean): If True, the class copies x and y inside. If False, x and y references are used. Copy is the default setting.
  • fill_value(array_data): This value will be used to fill in for desired points outside of the data range if it is a ndarray (or float). If no value is specified, NaN is used as the default. The array-like must broadcast properly to the non-interpolation axes’ dimensions.
  • bounds_error(boolean): If True, each time interpolation is tried on a value outside of the range of x, a ValueError is raised. If False, the fill value is allocated to out-of-bounds values. Unless fill value=”extrapolate” is specified, an error is raised by default.
  • assume_sorted(boolean): If False, the x values can be in any sequence and are sorted first. If True, x must be an array of rising values in monotonic order.

Let’s take an example by following the below steps:

Import the required libraries using the below python code.

from scipy.interpolate import interp1d
import matplotlib.pyplot as plt
import numpy as np

Generate x and y values and pass both values to a method interp1d() using the below code.

x_val = np.arange(0, 20)
y_val = np.exp(-x_val/4.0)
fun = interp1d(x_val, y_val)

Create new xdata and ydata values using the below code.

xdata = np.arange(0, 15, 0.1)
ydata = fun(xdata)

Plot the above data using the below code.

plt.plot(x_val, y_val, 'o', xdata, ydata, '-')
plt.show()
Python Scipy Exponential Interpolation
Python Scipy Exponential Interpolation

This is how to use the method interp1d() of Python SciPy to generate the exponential values.

Also, take a look at some more Python SciPy tutorials.

So, in this tutorial, we have learned about the “Python SciPy Exponential” and covered the following topics.

  • Python Scipy Exponential
  • Python Scipy Exponential Integral
  • Python Scipy Exponential Curve Fit
  • Python Scipy Exponential Matrix
  • Python Scipy Exponential Regression
  • Python Scipy Exponential Interpolation