Python SciPy Tutorial for Beginners

Python consists of SciPy, which is an open-source library. The library is distributed under a BSD license.

Python Scipy is meant to compute the scientific, mathematical, and engineering problems. It is user-friendly. It is a useful tool for numerical integration and optimization. SciPy is pronounced as Sigh Pi. SciPy is a scientific library.

Let us learn more about Python Scipy through this TechVidvan Python Tutorial.

Python SCiPy Tutorial

SciPy is the base library. It is built on top of NumPy extension. There is no need to import NumPy if we have SciPy imported. It includes working on arrays.

The SciPy is compatible with the N-dimensional array object of NumPy. It consists of code for the operation of NumPy functions. SciPy and NumPy together is the best choice for scientific operations.

Prerequisite

The two essential prerequisites for SciPy are Python and Mathematics. As SciPy is built on python language, basic learning about Python is a requirement.

Also, as SciPy is for carrying out mathematical calculations, knowledge of mathematics is necessary for output verification and understanding.

Uses of SciPy

SciPy is a very useful scientific library for mathematical and scientific calculations. It consists of a wide range of mathematical algorithms to work with. It helps create useful programs. SciPy has significant additions being an open-source library. It has a variety of modules, which is a very beneficial source for scientific calculations.

SciPy Sub-packages

SciPy consists of a variety of packages to carry out a range of functionalities. It has packages for specific requirements. It consists of more than 15 packages for carrying out the operations.

SciPy has a dedicated package for statistical functions, linear algebra, clustering of the data, image and signal processing, for matrices, for integration and differentiation, etc.

Here are some of the examples:

  • linalg – It is a package dedicated to carrying out linear algebra operations.
  • cluster – It is a package for conducting clustering algorithms
  • constants – it works with constant values.
  • integrate – it is to perform the differentiation and integration functions
  • ndimage – it is for image processing
  • signal – it is a package for signal processing
  • stats – it works for statistical functions
  • io – it is meant to work for input and output operations.
  • fftpack – it is meant for Fourier transform operation.
  • odr – it is for orthogonal distance regression.
  • special – it is a module for special functions.
  • sparse – it is meant to work with sparse matrices.
  • spatial – it is meant to work with spatial data and algorithms.
  • weaves – it is a tool meant for writing purposes.
  • interpolation – it is meant for interpolation operations.
  • optimize – it is a tool for the optimization of the arrays.

NumPy vs SciPy

Scipy is an open-source library, hence its functionality keeps on growing. Numpy on the other hand has lesser functionality.

The difference also lies in the array object.

The arrays in NumPy are homogenous while this constraint does not exist in SciPy. Scipy builds on Numpy and hence both the libraries are interrelated.

File Input Output Package

SciPy has capabilities to work along with other files. It has the input/output package which enables us to access other file formats.

With this package, we can work with Matlab, Arff, Wave, Matrix Market, IDL, NetCDF, TXT, CSV, and binary format files.

We take an example of Matlab file format,

import numpy as np
 from scipy import io as sio
 array = np.zeros((5, 5))
 sio.savemat('example.mat', {'ar': array}) 
 data = sio.loadmat('example.mat', struct_as_record=True)
 data['ar']

Output

array([[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.]])

Special Function Package

SciPy consists of a scipy.special package to work with complex mathematical and physics calculations. It consists of a wide range of functions for these calculations. It can deal with logarithmic, exponential, permutations and combinations, parabolic and exponential problems. It has functions for cube roots, lambert, beta, gamma, Bessel, and hypergeometry.

All these functions follow the broadcasting and array looping regulations.

We can call the functions as follows:

#log sum function : scipy.special.logsumexp(x)

#bessel function : scipy.special.jn()

#cube root function : scipy.special.cbrt(x)

Exponential Function

from scipy.special import exp10
# exp function 
exp = exp10([1,10])
print(exp)

Output

[1.e+01 1.e+10]

Permutations and Combination

from scipy.special import comb,perm
# combinations 
com = comb(3, 4, exact = False, repetition=True)
print(com)
 
 
# permutation
per = perm(3, 2, exact = True)
print(per)

Output

15.0
6

Linear Algebra with SciPy

Scipy consists of scipy.linalg whose working based on BLAS and LAPACK. But it has a better performance and speed of calculations.

The functions accept two-dimensional array input and output is also a two-dimensional array.

from scipy import linalg
import numpy as np
 
a = np.array([ [5,7], [10,20] ])
 
# det() function
linalg.det(a )

Output

29.999999999999993

Similarly, we can calculate for inverse matrices, eigenvalues, and vectors. It consists of all basic and complex linear functions.

Discrete Fourier Transform

Scipy has a package for DFT,scipy.fftpack. We perform DFT for conversion of spatial data into frequency data. We also have functions for Fast Fourier Transform.

FFT is useful when working with multidimensional arrays.

The frequency transformation helps determine the signals and wavelengths.

from matplotlib import pyplot as plt
import numpy as np 
 
 
fre  = 2 
 
fre_samp = 10
t = np.linspace(0, 2, 2 * fre_samp, endpoint = False )
a = np.sin(fre  * 2 * np.pi * t)
figure, axis = plt.subplots()
axis.plot(t, a)
axis.set_xlabel ('Time (s)')
axis.set_ylabel ('Signal amplitude')
plt.show()

Output

Scipy Installation

Optimization and Fit in SciPy

For optimization in SciPy we have the scipy.optimize module. It is a really tool for optimizing the final outputs. It can be useful when we want to minimize curves, root and scalar values.

import matplotlib.pyplot as plt
from scipy import optimize
import numpy as np
 
def function(a):
       return   a*1 + 5 * np.sin(a)
plt.plot(a, function(a))
plt.show()
 
optimize.fmin_bfgs(function, 0) 

Output

Optimization and Fit in SciPy

Optimization terminated successfully.
Current function value: -6.671134
Iterations: 4
Function evaluations: 18
Gradient evaluations: 6
array([-1.77215427])

One of the most basic optimization algorithms in Python scipy tutorial is the Nelder Mead algorithm. It is one of the most basic method for minimization of function. We can select it using the method argument.

It has a drawback for gradient evaluations as it has a slow performance.

import numpy as np
from scipy.optimize import minimize
#define function f(x)
def f(x):   
    return (2*(1 + x[0])**2)
  
optimize.minimize(f, [2, 1], method="Nelder-Mead")

Output

final_simplex: (array([[-1. , 1.725 ],
[-1. , 1.72509766],
[-1. , 1.72501221]]), array([0., 0., 0.]))
fun: 0.0
message: ‘Optimization terminated successfully.’
nfev: 159
nit: 73
status: 0
success: True
x: array([-1. , 1.725])

Image Processing

SciPy consists of the scipy.ndimage module for image processing. It is a very useful package for processing n-dimensional images. It has various manipulation functions like filtering, rotate, crop, display, classification and feature extraction.

We can use the MISC package to access images and perform operations.

from scipy import misc
from matplotlib import pyplot as plt
import numpy as np
 
panda = misc.face()
#plot  image 
plt.imshow( panda )
plt.show()

Output

Image processing in SciPy

Summary

Finally, we come to the end of the Python SciPy tutorial. SciPy is a very important open-source package in Python. It is one of the most basic packages for carrying out python operations.

SciPy is easy to understand and consists of huge functionality. It is user-friendly while carrying out mathematical and scientific analysis. It has extended functionality because of its sub-packages.

TechVidvan Team

The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today’s tech industry.