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
| module | Main purpose | Recommendation |
|---|---|---|
scipy.stats | Statistical tests, correlations, probability distributions | core |
scipy.optimize | Fitting, optimization, root finding | core |
scipy.interpolate | Data interpolation, curve construction | core |
scipy.integrate | Numerical integration, differential equations | important |
scipy.linalg | Linear equations, matrix factorization | Commonly used |
scipy.signal | Smoothing, filtering, peak detection | on demand |
scipy.spatial | Distance calculation, nearby point search | on demand |
scipy.sparse | Efficiently store sparse matrices | on 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)
| method | Features |
|---|---|
| Pearson | linear correlation |
| Spearman | Rank-based monotonic correlation |
| Kendall | Rank 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:
| method | Purpose |
|---|---|
ttest_1samp | One-sample mean test |
ttest_ind | Comparison of two independent sample means |
ttest_rel | Paired sample mean comparison |
mannwhitneyu | Non-parametric test for two independent samples |
f_oneway | One-way analysis of variance ANOVA |
chi2_contingency | Categorical variable independence test |
shapiro | Normality test |
levene | Test 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,
)
| method | meaning |
|---|---|
pdf() | probability density |
pmf() | discrete probability mass |
cdf() | cumulative distribution function |
ppf() | Quantile function, inverse of CDF |
rvs() | random sampling |
sf() | Survival function, |
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:
Among them:
- : independent variable.
- : Observed value.
- : Parameters that need to be estimated.
- : Error.
The goal is to find parameters that minimize the difference between predicted and observed values.
Nonlinear curve fitting
For example, fitting exponential decay:
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:
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:
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:
where the residuals are usually:
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:
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:
| method | Features |
|---|---|
| BFGS | Smooth unconstrained optimization |
| L-BFGS-B | Support variable bounds |
| SLSQP | Support constraints |
| Nelder-Mead | No explicit gradient required |
| differential_evolution | global 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:
solution.
Single variable equation
For example:
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:
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
| method | Solve 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:
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:
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:
| API | Function |
|---|---|
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
| demand | Recommended method |
|---|---|
| Descriptive statistics | NumPy、Pandas、stats.describe |
| correlation test | stats.pearsonr、spearmanr |
| Hypothesis testing | stats.ttest_ind etc. |
| Probability distribution parameter estimation | stats.<distribution>.fit |
| Linear trend analysis | stats.linregress、np.polyfit |
| Nonlinear curve fitting | optimize.curve_fit |
| Robust fitting with outliers | optimize.least_squares |
| general optimization | optimize.minimize |
| Solve | optimize.root_scalar |
| nonlinear equations | optimize.root |
| One-dimensional interpolation | np.interp、CubicSpline、PchipInterpolator |
| Two-dimensional scatter interpolation | interpolate.griddata |
| function integral | integrate.quad |
| discrete curve integral | integrate.trapezoid、simpson |
| differential equations | integrate.solve_ivp |
| System of linear equations | linalg.solve |
| signal smoothing | signal.savgol_filter |
| nearest neighbor space search | spatial.cKDTree |
The difference between fitting, interpolation, optimization and root finding
These concepts deserve a clear distinction:
| Type | math goals | Typical uses |
|---|---|---|
| Fitting | Make the model as close as possible to the observed data | Experimental data fitting |
| Interpolation | Construct a function that passes through data points | Estimate the value between sampling points |
| Optimization | Find the optimal value of the objective function | Parameter and resource optimization |
| Root Finding | Find a solution that satisfies the equation | Solving 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:
| priority | API |
|---|---|
| core | stats.pearsonr、ttest_ind、norm |
| core | optimize.curve_fit |
| core | optimize.least_squares |
| core | optimize.minimize |
| core | optimize.root_scalar、root |
| important | interpolate.CubicSpline、PchipInterpolator |
| important | integrate.quad、trapezoid |
| Commonly used | linalg.solve、lstsq |
| on demand | signal.savgol_filter、find_peaks |
| on demand | spatial.cKDTree、cdist |
The most important concepts:
- Statistical Inference: Inferring overall characteristics from sample data requires attention to assumptions, confidence intervals, and uncertainties.
- Least Squares: Estimates model parameters by minimizing the sum of squared residuals and is the basis for a large number of curve fitting methods.
- Numerical Optimization: In cases where analytical solution may not be possible, a better solution is found through an iterative algorithm.
- Interpolation vs Fitting: Interpolation usually passes through the observation points, and fitting looks for the overall trend.
- Numerical Stability: Initial values, parameter scales, outliers and convergence conditions will all affect the solution results.