Learn SciPy Library In Python with Examples | For Beginners

Learn SciPy Library In Python with Examples | For Beginners

Introduction

SciPy library is built on NumPy in Python. SciPy library is 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 high level commands and classes for manipulating and visualizing data.

Sub-packages in SciPy

SciPy is collection of different sub-packages covering different scientific computation domain. 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

1) scipy.special

Now we will look some of the sub-packages of 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 some examples on 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 array as an input and returns 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 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 is exp10() function

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

Output

[  10.  100. 1000.]

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

The another special function that we’re going to look 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 log sum of exponential of the individual elements of array or list.

Lambert function

The another special function that we’re going to look 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 lambert w function and is defined as inverse of w*exp(w).

Permutationa and combination

The another special function that we’re going to look 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 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 perm() function.

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

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

Output

Combination:  120.0

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

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

Output

Combination:  [120.  20.]

2. Linear Algebra

Linear algebra in SciPy library provides function for solving equations, finding inverse, determinant of metrices, rank of metrices, eigen value and eigen vector 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 inverse of matrix. The thing that one should keep in mind using inv() function is that the matrix should be square matrix. If one wish to calculate inverse of 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 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 need to understand is the supplied matrix should be 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 these two equation and determine values of x and y in this two sets of equation, 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

Eigen values and eigen vector 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 eigen values and eigen vector of a matrix.

3. Integration

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

For single integration, 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 ‘estimated integral’ value and second is ‘upper bound on’ error. The range 0, 2 after lambda function represent the limit to the integral x. Lambda function is use for providing 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 use for providing the desired function under integration. Two sets of 0, 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)

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

4. n-dimensional image

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

SciPy has misc packages that come with images. We’ll use misc package to load a 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

open image in scipy using misc

 

 

 

 

 

 

 

 

 

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

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

Output

Shape of image:  (768, 1024, 3)

First two numbers specify the size of image and last number represent the number of color channel in the image. the number 3 represents the Red, Blue, Green channel in image.

Changing image to gray scale image

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

Output

change to grey scale image in scipy using misc

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

crop image in scipy using misc

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

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

rotate image

Conclusion

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

Reference

Happy Learning 🙂

Leave a Reply