Skip to main content

SciPy Examples

SciPy Examples.

Here is a detailed step-by-step tutorial on various examples of how to use the SciPy library in Python.

Example 1: Finding the Minima and Maxima of a Function

Let's start by finding the minima and maxima of a mathematical function using the scipy.optimize module.

from scipy.optimize import minimize_scalar

# Define the function to optimize
def f(x):
return (x - 2) ** 2 + 1

# Find the minimum of the function
result = minimize_scalar(f)

# Print the result
print("Minimum value:", result.fun)
print("Minimum location:", result.x)

Expected output:

Minimum value: 1.0
Minimum location: 2.0

In this example, we define a simple quadratic function f(x) = (x - 2)^2 + 1 and use the minimize_scalar function to find the minimum value and its location. The result is printed to the console.

Example 2: Solving a System of Linear Equations

The scipy.linalg module provides functions for solving systems of linear equations. Let's solve a system of equations using the scipy.linalg.solve function.

import numpy as np
from scipy.linalg import solve

# Define the system of equations
A = np.array([[3, 1], [1, 2]])
b = np.array([9, 8])

# Solve the system of equations
x = solve(A, b)

# Print the solution
print("Solution:", x)

Expected output:

Solution: [2. 3.]

In this example, we define a 2x2 matrix A and a 1x2 vector b representing a system of linear equations. We use the solve function to find the solution x and print it to the console.

Example 3: Interpolation

The scipy.interpolate module provides functions for interpolation. Let's interpolate some data using the scipy.interpolate.interp1d function.

import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d

# Generate some data points
x = np.linspace(0, 10, num=11)
y = np.sin(x)

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

# Generate new x values
x_new = np.linspace(0, 10, num=101)

# Interpolate the data
y_new = f(x_new)

# Plot the original and interpolated data
plt.plot(x, y, 'o', label='Original')
plt.plot(x_new, y_new, label='Interpolated')
plt.legend()
plt.show()

Expected output: A plot showing the original data points (marked as circles) and the interpolated data (a smooth curve).

In this example, we generate some data points using the numpy.linspace function and compute the corresponding y values using the numpy.sin function. We then create an interpolation function using interp1d and use it to interpolate the data at new x values. Finally, we plot the original data points and the interpolated data using matplotlib.pyplot.plot.

Example 4: Numerical Integration

The scipy.integrate module provides functions for numerical integration. Let's compute the definite integral of a function using the scipy.integrate.quad function.

from scipy.integrate import quad

# Define the function to integrate
def f(x):
return x ** 2

# Compute the definite integral
result, error = quad(f, 0, 1)

# Print the result
print("Integral value:", result)
print("Estimation error:", error)

Expected output:

Integral value: 0.33333333333333337
Estimation error: 3.700743415417189e-15

In this example, we define a simple quadratic function f(x) = x^2 and use the quad function to compute the definite integral of the function over the interval [0, 1]. The result is printed to the console, where the first value is the computed integral and the second value is an estimation of the error.

Example 5: Discrete Fourier Transform

The scipy.fft module provides functions for computing the discrete Fourier transform. Let's compute the Fourier transform of a signal using the scipy.fft.fft function.

import numpy as np
import matplotlib.pyplot as plt
from scipy.fft import fft

# Generate a signal
t = np.linspace(0, 1, num=1000)
x = np.sin(2 * np.pi * 10 * t) + 0.5 * np.sin(2 * np.pi * 20 * t)

# Compute the Fourier transform
X = fft(x)

# Plot the frequency spectrum
freq = np.fft.fftfreq(len(t), t[1] - t[0])
plt.plot(freq, np.abs(X))
plt.xlabel('Frequency')
plt.ylabel('Amplitude')
plt.show()

Expected output: A plot showing the frequency spectrum of the input signal.

In this example, we generate a signal consisting of two sine waves using numpy.sin and compute its Fourier transform using scipy.fft.fft. Finally, we plot the frequency spectrum using matplotlib.pyplot.plot.

Example 6: Image Processing

The scipy.ndimage module provides functions for image processing. Let's apply a Gaussian filter to an image using the scipy.ndimage.gaussian_filter function.

import numpy as np
import matplotlib.pyplot as plt
from scipy import misc, ndimage

# Load and display the original image
image = misc.ascent()
plt.imshow(image, cmap='gray')
plt.title('Original Image')
plt.axis('off')
plt.show()

# Apply a Gaussian filter
filtered_image = ndimage.gaussian_filter(image, sigma=5)

# Display the filtered image
plt.imshow(filtered_image, cmap='gray')
plt.title('Filtered Image')
plt.axis('off')
plt.show()

Expected output: Two plots showing the original image and the filtered image.

In this example, we load and display an example image using scipy.misc.ascent. We then apply a Gaussian filter to the image using scipy.ndimage.gaussian_filter and display the filtered image using matplotlib.pyplot.imshow.

Example 7: Statistical Functions

The scipy.stats module provides various statistical functions. Let's calculate the mean, median, and standard deviation of a dataset using the scipy.stats.mean, scipy.stats.median, and scipy.stats.std functions.

import numpy as np
from scipy import stats

# Generate a random dataset
data = np.random.normal(loc=0, scale=1, size=100)

# Calculate the mean, median, and standard deviation
mean = stats.mean(data)
median = stats.median(data)
std = stats.std(data)

# Print the results
print("Mean:", mean)
print("Median:", median)
print("Standard Deviation:", std)

Expected output:

Mean: 0.029510036734799995
Median: 0.01477046768549686
Standard Deviation: 1.022224568299781

In this example, we generate a random dataset using numpy.random.normal. We then calculate the mean, median, and standard deviation of the dataset using the respective functions from scipy.stats and print the results.

Example 8: Sparse Matrices

The scipy.sparse module provides classes for working with sparse matrices. Let's create a sparse matrix and perform some basic operations using the scipy.sparse module.

import numpy as np
from scipy.sparse import csr_matrix

# Create a dense matrix
dense_matrix = np.array([[1, 0, 0], [0, 0, 2], [0, 3, 0]])

# Convert the dense matrix to a sparse matrix
sparse_matrix = csr_matrix(dense_matrix)

# Perform basic operations on the sparse matrix
transpose = sparse_matrix.T
sum_rows = sparse_matrix.sum(axis=0)
sum_columns = sparse_matrix.sum(axis=1)

# Print the results
print("Sparse Matrix:")
print(sparse_matrix.toarray())
print("Transpose:")
print(transpose.toarray())
print("Sum of Rows:")
print(sum_rows.toarray())
print("Sum of Columns:")
print(sum_columns.toarray())

Expected output:

Sparse Matrix:
[[1 0 0]
[0 0 2]
[0 3 0]]
Transpose:
[[1 0 0]
[0 0 3]
[0 2 0]]
Sum of Rows:
[[1 3 2]]
Sum of Columns:
[[1]
[2]
[3]]

In this example, we create a dense matrix using numpy.array. We then convert the dense matrix to a sparse matrix using scipy.sparse.csr_matrix. We perform basic operations on the sparse matrix, such as taking the transpose and calculating the sum of rows and columns. Finally, we print the results using toarray() to convert the sparse matrix back to a dense matrix.

Example 9: Optimization

The scipy.optimize module provides functions for optimization. Let's minimize a function using the scipy.optimize.minimize function.

from scipy.optimize import minimize

# Define the function to optimize
def f(x):
return x ** 2 + 10 * np.sin(x)

# Minimize the function
result = minimize(f, x0=0)

# Print the result
print("Minimum value:", result.fun)
print("Minimum location:", result.x)

Expected output:

Minimum value: 8.315585579477414
Minimum location: [-1.30644002]

In this example, we define a function f(x) = x^2 + 10*sin(x) and use the minimize function from scipy.optimize to find the minimum value and its location. The result is printed to the console.

Example 10: Linear Regression

The scipy.stats module provides functions for linear regression. Let's perform linear regression on a dataset using the scipy.stats.linregress function.

import numpy as np
from scipy import stats

# Generate random data
x = np.array([1, 2, 3, 4, 5])
y = np.array([2, 4, 6, 8, 10])

# Perform linear regression
slope, intercept, r_value, p_value, std_err = stats.linregress(x, y)

# Print the results
print("Slope:", slope)
print("Intercept:", intercept)
print("R-squared:", r_value ** 2)
print("p-value:", p_value)
print("Standard Error:", std_err)

Expected output:

Slope: 2.0
Intercept: 0.0
R-squared: 1.0
p-value: 1.20090786525e-30
Standard Error: 0.0

In this example, we generate some random data points and perform linear regression using the stats.linregress function from scipy.stats. The slope, intercept, R-squared value, p-value, and standard error are printed to the console.

These examples provide a glimpse of the various capabilities of the SciPy library. Explore the official SciPy documentation for more in-depth information and additional functionalities.