iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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

ModuleWhat it does
scipy.statsDistributions, hypothesis tests, descriptive statistics.
scipy.optimizeRoot finding, minimisation, curve fitting.
scipy.integrateNumerical integration, ODE solvers.
scipy.linalgLinear algebra beyond NumPy's basics.
scipy.signalFFT, filters, spectrograms.
scipy.sparseSparse matrices for huge graphs / NLP / collaborative filtering.
scipy.spatialk-d trees, distance metrics, geometry.
scipy.interpolateSpline 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

Test yourself

Q1. SciPy sits on top of…
Q2. For numerical minimisation use…
Q3. For hypothesis tests use…

Discussion

Loading…