Vai al contenuto
__HTML_TAG_152_📋 Copia tutto Comandi SciPy_HTML_TAG_153__ __HTML_TAG_154_📄 Generare SciPy PDF Guide_HTML_TAG_155__

SciPy Cheatsheet

Installazione

Tabella_158_

Comandi di base

Importa e imposta

Tabella_159

Optimization Basics

TABELLA

Integrazione

Tabella_161_

Interpolazione

Tabella_162_

Statistiche

Tabella_163_

Algebra lineare

Tabella_164_

Elaborazione dei segnali

Tabella_165

Sparse Matricis

Tabella_166

Uso avanzato

Ottimizzazione avanzata

Tabella_167_

Integrazione avanzata

Tabella_168_

Interpolazione avanzata

Tabella_169

Statistiche avanzate

Tabella_170_

Algebra lineare avanzata

TABELLA 171_

Elaborazione avanzata dei segnali

Tabella_172_

Advanced Sparse Operations

TABELLA 173_

Operazioni spaziali

Tabella_174_

# Image Processing

Tabella_175_

Configurazione

NumPy/SciPy Configuration

# Display build and configuration information
import scipy
scipy.show_config()

# Set NumPy print options (affects SciPy output)
import numpy as np
np.set_printoptions(precision=4, suppress=True, linewidth=100)

# Configure warning filters
import warnings
warnings.filterwarnings('ignore', category=RuntimeWarning)

Configurazione di ottimizzazione

# Configure optimization options
from scipy.optimize import minimize

options = {
    'maxiter': 1000,      # Maximum iterations
    'disp': True,         # Display convergence messages
    'ftol': 1e-8,        # Function tolerance
    'gtol': 1e-8         # Gradient tolerance
}

result = minimize(func, x0, method='BFGS', options=options)

Integration Tolerances

from scipy.integrate import quad, solve_ivp

# Configure integration accuracy
result, error = quad(func, a, b, 
                    epsabs=1e-10,  # Absolute error tolerance
                    epsrel=1e-10,  # Relative error tolerance
                    limit=100)     # Subdivision limit

# Configure ODE solver
sol = solve_ivp(func, t_span, y0,
               method='RK45',
               rtol=1e-6,      # Relative tolerance
               atol=1e-9,      # Absolute tolerance
               max_step=0.1)   # Maximum step size

Selezione del formato della matrice di Sparse

from scipy import sparse

# Choose format based on use case
# CSR: efficient row slicing, matrix-vector products
A_csr = sparse.csr_matrix(data)

# CSC: efficient column slicing, matrix-vector products
A_csc = sparse.csc_matrix(data)

# COO: efficient construction, conversion
A_coo = sparse.coo_matrix(data)

# LIL: efficient incremental construction
A_lil = sparse.lil_matrix((1000, 1000))

# Random Number Generation

from scipy import stats
import numpy as np

# Set random seed for reproducibility
np.random.seed(42)

# Use RandomState for thread-safe operations
rng = np.random.RandomState(42)
data = stats.norm.rvs(loc=0, scale=1, size=1000, random_state=rng)

Common Use Cases

Use Case 1: Curve Fitting and Model Selection

import numpy as np
from scipy.optimize import curve_fit
from scipy import stats
import matplotlib.pyplot as plt

# Generate noisy data
x = np.linspace(0, 10, 100)
y_true = 2.5 * np.exp(-0.5 * x) + 1.0
y_noisy = y_true + 0.2 * np.random.normal(size=len(x))

# Define model
def exponential_model(x, a, b, c):
    return a * np.exp(-b * x) + c

# Fit curve
params, covariance = curve_fit(exponential_model, x, y_noisy)
y_fit = exponential_model(x, *params)

# Calculate R-squared
residuals = y_noisy - y_fit
ss_res = np.sum(residuals**2)
ss_tot = np.sum((y_noisy - np.mean(y_noisy))**2)
r_squared = 1 - (ss_res / ss_tot)

print(f"Parameters: a={params[0]:.3f}, b={params[1]:.3f}, c={params[2]:.3f}")
print(f"R-squared: {r_squared:.4f}")

Use Case 2: Signal Filtering and Analysis

import numpy as np
from scipy import signal
from scipy.fft import fft, fftfreq

# Create noisy signal
fs = 1000  # Sampling frequency
t = np.linspace(0, 1, fs)
clean_signal = np.sin(2 * np.pi * 50 * t) + np.sin(2 * np.pi * 120 * t)
noisy_signal = clean_signal + 0.5 * np.random.normal(size=len(t))

# Design and apply Butterworth filter
sos = signal.butter(10, 100, btype='low', fs=fs, output='sos')
filtered_signal = signal.sosfilt(sos, noisy_signal)

# Find peaks
peaks, properties = signal.find_peaks(filtered_signal, 
                                     height=0.5, 
                                     distance=20)

# Compute power spectral density
f, Pxx = signal.welch(filtered_signal, fs, nperseg=256)

print(f"Found {len(peaks)} peaks")
print(f"Dominant frequency: {f[np.argmax(Pxx)]:.2f} Hz")

Use Case 3: Statistica Ipotesi Testing

import numpy as np
from scipy import stats

# Generate two sample datasets
np.random.seed(42)
group1 = stats.norm.rvs(loc=100, scale=15, size=50)
group2 = stats.norm.rvs(loc=105, scale=15, size=50)

# Test for normality
_, p_norm1 = stats.shapiro(group1)
_, p_norm2 = stats.shapiro(group2)

# Test for equal variances
_, p_var = stats.levene(group1, group2)

# Perform appropriate t-test
if p_var > 0.05:
    # Equal variances
    t_stat, p_value = stats.ttest_ind(group1, group2)
    test_type = "Independent t-test (equal variances)"
else:
    # Unequal variances (Welch's t-test)
    t_stat, p_value = stats.ttest_ind(group1, group2, equal_var=False)
    test_type = "Welch's t-test (unequal variances)"

# Calculate effect size (Cohen's d)
pooled_std = np.sqrt((np.std(group1)**2 + np.std(group2)**2) / 2)
cohens_d = (np.mean(group1) - np.mean(group2)) / pooled_std

print(f"Test: {test_type}")
print(f"t-statistic: {t_stat:.4f}, p-value: {p_value:.4f}")
print(f"Cohen's d: {cohens_d:.4f}")

Use Case 4: Ottimizzazione con i vincoli

import numpy as np
from scipy.optimize import minimize

# Portfolio optimization: maximize return, minimize risk
def portfolio_objective(weights, returns, cov_matrix, risk_aversion=1.0):
    portfolio_return = np.sum(returns * weights)
    portfolio_risk = np.sqrt(np.dot(weights.T, np.dot(cov_matrix, weights)))
    return -(portfolio_return - risk_aversion * portfolio_risk)

# Sample data
n_assets = 4
returns = np.array([0.10, 0.12, 0.15, 0.08])
cov_matrix = np.array([[0.005, -0.001, 0.001, 0.000],
                       [-0.001, 0.008, 0.002, 0.001],
                       [0.001, 0.002, 0.012, 0.003],
                       [0.000, 0.001, 0.003, 0.004]])

# Constraints: weights sum to 1
constraints = {'type': 'eq', 'fun': lambda x: np.sum(x) - 1}

# Bounds: each weight between 0 and 1
bounds = tuple((0, 1) for _ in range(n_assets))

# Initial guess
x0 = np.array([1/n_assets] * n_assets)

# Optimize
result = minimize(portfolio_objective, x0, 
                 args=(returns, cov_matrix),
                 method='SLSQP',
                 bounds=bounds,
                 constraints=constraints)

optimal_weights = result.x
print("Optimal portfolio weights:")
for i, weight in enumerate(optimal_weights):
    print(f"Asset {i+1}: {weight*100:.2f}%")

Use Case 5: Pipeline di elaborazione delle immagini

import numpy as np
from scipy import ndimage
from scipy import signal

# Load or create image (grayscale)
image = np.random.rand(256, 256) * 255

# Step 1: Denoise with Gaussian filter
denoised = ndimage.gaussian_filter(image, sigma=2)

# Step 2: Edge detection
edges_x = ndimage.sobel(denoised, axis=0)
edges_y = ndimage.sobel(denoised, axis=1)
edges = np.hypot(edges_x, edges_y)

# Step 3: Threshold to create binary image
threshold = np.mean(edges) + np.std(edges)
binary = edges > threshold

# Step 4: Morphological operations
struct = ndimage.generate_binary_structure(2, 2)
cleaned = ndimage.binary_opening(binary, structure=struct)
cleaned = ndimage.binary_closing(cleaned, structure=struct)

# Step 5: Label connected components
labeled, num_features = ndimage.label(cleaned)

# Step 6: Calculate properties
sizes = ndimage.sum(cleaned, labeled, range(num_features + 1))
centers = ndimage.center_of_mass(cleaned, labeled, range(1, num_features + 1))

print(f"Found {num_features} objects")
print(f"Average object size: {np.mean(sizes[1:]):.2f} pixels")

Migliori Pratiche

  • Choose the Right Method: Seleziona algoritmi di ottimizzazione basati sulle caratteristiche dei problemi (basato a livello di funzionalità lisce, ottimizzatori globali per problemi multimodali)

  • Vectorize Operations: Utilizzare le operazioni di array NumPy invece di loop per migliorare le prestazioni; le funzioni di SciPy sono ottimizzate per gli input di array

  • Handle Numerical Stabilità**: Utilizzare tolleranze appropriate (rtol_, atol) per l'integrazione e l'ottimizzazione; essere consapevoli dei numeri delle condizioni nelle operazioni di algebra lineare

  • Leverage Sparse Matrices. Per grandi matrici con molti zeri, utilizzare formati di matrice radi (csr_matrix, csc_matrix) per salvare la memoria e migliorare la velocità di calcolo

  • Providere Buone Indovine iniziali: Gli algoritmi di ottimizzazione e di root-finding convergono più velocemente con punti di partenza ragionevoli; utilizzare la conoscenza del dominio quando possibile

  • Utilizzare i test statistici appropriati: Verificare i presupposti (normalità, uguale varianza) prima di applicare i test parametrici; utilizzare alternative non parametriche quando le ipotesi sono violate

  • Set Random Seeds: Assicurare la riproducibilità negli algoritmi stocastici impostando semi casuali con np.random.seed() o utilizzando oggetti RandomState

  • Profile Performance: Usa %timeit in Jupyter o cProfile per identificare i colli di bottiglia; considerare Numba o Cython per sezioni critiche se le funzioni di SciPy sono insufficienti

  • Control Convergence? Esaminare sempre i risultati di ottimizzazione (INLINE_CODE_149__, result.message) e gli errori di integrazione prima di fidarsi delle uscite

  • Unità di documento e scale: Documentare chiaramente unità fisiche e scale di dati; normalizzare i dati quando necessario per migliorare la stabilità numerica