Industrielle Fertigung
Industrielles Internet der Dinge | Industrielle Materialien | Gerätewartung und Reparatur | Industrielle Programmierung |
home  MfgRobots >> Industrielle Fertigung >  >> Industrial programming >> Python

SciPy in Python: Umfassendes Tutorial zu Bibliotheken & Funktionen

SciPy in Python: Umfassendes Tutorial zu Bibliotheken & Funktionen

SciPy in Python

SciPy ist eine Open-Source-Bibliothek, die NumPy erweitert, um Werkzeuge für die Lösung mathematischer, wissenschaftlicher, ingenieurtechnischer und technischer Probleme bereitzustellen. Auf NumPy aufbauend, bietet SciPy einen breiten Satz von High-Level-Befehlen für Datenmanipulation und Visualisierung.

Sub-Pakete

Dieses Tutorial deckt ab:

Warum SciPy verwenden?

NumPy vs. SciPy

NumPy

SciPy

Installation & Umgebungseinrichtung

Installieren Sie SciPy mit pip oder System-Paketmanagern:

python3 -m pip install --user numpy scipy
sudo apt-get install python3-scipy python3-numpy
sudo port install py35-scipy py35-numpy

SciPy und NumPy in Ihren Skripten importieren:

from scipy import special
import numpy as np

Datei-I/O mit scipy.io

MATLAB .mat Dateien einfach speichern und laden:

import numpy as np
from scipy import io as sio

array = np.ones((4, 4))
sio.savemat('beispiel.mat', {'ar': array})
geladen = sio.loadmat('beispiel.mat', struct_as_record=True)
print(geladen['ar'])

Ausgabe:

array([[1., 1., 1., 1.],
       [1., 1., 1., 1.],
       [1., 1., 1., 1.],
       [1., 1., 1., 1.]])

Spezielle Funktionen – scipy.special

Beispiele häufig verwendeter spezieller Funktionen:

Lineare Algebra – scipy.linalg

Determinante, Inverse, Eigenwerte und Eigenvektoren berechnen:

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)

Ausgabe:

-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]]

Diskrete Fourier-Transformation – scipy.fftpack

Einen Sinusoid transformieren und sein Spektrum visualisieren:

%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('Zeit (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('Frequenz (Hz)')
plt.ylabel('Magnitude')
plt.xlim(-sample_rate/2, sample_rate/2)
plt.ylim(0, 110)
plt.show()

Optimierung – scipy.optimize

Minimum einer skalaren Funktion mit BFGS und globaler Suche mit Basin-Hopping finden:

%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 Ergebnis:', min_bfgs)

min_basin = optimize.basinhopping(func, 0)
print('Basin-Hopping Ergebnis:', min_basin.x)

Die Ausgabe zeigt das lokale Minimum, das durch BFGS gefunden wurde, und das globale Optimum, das durch Basin-Hopping bestätigt wurde.

Nelder-Mead Algorithmus

Einfache unconstrained Minimierung ohne Gradienteninformation:

from scipy.optimize import minimize

def f(x):
    return 0.4*(1 - x[0])**2

res = minimize(f, [2, -1], method='Nelder-Mead')
print('Ergebnis:', res.x, 'Funktionswert:', res.fun)

Bildverarbeitung – scipy.ndimage

Bilder manipulieren: anzeigen, spiegeln, rotieren, Filter anwenden.

from scipy import ndimage, misc
from matplotlib import pyplot as plt

panda = misc.face()
plt.imshow(panda)
plt.title('Original')
plt.show()

flip_down = np.flipud(panda)
plt.imshow(flip_down)
plt.title('Nach unten gespiegelt')
plt.show()

rotated = ndimage.rotate(panda, 135)
plt.imshow(rotated)
plt.title('Rotiert 135°')
plt.show()

Numerische Integration – scipy.integrate

Einfache und doppelte Integrale mit automatischer Fehlerabschätzung:

from scipy import integrate

# Einfaches Integral von x^2 von 0 bis 1
einfach = integrate.quad(lambda x: x**2, 0, 1)
print('Einfaches Integral:', einfach)

# Doppeltes Integral von 64*x*y über dreieckige Domäne
doppelt = integrate.dblquad(lambda x, y: 64*x*y, 0, 2/4,
                            lambda x: 0,
                            lambda y: (1 - 2*y**2)**0.5)
print('Doppeltes Integral:', doppelt)

Beide geben ein Tupel zurück: (Wert, geschätzter Fehler).

Zusammenfassung

SciPy erweitert NumPy zu einem vollständigen wissenschaftlichen Computing-Stack, einschließlich linearer Algebra, Optimierung, Statistik, Signalverarbeitung und Bildmanipulation. Seine umfangreichen Sub-Pakete und der robuste Community-Support machen es unverzichtbar für Forscher und Ingenieure.

PaketnameBeschreibung
scipy.ioDatei-Ein-/Ausgabe für MATLAB, CSV, NetCDF, etc.
scipy.specialSpezielle mathematische Funktionen (Bessel, Gamma, etc.)
scipy.linalgFortgeschrittene lineare-Algebra-Routinen
scipy.interpolateInterpolationsmethoden
scipy.optimizeOptimierungs- und Kurvenanpassungswerkzeuge
scipy.statsStatistische Verteilungen & Zufallszahlengenerierung
scipy.integrateNumerische Integration (quad, dblquad, etc.)
scipy.fftpackSchnelle Fourier-Transformationen
scipy.signalSignalverarbeitungsdienstprogramme
scipy.ndimageMehrdimensionale Bildverarbeitung

Python

  1. Python print()-Funktion: Praktischer Leitfaden mit Beispielen
  2. Pythons str.count(): Zeichen & Teilstrings zählen mit Beispielen
  3. Python format()-Strings meistern mit klaren Beispielen
  4. Python Lambda-Funktionen meistern: Praxisbeispiele & Best Practices
  5. Python abs()-Funktion: Absolutwerte für Zahlen & Komplexe Zahlen berechnen
  6. Python round()-Funktion erklärt mit praktischen Beispielen
  7. Pythons map()-Funktion meistern: Syntax, Beispiele und Best Practices
  8. Python timeit(): Ausführungszeit messen mit praktischen Beispielen
  9. Pythons yield meistern: Generator vs. Return – Ein praktischer Leitfaden
  10. type() und isinstance() in Python verstehen: Praktische Beispiele