Python SciPy Tutorial

In this lesson, we will see what is the use of SciPy library in Python and how it helps us to work with mathematical equations and algorithms in an interactive manner. The good thing about SciPy Python package is that if we want classes or construct web pages, SciPy is fully compatible with the system as a whole and can provide seamless integration.

As SciPy is open source, it has a very active and vibrant community of developers due to which there are enormous number of modules present for a vast amount of scientific applications and calculations available with SciPy. Some of the complex mathematical operations which can be performed with SciPy are:

Interpolation

Integration

Optimization

Image processing

Statistics

Special function calculations etc.

SciPy can be compared to most command and standard libraries like GSL library for C++ and Matlab. As SciPy is built on top of NumPy package, these two packages can be integrated completely as well. If you can think of a mathematical operation which needs to be done, make sure you check SciPy library before you implement that module on your own because in most cases, SciPy have all the operations for you fully implemented already.

Install SciPy Library

Let’s install SciPy library before we move to the actual examples and concepts. There are two ways to install this package. First one includes using the Python package manager, pip:

pip install scipy

The second way relates to Anaconda, we can install the package as:

conda install -c anaconda scipy

Once the library is installed, we can import it as:

import scipy

Finally, as we will be using NumPy as well (It is recommended that for all NumPy operations, we use NumPy directly instead of going through the SciPy package):

import numpy

It is possible that in some cases, we will also like to plot our results for which we will use the Matplotlib library. Perform the following import for that library:

import matplotlib

I will be using the Anaconda manager for all the examples in this lesson. I will launch a Jupyter Notebook for the same:

Now that we are ready with all the import statements to write some code, let’s start diving into SciPy package with some practical examples.

Working with Polynomial Equations

We will start by looking at simple Polynomial equations. There are two ways with which we can integrate Polynomial functions into our program. We can make use of poly1d class which makes use of coefficients or the roots of a polynomial for initialising a polynomial. Let’s look at an example:

Clearly, the polynomial representation of the equation is printed as the output so that the result is pretty easy to understand. We can perform various operations on this polynomial as well, like square it, find its derivative or even solve it for a value of x. Let’s try doing all of these in the next example:

The integer we pass tells the package how many times to integrate the polynomial:

We can simply pass another integer which tells the package how many times to integrate this polynomial.

Solving Linear Equations

It is even possible to solve linear equations with SciPy and find their roots, if they exist. To solve linear equations, we represent the set of equations as NumPy arrays and their solution as a separate NumPy arrays. Let’s visualise it with an example where we do the same and make use of linalg package to find the roots of the equations, here are the equations we will be solving:

1x + 5y =6
3x + 7y =9

Let’s solve the above equations:

from scipy import linalg

equation = np.array([[1,5],[3,7]])
solution = np.array([[6],[9]])

roots = linalg.solve(equation, solution)

print("Found the roots:")print(roots)

print("\n Dot product should be zero if the solutions are correct:")print(equation.dot(roots) - solution)

When we run the above program, we will see that the dot product equation gives zero result, which means that the roots which the program found were correct:

Fourier Transformations with SciPy

Fourier Transformations helps us to express a function as separate components that make up that function and guides us about the way through which we can recombine those components to get the original function back.

Let’s look at a simple example of Fourier Transformations where we plot the sum of two cosines using the Matplotlib library:

Here, we started by constructing a sample space and cosine equation which we then transformed and plotted. Here is the output of the above program:

This is one of the good example where we see SciPy being used in a complex mathematical equation to visualise things easily.

Vectors and Matrix with SciPy

Now that we know a lot of things which SciPy is capable of, we can be sure that SciPy can also work with Vectors and Matrix. The matrices are an important part of linear algebra as matrices is something we use to represent Vector mappings as well.

Just like we looked at solving linear equations with SciPy, we can represent vectors with np.array() functions. Let’s start by constructing a matrix:

my_matrix = np.matrix(np.random.random((3,3)))print(my_matrix)

Here is the output of the above snippet:

Whenever we talk about matrices, we always talk about Eigenvalues and Eigenvectors. To put in simple words, Eigenvectors are the vectors which, when multiplied with a matrix, do not change their direction, as opposed to most of the vectors. This means that even when you multiply an Eigenvectors with a matrix, there exists a value (or eigenvalue) which is one of the factor of the multiplication. This means:

Ax = λx.

In above equation, A is the matrix, λ is the Eigenvalue and x is the Vector. Let’s write a simple code snippet to find the Eigenvalues for a given Vector:

la, vector = linalg.eig(my_matrix)

print(vector[:,0])print(vector[:,1])

print(linalg.eigvals(my_matrix))

When we run this example, we will see the following output:

Calculating Matrix Determinant

The next operation we will carry out with SciPy is to calculate the determinant of a 2-dimensional matrix. We will reuse the matrix we used in the last code snippet here:

linalg.det( my_matrix )

When we run this example, we will see the following output:

Conclusion

In this lesson, we looked at a lot of good examples where SciPy can help us by carrying out complex mathematical computations for us with an easy to use API and packages.

About the author

Shubham Aggarwal

I’m a Java EE Engineer with about 4 years of experience in building quality products. I have excellent problem-solving skills in Spring Boot, Hibernate ORM, AWS, Git, Python and I am an emerging Data Scientist.