SciPy: Scientific Computing, Data Fitting, and Numerical Solving

1. SciPy core module

SciPy
├── stats          Statistical analysis, probability distribution, hypothesis testing
├── optimize       Curve fitting, optimization, equation root finding
├── interpolate    Interpolation, splines
├── integrate      Numerical integration, differential equations
├── linalg         linear algebra
├── signal         signal processing, filtering
├── spatial        Distance calculation, spatial search
└── sparse         sparse matrix
moduleMain purposeRecommendation
scipy.statsStatistical tests, correlations, probability distributionscore
scipy.optimizeFitting, optimization, root findingcore
scipy.interpolateData interpolation, curve constructioncore
scipy.integrateNumerical integration, differential equationsimportant
scipy.linalgLinear equations, matrix factorizationCommonly used
scipy.signalSmoothing, filtering, peak detectionon demand
scipy.spatialDistance calculation, nearby point searchon demand
scipy.sparseEfficiently store sparse matriceson demand

Basic import:

import numpy as np
from scipy import stats, optimize, interpolate, integrate

2. scipy.stats: Statistical analysis

scipy.stats provides functions such as statistical testing, correlation analysis, probability distribution and statistical estimation.

Descriptive statistics

from scipy import stats

x = np.array([10, 12, 15, 18, 20, 21, 25])

stats.describe(x)
stats.skew(x)      # Skewness
stats.kurtosis(x)  # excess kurtosis
  • Skewness: Measures the degree of asymmetry of the distribution.
  • Kurtosis: measures tail characteristics, SciPy returns excess kurtosis by default.

Generally, NumPy can be used for mean, standard deviation and quantile.

correlation analysis

x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 4, 7]

stats.pearsonr(x, y)
stats.spearmanr(x, y)
stats.kendalltau(x, y)
methodFeatures
Pearsonlinear correlation
SpearmanRank-based monotonic correlation
KendallRank correlation based on sample pair consistency

For example:

result = stats.pearsonr(x, y)

result.statistic  # Correlation coefficient
result.pvalue     # p-value

Note: Correlation does not mean causation.

Hypothesis testing

Common tests:

methodPurpose
ttest_1sampOne-sample mean test
ttest_indComparison of two independent sample means
ttest_relPaired sample mean comparison
mannwhitneyuNon-parametric test for two independent samples
f_onewayOne-way analysis of variance ANOVA
chi2_contingencyCategorical variable independence test
shapiroNormality test
leveneTest for homogeneity of variances

For example, compare two sets of samples:

group_a = [10, 12, 11, 13, 12]
group_b = [14, 15, 13, 16, 14]

result = stats.ttest_ind(
    group_a,
    group_b,
    equal_var=False,
)

print(result.statistic)
print(result.pvalue)

equal_var=False Using Welch's t-test does not require that the two groups have the same population variance.

p-value represents: the probability of obtaining the current or more extreme statistical results when the null hypothesis and the test hypothesis are established.

It is not the probability that the null hypothesis is true, nor does it directly reflect the actual effect size.

When choosing a test method, you need to consider whether the samples are independent, distribution assumptions, and data type.

probability distribution

SciPy provides a large number of continuous and discrete probability distributions.

For example, normal distribution:

from scipy.stats import norm

norm.pdf(0, loc=0, scale=1)
norm.cdf(1.96)
norm.ppf(0.975)

samples = norm.rvs(
    loc=0,
    scale=1,
    size=1000,
    random_state=42,
)
methodmeaning
pdf()probability density
pmf()discrete probability mass
cdf()cumulative distribution function
ppf()Quantile function, inverse of CDF
rvs()random sampling
sf()Survival function, 1−CDF1-CDF

Distribution fitting

Assuming that the data approximately follows a normal distribution, its parameters can be estimated:

data = np.array([10, 12, 13, 15, 18, 20])

mu, sigma = stats.norm.fit(data)

fit() performs parameter estimation based on a specified distribution; obtaining the parameters does not mean that the data has been proven to fit the distribution.

Bootstrap confidence interval

Bootstrap Uncertainty in estimating a statistic by repeatedly sampling the sample with replacement.

data = np.array([10, 12, 15, 18, 20, 25])

result = stats.bootstrap(
    (data,),
    np.mean,
    n_resamples=5000,
    confidence_level=0.95,
    rng=np.random.default_rng(42),
)

print(result.confidence_interval)

This is a very practical resampling method in statistical analysis.

3. scipy.optimize.curve_fit: Curve fitting

Curve fitting (Curve Fitting) is a very important function of SciPy in actual data analysis.

Suppose there is a set of observation data:

y=f(x;θ)+ϵy=f(x;\theta)+\epsilon

Among them:

  • xx: independent variable.
  • yy: Observed value.
  • θ\theta: Parameters that need to be estimated.
  • ϵ\epsilon: Error.

The goal is to find parameters that minimize the difference between predicted and observed values.

Nonlinear curve fitting

For example, fitting exponential decay:

y=ae−bx+cy=a e^{-bx}+c
from scipy.optimize import curve_fit

x = np.linspace(0, 5, 30)

rng = np.random.default_rng(42)

y = (
    3 * np.exp(-0.8 * x)
    + 0.5
    + rng.normal(0, 0.1, size=x.size)
)

def model(x, a, b, c):
    return a * np.exp(-b * x) + c

popt, pcov = curve_fit(
    model,
    x,
    y,
    p0=[2, 1, 0],
)

a, b, c = popt

y_pred = model(x, *popt)

Return:

  • popt: Parameters obtained by fitting.
  • pcov: Approximate estimate of parameter covariance.

Parameter standard error:

perr = np.sqrt(np.diag(pcov))

It should be noted that pcov is based on local linear approximation and error model assumptions, and may not be able to reliably describe the parameter uncertainty of all nonlinear models.

parameter bounds

If parameters must satisfy business constraints:

popt, pcov = curve_fit(
    model,
    x,
    y,
    p0=[2, 1, 0],
    bounds=(
        [0, 0, -np.inf],
        [np.inf, np.inf, np.inf],
    ),
)

Here are the restrictions:

a≥0,b≥0a\geq0,\qquad b\geq0

weighted fit

Different observations may have different measurement errors.

sigma = np.full_like(y, 0.1)

popt, pcov = curve_fit(
    model,
    x,
    y,
    sigma=sigma,
    absolute_sigma=True,
)

When sigma is a one-dimensional array, the fit is usually minimized:

∑i(yi−f(xi;θ)σi)2\sum_i \left(\frac{y_i-f(x_i;\theta)}{\sigma_i}\right)^2

If the standard deviation of the measurement for each observation is known, you can use a weighted fit.

curve_fit is essentially a nonlinear least squares fit that usually looks for a local optimal solution, so the initial parameters p0 may affect the results.

4. least_squares, minimize: numerical optimization

least_squares

least_squares() is more general than curve_fit() and directly optimizes a residual vector.

Goal:

min⁡_θ12∑iri(θ)2\min\_\theta \frac{1}{2}\sum_i r_i(\theta)^2

where the residuals are usually:

ri(θ)=f(xi;θ)−yir_i(\theta)=f(x_i;\theta)-y_i

Example:

from scipy.optimize import least_squares

def residuals(params, x, y):
    a, b, c = params
    predicted = a * np.exp(-b * x) + c
    return predicted - y

result = least_squares(
    residuals,
    x0=[2, 1, 0],
    args=(x, y),
    bounds=(
        [0, 0, -np.inf],
        [np.inf, np.inf, np.inf],
    ),
    loss="soft_l1",
)

print(result.x)
print(result.success)

Here loss="soft_l1" is Robust Loss, which is used to reduce the impact of abnormal residuals on the fitting results.

Common Loss:

  • linear: ordinary least squares.
  • soft_l1: Smooth robust loss.
  • huber:Huber Loss。
  • cauchy: Further reduce the weight for large abnormal residuals.

Compared with curve_fit(), least_squares() is more suitable for custom residuals and robust fitting.

minimize

minimize() can be used when the objective is not least squares but an arbitrary objective function.

For example:

min⁡_x,y(x−2)2+(y+3)2\min\_{x,y}(x-2)^2+(y+3)^2
from scipy.optimize import minimize

def objective(params):
    x, y = params
    return (x - 2)**2 + (y + 3)**2

result = minimize(
    objective,
    x0=[0, 0],
    method="BFGS",
)

print(result.x)
print(result.fun)
print(result.success)

Common methods:

methodFeatures
BFGSSmooth unconstrained optimization
L-BFGS-BSupport variable bounds
SLSQPSupport constraints
Nelder-MeadNo explicit gradient required
differential_evolutionglobal heuristic search

When there are variable boundaries:

result = minimize(
    objective,
    x0=[0, 0],
    bounds=[(0, 5), (-5, 0)],
    method="L-BFGS-B",
)

minimize() usually looks for a local optimal solution; success=True does not mean that the result has been proven to be globally optimal.

5. root, root_scalar: Equation solving

Optimization problems look for the minimum value of the objective function, while equation solvers look for:

f(x)=0f(x)=0

solution.

Single variable equation

For example:

x2−2=0x^2-2=0
from scipy.optimize import root_scalar

result = root_scalar(
    lambda x: x**2 - 2,
    bracket=[1, 2],
    method="brentq",
)

print(result.root)
print(result.converged)

brentq is one of the robust root finding methods in one-dimensional rooted intervals.

Multivariable equations

For example:

{x2+y2=5x−y=1\begin{cases} x^2+y^2=5\\ x-y=1 \end{cases}
from scipy.optimize import root

def equations(vars):
    x, y = vars
    return [
        x**2 + y**2 - 5,
        x - y - 1,
    ]

result = root(
    equations,
    x0=[2, 1],
)

print(result.x)
print(result.success)

The obtained results should be re-substituted into the equation to check whether the residuals are small enough.

Difference from minimize

methodSolve the goal
root_scalar()Roots of a Single Variable Equation
root()Multivariable nonlinear equations
minimize()Minimum value of scalar objective function
least_squares()Minimum sum of squares of residuals

For observation data fitting, priority is given to curve_fit() / least_squares(); for root finding of mathematical equations, it is more direct to use the root() series.

6. scipy.interpolate: interpolation

Interpolation and Curve Fitting need to be distinguished.

  • Interpolation: Usually requires the interpolation curve to pass through the given data points.
  • Curve Fitting: A model that looks for approximate data trends and does not require passing through all observation points.

linear interpolation

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

x_new = np.array([0.5, 1.5, 2.5])

y_new = np.interp(x_new, x, y)

Simple one-dimensional linear interpolation can be done directly using NumPy.

CubicSpline

Cubic spline interpolation:

from scipy.interpolate import CubicSpline

x = np.array([0, 1, 2, 3, 4])
y = np.array([0, 1, 0, 2, 1])

spline = CubicSpline(x, y)

x_new = np.linspace(0, 4, 100)
y_new = spline(x_new)

CubicSpline can construct piecewise cubic polynomials with continuous first and second derivatives.

PchipInterpolator

If you want to reduce overshoot, consider PCHIP:

from scipy.interpolate import PchipInterpolator

f = PchipInterpolator(x, y)

y_new = f(x_new)

PCHIP has the characteristics of maintaining local monotonicity and avoiding certain overshoots.

Two-dimensional scatter interpolation

from scipy.interpolate import griddata

points = np.array([
    [0, 0],
    [1, 0],
    [0, 1],
    [1, 1],
])

values = np.array([1, 2, 3, 4])

result = griddata(
    points,
    values,
    xi=np.array([[0.5, 0.5]]),
    method="linear",
)

Suitable for interpolation of spatial observations, geographical data and irregular sampling points.

SciPy officially lists interp1d as Legacy API, and new codes usually recommend more specific implementations of CubicSpline, PchipInterpolator, etc.

7. scipy.integrate: Numerical integration and differential equations

quad: function integral

Calculation:

∫01x2 dx\int_0^1 x^2\,dx
from scipy.integrate import quad

value, error = quad(
    lambda x: x**2,
    0,
    1,
)

print(value)  # About 0.3333
print(error)  # absolute error of estimate

quad() is suitable for numerical integration of known mathematical functions.

trapezoid/simpson: Discrete data integration

If there is already a sampling point:

from scipy.integrate import trapezoid, simpson

x = np.linspace(0, 10, 101)
y = x**2

area1 = trapezoid(y, x=x)
area2 = simpson(y, x=x)

Common uses:

  • The velocity data is integrated to obtain the displacement.
  • The flow is integrated to get the total.
  • Calculate the area under the curve based on the observed data.

solve_ivp: differential equation

For example:

dydt=−0.5y,y(0)=10\frac{dy}{dt}=-0.5y,\qquad y(0)=10
from scipy.integrate import solve_ivp

def dydt(t, y):
    return -0.5 * y

t_eval = np.linspace(0, 10, 100)

result = solve_ivp(
    dydt,
    t_span=(0, 10),
    y0=[10],
    t_eval=t_eval,
)

print(result.t)
print(result.y[0])

Common methods:

  • RK45: Default method, suitable for many non-rigid problems.
  • DOP853: High-precision non-rigid problem.
  • Radau/BDF: suitable for certain rigid differential equations.

If you only do general data analysis, you only need to master quad(), trapezoid() and simpson(); differential equation solving can be learned on demand.

8. scipy.linalg: Linear algebra

Both SciPy and NumPy provide linear algebra functionality.

Common SciPy API:

from scipy import linalg

A = np.array([
    [3.0, 1.0],
    [1.0, 2.0],
])

b = np.array([9.0, 8.0])

x = linalg.solve(A, b)

Other common methods:

APIFunction
linalg.solve()System of linear equations
linalg.lstsq()linear least squares
linalg.eigh()Symmetric / Hermitian matrix eigenvalues
linalg.svd()singular value decomposition
linalg.cholesky()Cholesky decomposition
linalg.lu()LU decomposition

For ordinary matrix calculations, numpy.linalg is usually sufficient.

If you need richer decomposition algorithms, matrix types, or advanced solving capabilities, use scipy.linalg instead.

9. scipy.signal and scipy.spatial

These two modules are very useful in certain types of data analysis.

signal: Signal processing

For example smoothing a noisy sequence:

from scipy.signal import savgol_filter

x = np.linspace(0, 10, 101)

rng = np.random.default_rng(42)
y = np.sin(x) + rng.normal(0, 0.2, len(x))

y_smooth = savgol_filter(
    y,
    window_length=11,
    polyorder=3,
)

Savitzky-Golay Filter is smoothed by local polynomial fitting.

Suitable for measurement sequences, sensor data, etc.

Peak detection:

from scipy.signal import find_peaks

peaks, properties = find_peaks(
    y_smooth,
    prominence=0.5,
)

spatial: spatial distance

Calculate the distance between two sets of vectors:

from scipy.spatial.distance import cdist

a = np.array([[0, 0], [1, 1]])
b = np.array([[2, 2], [3, 3]])

distances = cdist(a, b, metric="euclidean")

For nearest neighbor queries for a large number of spatial points, you can use cKDTree:

from scipy.spatial import cKDTree

points = np.array([
    [0, 0],
    [1, 1],
    [2, 2],
])

tree = cKDTree(points)

distance, index = tree.query([0.8, 0.9])

cKDTree is suitable for nearby point search in low-dimensional Euclidean space. Longitude and latitude data cannot directly treat angles as metric distances. Appropriate geographical distances or coordinate projections should first be considered.

10. How to choose commonly used algorithms

demandRecommended method
Descriptive statisticsNumPy、Pandas、stats.describe
correlation teststats.pearsonr、spearmanr
Hypothesis testingstats.ttest_ind etc.
Probability distribution parameter estimationstats.<distribution>.fit
Linear trend analysisstats.linregress、np.polyfit
Nonlinear curve fittingoptimize.curve_fit
Robust fitting with outliersoptimize.least_squares
general optimizationoptimize.minimize
Solve f(x)=0f(x)=0optimize.root_scalar
nonlinear equationsoptimize.root
One-dimensional interpolationnp.interp、CubicSpline、PchipInterpolator
Two-dimensional scatter interpolationinterpolate.griddata
function integralintegrate.quad
discrete curve integralintegrate.trapezoid、simpson
differential equationsintegrate.solve_ivp
System of linear equationslinalg.solve
signal smoothingsignal.savgol_filter
nearest neighbor space searchspatial.cKDTree

The difference between fitting, interpolation, optimization and root finding

These concepts deserve a clear distinction:

Typemath goalsTypical uses
FittingMake the model as close as possible to the observed dataExperimental data fitting
InterpolationConstruct a function that passes through data pointsEstimate the value between sampling points
OptimizationFind the optimal value of the objective functionParameter and resource optimization
Root FindingFind a solution that satisfies the equationSolving Mathematical Equations

curve_fit itself also uses numerical optimization algorithms, but provides a more convenient fitting interface.

11. Important Notes on Numerical Calculations

initial value

Nonlinear fitting and optimization are often sensitive to initial parameters.

curve_fit(model, x, y, p0=[2, 1, 0])

Different p0 may cause the algorithm to converge to different local solutions.

Convergence and residuals

Just because the solver returns success does not mean that the results are necessarily reasonable in business terms.

result.success
result.message
result.fun

Also check:

  • Residual size.
  • Parameter range.
  • Prediction curve.
  • Sensitivity to outliers.
  • Whether it makes business or physical sense.

numerical scale

If the order of magnitude difference of parameters is too large, it may affect the stability of the optimization algorithm.

For example:

Parameter A ≈ 0.000001
Parameter B ≈ 1000000

This can be improved through parameter scaling, normalization, or solver-specific configuration.

NaN / Inf

Many numerical solvers require inputs to be finite floating point numbers.

np.isfinite(x).all()
np.isfinite(y).all()

Before actual fitting, missing values and abnormal data should be cleaned up, and the units should be confirmed to be consistent.


Summary

For data analysis, fitting and solving, SciPy is the most worth mastering API:

priorityAPI
corestats.pearsonr、ttest_ind、norm
coreoptimize.curve_fit
coreoptimize.least_squares
coreoptimize.minimize
coreoptimize.root_scalar、root
importantinterpolate.CubicSpline、PchipInterpolator
importantintegrate.quad、trapezoid
Commonly usedlinalg.solve、lstsq
on demandsignal.savgol_filter、find_peaks
on demandspatial.cKDTree、cdist

The most important concepts:

  1. Statistical Inference: Inferring overall characteristics from sample data requires attention to assumptions, confidence intervals, and uncertainties.
  2. Least Squares: Estimates model parameters by minimizing the sum of squared residuals and is the basis for a large number of curve fitting methods.
  3. Numerical Optimization: In cases where analytical solution may not be possible, a better solution is found through an iterative algorithm.
  4. Interpolation vs Fitting: Interpolation usually passes through the observation points, and fitting looks for the overall trend.
  5. Numerical Stability: Initial values, parameter scales, outliers and convergence conditions will all affect the solution results.

Reference documentation

Back to top