SciPy Cheatsheet



The SciPy cheatsheet provides the quick reference to all its fundamental topics. This is free open−source library that used for various tasks such as signal processing, statistics, linear algebra, and data analysis. Go through this cheat sheet and learn the SciPy library of Python.

Table of Content

1. Introduction to SciPy

In the introduction section, we will cover the basic definition, installation and learn how to import the SciPy.

i. What is SciPy?

The SciPy is an open-source library of Python that can be used for scientific and technical computing.

ii. Installation

To install the SciPy library of Python, use the following command −

pip install scipy

iii. Importing SciPy

To import the SciPy, use the following lines of code −

import scipy
import numpy as np

2. Special Functions (scipy.special)

The scipy.special module provides a collection of mathematical functions such as gamma functions, beta functions, and error functions.

i. Common Special Functions

The common special function are mostly used in statistics, physics and engineering applications.

from scipy import special

# Gamma function
print(special.gamma(5))  

# Beta function
print(special.beta(2, 3)) 

# Error function 
print(special.erf(1.0))  

ii. Bessel Functions

In SciPy, Bessel functions are reference through scipy.special that calculate the specific order and argument.

# Bessel function of the first kind
from scipy import special
print(special.jn(1, 2.5))  

3. Linear Algebra (scipy.linalg)

The scipy.linalg module provides functions for matrix operations such as solving linear equations, and computing determinants.

i. Solving Linear Equations

To solve the linear equation in SciPy, use the solve function.

from scipy.linalg import solve
import numpy as np
A = np.array([[3, 1], [1, 2]])
b = np.array([9, 8])
x = solve(A, b)
print(x)

ii. Matrix Operations

In SciPy, matrix operations can be implemented as 2D list or 2D array. You can perform various operations in matrices such as addition, subtraction, transpose, and inversion of a matrix.

from scipy.linalg import inv
import numpy as np
matrix = np.array([[1, 2], [3, 4]])

# Inverse of a matrix
print(inv(matrix))  

4. Optimization (scipy.optimize)

The scipy.optimize module is used for finding the minimum, maximum, and roots of functions.

i. Minimization of a Function

Minimizing a function is useful in machine learning and mathematical modeling.

from scipy.optimize import minimize

def func(x):
    return x**2 + 5*x + 6

result = minimize(func, x0=0)

# Minimum value
print(result.x)  

ii. Finding Roots of Equations

In SciPy, finding the roots methods helps to locate zeros.

from scipy.optimize import root

def equation(x):
    return x**2 - 4

sol = root(equation, x0=0)
print(sol.x)  # Root of the equation

iii. Curve Fitting (curve_fit)

Curve fitting is used to approximate data using a given function.

from scipy.optimize import curve_fit
import numpy as np
def func(x, a, b):
    return a * x + b

x_data = np.array([1, 2, 3, 4, 5])
y_data = np.array([2, 4, 6, 8, 10])
params, _ = curve_fit(func, x_data, y_data)

# Fitted parameters
print(params) 

5. Integration (scipy.integrate)

The SciPy integration are defined using numerical methods for calculating definite integrals which contains single, double and triple integrals as well as differential equations.

i. Definite and Indefinite Integrals (quad, dblquad)

The quad function measures the definite integral of a function over a given range, while dblquad is used for double integrals.

from scipy.integrate import quad, dblquad

# Single integral
result, error = quad(lambda x: x**2, 0, 2)
print(result)  

# Double integral
double_result, error = dblquad(lambda y, x: x * y, 0, 1, lambda x: 0, lambda x: 2)
print(double_result)  

ii. Solving Ordinary Differential Equations (odeint, solve_ivp)

The odeint and solve_ivp functions are used to solve ordinary differential equations (ODEs).

from scipy.integrate import odeint, solve_ivp
import numpy as np

# Define the function dy/dt = -2y
def model(y, t):
    return -2 * y

t = np.linspace(0, 5, 100)  # Time points
y0 = 1  # Initial condition

# ODE using odeint
y = odeint(model, y0, t)

# Print first few values
print(y[:5]) 

# ODE using solve_ivp
solution = solve_ivp(model, [0, 5], [y0], t_eval=t)

# Print first some values
print(solution.y[0][:5])  

6. Interpolation (scipy.interpolate)

The interpolation calculates the value between two known values.

i. 1D Interpolation (interp1d)

The interp1d function is used for interpolating 1D data.

from scipy.interpolate import interp1d
import numpy as np

# data points
x = np.array([0, 1, 2, 3, 4])
y = np.array([0, 2, 4, 6, 8])

# Create an interpolation function
f = interp1d(x, y, kind='linear')

# Interpolated value at x = 2.5
print(f(2.5))  

ii. 2D and Multivariate Interpolation

The griddata function is used for interpolating 2D and multivariate data.

from scipy.interpolate import griddata
import numpy as np
# data points
points = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
values = np.array([1, 2, 3, 4])

# query point for interpolation
query_point = np.array([[0.5, 0.5]])

# interpolation
result = griddata(points, values, query_point, method='cubic')

# Interpolated value at (0.5, 0.5)
print(result)  

7. Statistics (scipy.stats)

The scipy.stats module provides statistical functions, including mean, variance, and hypothesis testing.

ii. Descriptive Statistics (Mean, Median, Variance)

You can compute mean, median, and variance using SciPy.

# mean
mean_value = stats.tmean(data)	

# median 
median_value = stats.tmedian(data) 

# variance
variance_value = stats.tvar(data) 

iii. Hypothesis Testing (t-test, chi-square test)

The hypothetical testing determine the statistical method to test about a population parameter using sample data.

from scipy.stats import ttest_1samp, chi2_contingency
import numpy as np
data = np.array([1, 2, 3, 4, 5, 6])
t_stat, p_value = ttest_1samp(data, popmean=3.5)
print("T-test p-value:", p_value)

8. Fast Fourier Transform (FFT) (scipy.fft)

The Fast Fourier Transform (FFT) is an efficient method for calculating the Discrete Fourier Transform (DFT) of a signal and its inverse.

i. 1D and 2D Fourier Transforms

The Fast Fourier Transform (FFT) is an algorithm to operates the discrete Fourier transform (DFT) and its inverse. The 1D FFT is used for 1−dimensional data, and the 2D FFT is applied to two−dimensional data such as images.

from scipy.fft import fft, fft2
import numpy as np

# 1D Fourier Transform
x = np.array([0, 1, 2, 3, 4, 5, 6, 7])
fft_result_1d = fft(x)

print("1D FFT result:\n", fft_result_1d)

# 2D Fourier Transform
x_2d = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]])
fft_result_2d = fft2(x_2d)

print("2D FFT result:\n", fft_result_2d)

ii. Inverse Fourier Transform

In SciPy, inverse FFT transforms the frequency−domain data back to the time or spatial domain.

import numpy as np
from scipy.fft import fft, ifft, fft2, ifft2

# 1D array
data_1d = np.array([1, 2, 3, 4])

# Fourier Transform
fft_result_1d = fft(data_1d)

# Inverse Fourier Transform
ifft_result_1d = ifft(fft_result_1d)
print("1D Inverse FFT result:\n", ifft_result_1d)

# 2D array
data_2d = np.array([[1, 2], [3, 4]])

# 2D Fourier Transform
fft_result_2d = fft2(data_2d)

# 2D Inverse Fourier Transform
ifft_result_2d = ifft2(fft_result_2d)
print("2D Inverse FFT result:\n", ifft_result_2d)

9. Signal Processing (scipy.signal)

In SciPy, signal processing is a part of python library that provides the tools like filtering, Fourier transform and wavelets.

i. Filtering (Low-pass, High-pass)

In SciPy, filtering helps in removing unwanted noise or frequencies from a signal.

from scipy.signal import butter, filtfilt
import numpy as np

# create a low-pass filter
def butter_lowpass(cutoff, fs, order=5):
    nyquist = 0.5 * fs
    normal_cutoff = cutoff / nyquist
    b, a = butter(order, normal_cutoff, btype='low', analog=False)
    return b, a

# sample signal
fs = 100  
signal = np.sin(2 * np.pi * 5 * np.linspace(0, 1, fs)) 

# apply filter
# 10 Hz cutoff frequency
b, a = butter_lowpass(10, fs)  
filtered_signal = filtfilt(b, a, signal)

ii. Convolution and Correlation

In SciPy, convolution and correlation are used for signal processing operations such as filtering and feature detection.

from scipy.signal import convolve, correlate
import numpy as np
x = np.array([1, 2, 3])
h = np.array([0, 1, 0.5])

conv_result = convolve(x, h, mode='full')
corr_result = correlate(x, h, mode='full')

# Convolution result
print(conv_result)
# Correlation result  
print(corr_result)  

iii. Peak Detection

Peak detection is used to find local maxima from the signal.

from scipy.signal import find_peaks
import numpy as np
signal = np.array([0, 1, 0, 2, 1, 3, 1, 0])
peaks, _ = find_peaks(signal, height=1)

# Indices of peaks
print(peaks)  

10. Image Processing (scipy.ndimage)

Image Processing in SciPy defines the signals in the form of pixel data. This is also known as image analysis.

i. Image Filtering (Gaussian, Median)

SciPy provides various image filters such as Gaussian and Median filters for the smooth images.

from scipy.ndimage import gaussian_filter, median_filter
import numpy as np
image = np.random.random((5, 5))

gaussian_filtered = gaussian_filter(image, sigma=1)
median_filtered = median_filter(image, size=2)

# Gaussian filtered image
print(gaussian_filtered)

# Median filtered image  
print(median_filtered)  

ii. Morphological Operations

Morphological operations are used for image processing tasks such as edge detection and noise removal.

from scipy.ndimage import binary_dilation, binary_erosion
import numpy as np

binary_image = np.random.randint(0, 2, (5, 5))

dilated_image = binary_dilation(binary_image)
eroded_image = binary_erosion(binary_image)

print(dilated_image)  # Dilated image
print(eroded_image)  # Eroded image

11. Sparse Matrices (scipy.sparse)

A sparse matrices are the matrix by containing most zero elements.

i. Creating Sparse Matrices

Sparse matrices store only nonzero elements to save memory.

from scipy.sparse import csr_matrix
import numpy as np
dense_matrix = np.array([[0, 0, 1], [1, 0, 0], [0, 2, 0]])
sparse_matrix = csr_matrix(dense_matrix)

print(sparse_matrix)

ii. Sparse Matrix Operations

This is like a matrix multiplication and the conversion can be performed on sparse matrices.

# Transpose
sparse_matrix_T = sparse_matrix.transpose()  

# Matrix multiplication
sparse_matrix_dot = sparse_matrix.dot(sparse_matrix_T)  
print(sparse_matrix_dot)

12. File I/O (scipy.io)

Reading / Writing MATLAB Files

MATLAB files (.mat) can be used to read and write files using SciPy.

from scipy.io import savemat, loadmat
import numpy as np
data = {'array': np.array([1, 2, 3])}
# Save to MATLAB file
savemat("data.mat", data)  

# Load MATLAB file
loaded_data = loadmat("data.mat")  
print(loaded_data)

ii. Reading / Writing WAV Files

SciPy provides functions to read and write audio files in WAV format.

from scipy.io import wavfile
import numpy as np
# Writing a WAV file
fs = 44100
wavfile.write("output.wav", fs, np.random.randint(-32768, 32767, 44100, dtype=np.int16))

# Reading a WAV file
rate, data = wavfile.read("output.wav")
print(rate, data.shape)
Advertisements