SciPy in Python: Uitgebreide Tutorial over Bibliotheken & Functies
SciPy in Python
SciPy is een open-source bibliotheek die NumPy uitbreidt om tools te bieden voor het oplossen van wiskundige, wetenschappelijke, technische en engineering problemen. Gebouwd op NumPy, biedt SciPy een brede set high-level commando's voor data manipulatie en visualisatie.
Sub-pakketten
- scipy.io – Bestands I/O voor MATLAB, NetCDF, CSV en vele andere formaten
- scipy.special – Speciale wiskundige functies (Bessel, Gamma, etc.)
- scipy.linalg – Lineaire algebra routines
- scipy.interpolate – Interpolatie technieken
- scipy.optimize – Optimalisatie en curve fitting
- scipy.stats – Statistische verdelingen en random number generatie
- scipy.integrate – Numerieke integratie
- scipy.fftpack – Snelle Fourier transformaties
- scipy.signal – Signaalverwerking
- scipy.ndimage – Multi-dimensionale beeldverwerking
Deze tutorial behandelt:
- Wat SciPy is en waarom het belangrijk is
- Verschillen tussen NumPy en SciPy
- Installatie en omgeving setup
- Belangrijke sub-pakketten met codevoorbeelden
- Praktische toepassingen: lineaire algebra, Fourier transformaties, optimalisatie, beeldverwerking en numerieke integratie
Waarom SciPy Gebruiken?
- Uitgebreide set wetenschappelijke tools, tweede alleen aan bibliotheken zoals GNU Scientific Library en MATLAB
- Gemakkelijk te gebruiken, snel en volledig compatibel met NumPy arrays
- Wijd geadopteerd in academie en industrie, wat robuuste ondersteuning en community bijdrages garandeert
NumPy vs. SciPy
NumPy
- Kernbibliotheek voor high-performance numerieke computing in Python, geschreven in C
- Biedt array-objecten en basisoperaties (sorteren, reshapen, indexeren)
- Fundament voor alle wetenschappelijke bibliotheken in Python
SciPy
- Gebouwd op NumPy, uitbreidt het met gespecialiseerde algoritmes
- Bevat complete lineaire-algebra suites, optimalisatie, statistiek en meer
- Essentieel voor geavanceerde wetenschappelijke workflows
Installatie & Omgeving Setup
Installeer SciPy met pip of systeem package managers:
python3 -m pip install --user numpy scipy
sudo apt-get install python3-scipy python3-numpy
sudo port install py35-scipy py35-numpy
Importeer SciPy en NumPy in je scripts:
from scipy import special import numpy as np
Bestands I/O met scipy.io
Sla en laad MATLAB .mat bestanden eenvoudig op:
import numpy as np
from scipy import io as sio
array = np.ones((4, 4))
sio.savemat('voorbeeld.mat', {'ar': array})
geladen = sio.loadmat('voorbeeld.mat', struct_as_record=True)
print(geladen['ar'])
Output:
array([[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.]])
Speciale Functies – scipy.special
Voorbeelden van veelgebruikte speciale functies:
- Derde machtswortel:
scipy.special.cbrt(x)→cbrt([27, 64]) # [3., 4.] - 10x:
scipy.special.exp10(x)→exp10([1,10]) # [1.e+01 1.e+10] - Combinaties:
scipy.special.comb(N, k, exact=False, repetition=True)→comb(5, 2) # 15.0 - Permutaties:
scipy.special.perm(N, k, exact=True)→perm(5, 2) # 20 - LogSumExp:
scipy.special.logsumexp(x) - Bessel J:
scipy.special.jn(n, x)
Lineaire Algebra – scipy.linalg
Bereken determinant, inverse, eigenwaarden en eigenvectoren:
from scipy import linalg import numpy as np A = np.array([[4,5],[3,2]]) print(linalg.det(A)) # -7.0 print(linalg.inv(A)) # inverse matrix vals, vecs = linalg.eig(A) print(vals) print(vecs)
Output:
-7.0
array([[-0.28571429, 0.71428571],
[ 0.42857143, -0.57142857]])
[ 9.+0.j -1.+0.j]
[[ 0.70710678 -0.5547002 ]
[ 0.70710678 0.83205029]]
Discrete Fourier Transform – scipy.fftpack
Transformeer een sinusoïde en visualiseer het spectrum:
%matplotlib inline
from matplotlib import pyplot as plt
import numpy as np
from scipy import fftpack
freq = 5
sample_rate = 50
t = np.linspace(0, 2, 2 * sample_rate, endpoint=False)
wave = np.sin(freq * 2 * np.pi * t)
plt.plot(t, wave)
plt.xlabel('Tijd (s)'); plt.ylabel('Amplitude')
plt.show()
A = fftpack.fft(wave)
frequency = fftpack.fftfreq(len(wave)) * sample_rate
plt.stem(frequency, np.abs(A))
plt.xlabel('Frequentie (Hz)')
plt.ylabel('Magnitude')
plt.xlim(-sample_rate/2, sample_rate/2)
plt.ylim(0, 110)
plt.show()
Optimalisatie – scipy.optimize
Vind het minimum van een scalaire functie met BFGS en globale zoektocht met basin-hopping:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from scipy import optimize
def func(a):
return a*2 + 20*np.sin(a)
plt.plot(np.linspace(-10, 10, 400), func(np.linspace(-10, 10, 400)))
plt.show()
min_bfgs = optimize.fmin_bfgs(func, 0)
print('BFGS resultaat:', min_bfgs)
min_basin = optimize.basinhopping(func, 0)
print('Basin-hopping resultaat:', min_basin.x)
De output toont het lokale minimum gevonden door BFGS en het globale optimum bevestigd door basin-hopping.
Nelder-Mead Algoritme
Eenvoudige unconstrained minimalisatie zonder gradiëntinformatie:
from scipy.optimize import minimize
def f(x):
return 0.4*(1 - x[0])**2
res = minimize(f, [2, -1], method='Nelder-Mead')
print('Resultaat:', res.x, 'Functiewaarde:', res.fun)
Beeldverwerking – scipy.ndimage
Manipuleer afbeeldingen: tonen, spiegelen, roteren en filters toepassen.
from scipy import ndimage, misc
from matplotlib import pyplot as plt
panda = misc.face()
plt.imshow(panda)
plt.title('Origineel')
plt.show()
flip_down = np.flipud(panda)
plt.imshow(flip_down)
plt.title('Omgekeerd')
plt.show()
rotated = ndimage.rotate(panda, 135)
plt.imshow(rotated)
plt.title('Geroteerd 135°')
plt.show()
Numerieke Integratie – scipy.integrate
Enkele en dubbele integralen met automatische foutschatting:
from scipy import integrate
# Enkele integraal van x^2 van 0 tot 1
single = integrate.quad(lambda x: x**2, 0, 1)
print('Enkele integraal:', single)
# Dubbele integraal van 64*x*y over een driehoekig domein
double = integrate.dblquad(lambda x, y: 64*x*y, 0, 2/4, lambda x: 0, lambda y: (1 - 2*y**2)**0.5)
print('Dubbele integraal:', double)
Beide retourneren een tuple: (waarde, geschatte fout).
Samenvatting
SciPy breidt NumPy uit om een complete wetenschappelijke computing stack te bieden, inclusief lineaire algebra, optimalisatie, statistiek, signaalverwerking en beeldmanipulatie. De uitgebreide sub-pakketten en robuuste community ondersteuning maken het onmisbaar voor onderzoekers en ingenieurs.
| Pakketnaam | Beschrijving |
|---|---|
| scipy.io | Bestands input/output voor MATLAB, CSV, NetCDF, etc. |
| scipy.special | Speciale wiskundige functies (Bessel, Gamma, etc.) |
| scipy.linalg | Geavanceerde lineaire-algebra routines |
| scipy.interpolate | Interpolatie methoden |
| scipy.optimize | Optimalisatie en curve fitting tools |
| scipy.stats | Statistische verdelingen & random number generatie |
| scipy.integrate | Numerieke integratie (quad, dblquad, etc.) |
| scipy.fftpack | Snelle Fourier transformaties |
| scipy.signal | Signaalverwerking utiliteiten |
| scipy.ndimage | Multi-dimensionale beeldverwerking |
Python
- Python print()-functie: Praktische handleiding met voorbeelden
- Python's str.count() beheersen: Karakters & substrings tellen met voorbeelden
- Python `format()` strings beheersen met duidelijke voorbeelden
- Python's String.find()-methode beheersen: Syntaxis, voorbeelden & alternatieven
- Python lambda-functies beheersen: praktische voorbeelden & best practices
- Python abs()-functie: absolute waarden berekenen voor getallen & complexe getallen
- Python round()-functie uitgelegd met praktische voorbeelden
- Python's map()-functie beheersen: syntaxis, voorbeelden en best practices
- Python timeit() – Uitvoeringstijd meten met praktische voorbeelden
- Python's yield meesteren: Generator vs Return – Een praktische gids
- type() en isinstance() in Python begrijpen: praktische voorbeelden