Learn SciPy Library in Python with Examples | For Beginners

Introduction

SciPy library is built on NumPy in Python. SciPy library is a collection of mathematical algorithms and functions built-in NumPy extension in Python. It adds significant power to the interactive Python session by providing the user with high-level commands and classes for manipulating and visualizing data.

 

Sub-packages in SciPy

SciPy is a collection of different sub-packages covering different scientific computation domains. They are as follows:

  • scipy.cluster ⇒ Clustering
  • scipy.constants ⇒ Physical and Mathematical Constant
  • scipy.fftpack ⇒ Fast Fourier Transform
  • scipy.integrate ⇒ Integration
  • scipy.interpolate ⇒ Interpolation
  • scipy.io ⇒ Data Input and Output
  • scipy.linalg ⇒ Linear Algebra
  • scipy.ndimage ⇒ n-dimensional Image Package
  • scipy.odr ⇒ Orthogonal Regression
  • scipy.optimize ⇒ Optimization
  • scipy.signal ⇒ Signal Processing
  • scipy.sparse ⇒ Sparse Metrices
  • scipy.spatial ⇒ Spatial Data Structure and Algorithm
  • scipy.special ⇒ Any Special Mathematical Function
  • scipy.stats ⇒ Statistics

scipy.special

Now we will look at some of the sub-packages of the SciPy library. Some of the most frequently used special functions

  • Cubic root function
  • Exponential function
  • Relative error exponential function
  • Log sum exponential function
  • Lambert function
  • Permutation and combination function
  • Gamma function

Now we will look at some examples of the cubic root function of scipy.special

First of all, we’ll be looking cbrt function

Cubic root

from scipy.special import cbrt
a = cbrt(8)
print("Cube root is: ", a)

Output

Cube root is:  2.0

The cubic root function returns the cube root of the number that is passed to cbrt() function. The cbrt() function also takes the array as an input and returns the cubic root of the individual elements of the array. Let’s take an example of it

from scipy.special import cbrt
import numpy as np
a = cbrt(np.array([8,27,64,125]))
print("Cube root is: ", a)

Output

Cube root is:  [2. 3. 4. 5.]

Instead  of passing elements as an array, the cbrt() function also takes a python list and returns the cubic root of the individual elements of a list

from scipy.special import cbrt
a = cbrt([8,27,64,125])
print("Cube root is: ", a)

Output

Cube root is:  [2. 3. 4. 5.]

 

Exponential

The second special function that we’re looking for is the exp10() function

from scipy.special import exp10
result = exp10([1,2,3])
print(result)

Output

[  10.  100. 1000.]

exp10() function returns a value equal to 10 raised to the power of individual elements of a list in an argument of the function.

Another special function that we’re going to look at is logsumexp() function

from scipy.special import logsumexp
import numpy as np
a = np.array([1,2,3,4])
res = logsumexp(a)
print("Result of log of sum of exponential of input: ", res)

Output

Result of log of sum of exponential of input:  4.440189698561196

This function returns the log sum of the exponential of the individual elements of an array or list.

 

Lambert function

Another special function that we’re going to look at is lambertw() function

from scipy.special import lambertw
res1 = lambertw(2)
res2 = lambertw(2+3j)
print(res1)
print(res2)

Output

(0.8526055020137254+0j)
(1.0900765344857908+0.5301397207748387j)

Lambert function is also called the lambert w function and is defined as the inverse of w*exp(w).

 

Permutation and combination

Another special function that we’re going to look at is perm() and comb() function

from scipy.special import perm
res = perm(10,3)
print("Permutation: ", res)

Output

Permutation:  720

perm() function calculates the permutation of two numbers.

We also can calculate permutation between two sets of numbers as

from scipy.special import perm
res = perm([10,3],[2,1])
print("Permutation: ", res)

Output

Permutation:  [90.  3.]

This shows how permutation is calculated using the perm() function.

Like permutation, we can also calculate combination using the comb() function

from scipy.special import comb
res = comb(10,3)
print("Combination: ", res)

Output

Combination:  120.0

comb() function calculates the combination between two numbers as shown in the above example. We can also calculate the combination between two or more two pair of numbers as

from scipy.special import comb
res = comb([10,20],[3,1])
print("Combination: ", res)

Output

Combination:  [120.  20.]

 

Linear Algebra

Linear algebra in the SciPy library provides functions for solving equations, finding inverse, determinants of metrics, the rank of metrics, eigenvalue and eigenvector, and so on.

from scipy.linalg import inv
A = np.array([[2,3], [5,6]])
print("Inverse of A: \n", inv(A))

Output

Inverse of A: 
 [[-2.          1.        ]
 [ 1.66666667 -0.66666667]]

inv() function returns the inverse of a matrix. The thing that one should keep in mind using the inv() function is that the matrix should be a square matrix. If one wishes to calculate the inverse of a non-square matrix then pinv() function can be used.

from scipy.linalg import pinv
A = np.array([[2,3,4], [5,6,1]])
print("Inverse of A: \n", pinv(A))

Output

Inverse of A: 
 [[-0.04651163  0.10465116]
 [-0.00775194  0.10077519]
 [ 0.27906977 -0.12790698]]

To calculate the determinant of a matrix, det()function is used

from scipy.linalg import det
A = np.array([[2,3], [5,6]])
print("\n Determinant of A: ", det(A))

Output

Determinant of A:  -3.0

The important thing one needs to understand is the supplied matrix should be a square matrix.

Linear algebra provides a function called solve() that is used to solve the equations.

For eg:

3x+2y=4 ——–eqn(i)
4x-2y=6———eqn(ii)

If we want to solve this two-equation and determine values of x and y in these two sets of equations, we can solve easily using solve() function

from scipy.linalg import solve
a = np.array([[3,2],[4,-2]])
b = np.array([[4],[6]])
res = solve(a,b)
x = res[0][0]
y = res[1][0]
print("x: ", x)
print("y: ", y)

Output

x:  1.4285714285714286
y:  -0.14285714285714285

Let’s take another example

4x+y+2z=8 —————equation(1)
3x-5y+z = 10 ————equation(2)
7x-2-3zy=9 ————–equation(3)

We’ll use solve() function to get values of x, y, and z

from scipy.linalg import solve
a = np.array([[4,1,2],[3,-5,1],[7,2,-3]])
b = np.array([[8],[10],[9]])
res = solve(a,b)
x, y, z = res[0][0], res[1][0], res[2][0]
print("x : ",x)
print("y : ",y)
print("z : ",z)

Output

x :  1.82
y :  -0.7600000000000001
z :  0.7400000000000001

Eigenvalues and eigenvector can also be calculated using eig() function

from scipy.linalg import eig
a = np.array([[3,6],[3,1]])
eigen_values, eigen_vector = eig(a)
print("Eigen values: \n", eigen_values)
print("\nEigen vector: \n", eigen_vector)

Output

Eigen values: 
 [ 6.35889894+0.j -2.35889894+0.j]

Eigen vector: 
 [[ 0.87257427 -0.7458292 ]
 [ 0.48848147  0.66613722]]

eig() function returns eigenvalues and eigenvector of a matrix.

 

Integration

Integration is used for calculating summation, calculation area, and also to calculate volume. Single integration calculates summation, double integration calculates area and triple integration calculates the volume of the curve.

For single integration, the quad() function is used.

from scipy.integrate import quad
result = quad(lambda x:x**2, 0, 2)
print("result: ", result)
print("Value of integral: ",result[0])

Output

result:  (2.666666666666667, 2.960594732333751e-14)
Value of integral:  2.666666666666667

quad() function returns two values as tuple. The first value is the ‘estimated integral’ value and the second is the ‘upper bound’ on the error. The range 0, 2 after the lambda function represents the limit to the integral x. The Lambda function is used for providing the desired function under the integral.

To calculate double integration, dblquad() function is used

from scipy.integrate import dblquad
result = dblquad(lambda x,y:x**2*y**2, 0, 2, 0, 2)
print("Result: ", result)

Output

Result:  (7.1111111111111125, 1.1791005245764718e-13)

Here lambda function is used for providing the desired function under integration. Two sets of 0, and 2 represent the limit to the integral of y and x respectively.

For triple integration, tplquad() function is used

from scipy.integrate import tplquad
result = tplquad(lambda x,y,z:x*y*z, 0, 2, 0, 2,0,1)
print("Result: ", result)

Output

Result:  (1.9999999999999998, 2.2204460492503128e-14)

The Lambda function is used for providing the desired function inside the integral. 0,2 and 0,2 and 0,1 represent the limits to the integral of x, y, and z respectively.

 

n-dimensional image

n-dimensional image is used for image processing. Some of the image processing tasks are reading images, writing images, displaying images, flipping images, rotating images, cropping images, smoothing image, blurring images, image classification, features extraction, and so on. We’ll look at some of the above-mentioned tasks.

SciPy has misc packages that come with images. We’ll use the misc package to load an image and do image manipulation.

 

Opening image

import matplotlib.pyplot as plt
from scipy import misc
face = misc.face()
plt.imshow(face)
print("Shape of image: ", face.shape)
plt.show()

Output

scipy-open-image

 

 

We can see the shape of the image and the color channel that the image has using the shape() function.

print("Shape of image: ", face.shape)

Output

Shape of image:  (768, 1024, 3)

The first two numbers specify the size of the image and the last number represents the number of a color channel in the image. the number 3 represents the Red, Blue, and Green channels in the image.

 

Changing the image to a grayscale image

from scipy import misc
face = misc.face(gray = True)
plt.imshow(face)
plt.show()

Output

scipy-change-grayscale

 

Cropping image

from scipy import misc
face = misc.face()
crop_face = face[lx // 4: - lx // 4, ly // 4: - ly // 4]
plt.imshow(crop_face)
plt.show()

Output

scipy-crop-image

 

Flipping image

import numpy as np
from scipy import misc
face = misc.face()
flip_face = np.flipud(face)
plt.imshow(flip_face)
plt.show()

Output

scipy-flip-image

Rotating image

from scipy import misc, ndimage
face = misc.face()
rotated_face = ndimage.rotate(face, 75)
plt.imshow(rotated_face)
plt.show()

Output

scipy-rotate-image

Conclusion

SciPy library provides mathematical algorithms and functions for scientific and numerical calculation.  Integration, optimization, Input-output, Linear algebra, Image manipulation, and Interpolation are some of the features of SciPy. SciPy is built on top of NumPy so it makes use of the NumPy array. It provides fast calculation of n-dimensional array manipulation. So, SciPy is a very important scientific library for mathematics, science, and engineering.

Reference

Happy Learning 🙂

Leave a Comment