SciPy Tutorial
SciPy is built on NumPy and adds scientific algorithms — optimisation, integration, statistics, linear algebra, signal processing, sparse matrices.
Install
SHELL
pip install scipy
The submodules you'll meet
| Module | What it does |
|---|---|
scipy.stats | Distributions, hypothesis tests, descriptive statistics. |
scipy.optimize | Root finding, minimisation, curve fitting. |
scipy.integrate | Numerical integration, ODE solvers. |
scipy.linalg | Linear algebra beyond NumPy's basics. |
scipy.signal | FFT, filters, spectrograms. |
scipy.sparse | Sparse matrices for huge graphs / NLP / collaborative filtering. |
scipy.spatial | k-d trees, distance metrics, geometry. |
scipy.interpolate | Spline fitting and interpolation. |
Statistics quickstart
PYTHON
from scipy import stats
# Probability that a standard normal is < 1.96
print(stats.norm.cdf(1.96)) # ~0.975
# Random samples from a normal distribution
samples = stats.norm(loc=0, scale=1).rvs(size=1000)
# t-test between two samples
t, p = stats.ttest_ind(samples, stats.norm(0.5).rvs(1000))
print('t', t, 'p', p)
Optimisation
PYTHON
from scipy.optimize import minimize
def f(x):
return (x[0] - 3) ** 2 + (x[1] + 1) ** 2
result = minimize(f, x0=[0, 0])
print(result.x) # ≈ [3, -1]
Tip: SciPy is a layer above NumPy. If a function is purely about array math, look in NumPy first; if it's about an algorithm with a name, look in SciPy.
Example
Example
# from scipy import stats
# print(stats.norm.cdf(1.96))
print('SciPy adds optimisation, statistics, signal processing on top of NumPy.')
Try it Yourself »
Exercise
SciPy submodule containing distributions and tests.
from scipy import
Five letters.
Discussion
Loading…