Numpy 📋 Copia tutto Comandi NumPy_HTML_TAG_157__ __HTML_TAG_158_📄 Generare NumPy PDF Guida_HTML_TAG_159__ __HTML_TAG_160_ # NumPy Cheatsheet # ## Installazione _Tabella_162__ # Comandi di base ## Array Creation # _Tabella_163__ ### Array Properties _Tabella_164__ ### Array Indexing & Slicing _Tabella_165_ # Operazioni matematiche di base _Tabella_166_ ## Array Reshaping # _Tabella_167__ ### Array Concatenation & Split _Tabella_168__ ## Uso avanzato ## Algebra lineare _Tabella_169_ ### Funzioni statistiche _Tabella_170__ ### Broadcasting & Advanced Indexing TABELLA 171_ ### Funzioni universali (ufuncs) _Tabella_172__ # # Random Number Generation TABELLA 173_ ### Memory & Performance _Tabella_174__ ## Configurazione # Tipi di dati NumPy supporta vari tipi di dati per l'ottimizzazione della memoria: # Integer types np.int8 # -128 to 127 np.int16 # -32,768 to 32,767 np.int32 # -2^31 to 2^31-1 np.int64 # -2^63 to 2^63-1 np.uint8 # 0 to 255 np.uint16 # 0 to 65,535 # Float types np.float16 # Half precision np.float32 # Single precision np.float64 # Double precision (default) # Complex types np.complex64 # Two 32-bit floats np.complex128 # Two 64-bit floats # Boolean np.bool_ # True or False # String types np.str_ # Unicode string np.bytes_ # Byte string # Create array with specific dtype arr = np.array([1, 2, 3], dtype=np.float32) ### Opzioni di stampa Configurare come vengono visualizzati gli array: # Set print options np.set_printoptions( precision=3, # Decimal places suppress=True, # Suppress scientific notation threshold=1000, # Max elements before summarizing edgeitems=3, # Items at start/end when summarizing linewidth=120 # Characters per line ) # Example: suppress scientific notation np.set_printoptions(suppress=True) print(np.array([1e-10, 1e10])) # [0. 10000000000.] # Reset to defaults np.set_printoptions() ### Gestione degli errori Configurare come NumPy gestisce errori numerici: # Set error handling np.seterr( divide='warn', # Division by zero: 'ignore', 'warn', 'raise', 'call' over='warn', # Overflow: 'ignore', 'warn', 'raise', 'call' under='ignore', # Underflow invalid='warn' # Invalid operation (e.g., sqrt(-1)) ) # Context manager for temporary settings with np.errstate(divide='ignore'): result = np.array([1, 2]) / 0 # No warning in this block # Check for errors after operations np.seterr(all='ignore') result = np.array([1]) / 0 if np.isinf(result).any(): print("Infinity detected") ## Configurazione del generatore di numeri casuali # Legacy API (older code) np.random.seed(42) # Modern API (recommended) rng = np.random.default_rng(seed=42) # Use different algorithms from numpy.random import PCG64, Philox, MT19937 rng = np.random.Generator(PCG64(seed=42)) # Default, fastest rng = np.random.Generator(Philox(seed=42)) # Parallel streams rng = np.random.Generator(MT19937(seed=42)) # Legacy compatibility ## Common Use Cases ### Use Case 1: Normalizzazione dei dati Normalizzare i dati a zero media e variazione unità (standardizzazione): import numpy as np # Sample data data = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=float) # Standardize: (x - mean) / std mean = np.mean(data, axis=0) std = np.std(data, axis=0) normalized = (data - mean) / std print(normalized) # [[-1.22474487 -1.22474487 -1.22474487] # [ 0. 0. 0. ] # [ 1.22474487 1.22474487 1.22474487]] # Min-Max normalization: (x - min) / (max - min) min_val = np.min(data, axis=0) max_val = np.max(data, axis=0) normalized_minmax = (data - min_val) / (max_val - min_val) ### Use Case 2: Image Processing Manipolare immagini come array NumPy: import numpy as np from PIL import Image # Load image as array img = np.array(Image.open('photo.jpg')) print(f"Shape: {img.shape}") # (height, width, channels) # Convert to grayscale gray = np.mean(img, axis=2).astype(np.uint8) # Crop image (top-left 100x100 pixels) cropped = img[:100, :100] # Flip image vertically flipped = np.flipud(img) # Rotate 90 degrees rotated = np.rot90(img) # Adjust brightness (add value to all pixels) brighter = np.clip(img + 50, 0, 255).astype(np.uint8) # Apply threshold threshold = 128 binary = np.where(gray > threshold, 255, 0).astype(np.uint8) # Save result Image.fromarray(binary).save('processed.jpg') ### Use Case 3: Time Series Analysis Calcola le medie e le statistiche in movimento: import numpy as np # Sample time series data prices = np.array([100, 102, 101, 105, 107, 106, 108, 110, 109, 111]) # Simple moving average (window size 3) window = 3 moving_avg = np.convolve(prices, np.ones(window)/window, mode='valid') print(f"Moving average: {moving_avg}") # Calculate returns (percentage change) returns = np.diff(prices) / prices[:-1] * 100 print(f"Returns: {returns}") # Cumulative returns cumulative_returns = np.cumprod(1 + returns/100) - 1 print(f"Cumulative returns: {cumulative_returns}") # Volatility (rolling standard deviation) def rolling_std(arr, window): return np.array([np.std(arr[i:i+window]) for i in range(len(arr)-window+1)]) volatility = rolling_std(returns, window=3) print(f"Volatility: {volatility}") # Detect outliers (values > 2 std from mean) mean = np.mean(prices) std = np.std(prices) outliers = np.abs(prices - mean) > 2 * std print(f"Outliers at indices: {np.where(outliers)[0]}") ### Use Case 4: Matrix Operations for Machine Learning Attuazione delle operazioni di rete neurale di base: import numpy as np # Initialize weights and biases np.random.seed(42) input_size, hidden_size, output_size = 4, 5, 3 W1 = np.random.randn(input_size, hidden_size) * 0.01 b1 = np.zeros((1, hidden_size)) W2 = np.random.randn(hidden_size, output_size) * 0.01 b2 = np.zeros((1, output_size)) # Sample input (batch of 10 samples) X = np.random.randn(10, input_size) # Forward pass def sigmoid(x): return 1 / (1 + np.exp(-x)) def softmax(x): exp_x = np.exp(x - np.max(x, axis=1, keepdims=True)) return exp_x / np.sum(exp_x, axis=1, keepdims=True) # Hidden layer z1 = np.dot(X, W1) + b1 a1 = sigmoid(z1) # Output layer z2 = np.dot(a1, W2) + b2 a2 = softmax(z2) print(f"Output shape: {a2.shape}") # (10, 3) print(f"Output probabilities sum to 1: {np.allclose(np.sum(a2, axis=1), 1)}") # Calculate loss (cross-entropy) y_true = np.array([0, 1, 2, 0, 1, 2, 0, 1, 2, 0]) # True labels y_one_hot = np.eye(output_size)[y_true] loss = -np.mean(np.sum(y_one_hot * np.log(a2 + 1e-8), axis=1)) print(f"Loss: {loss}") ### Use Case 5: Analisi statistica Eseguire test di ipotesi e calcoli statistici: ``python' importazione numpy come np # Dati campione: punteggi di prova da due gruppi [85, 88, 90, 92, 87, 89, 91, 86, 88, 90]) gruppo_b = np.array([78, 82, 80, 85, 83, 81, 84, 79, 82, 80]) Statistiche descrittive stampa (f"Gruppo A - Mean: {np.mean(group_a):.2f}, Std: {np.std(group_a):.2f}") stampa(f"Gruppo B - Mean: {np.mean(group_b):.2f}, Std: {np.std(group_b):.2f}") # T-test (calcolo manuale) n_a, n_b = len(group_a), len(group_b) mean_a, mean_b = np.mean(group_a), np.mean(group_b) var_a, var_b = np.var(group_a, ddof=1), np.var(group_b, ddof=1) # Deviazione standard in piscina (n_a - 1) * var_a + (n_b - 1) * var_b - 1) * var_b) / (n_a + n_b - 2) t_statistic = (mean_a - mean_b) / (pooled_std * np.sqrt(1/n_a + 1/n_b) stampa (f"T-statistica: {t_statistic:.3f}") # Analisi della correlazione correlazione = np.corrcoef(group_a, group_b)[0, 1] stampa(f"Correlazione: {correlazione:.3f}") # Intervallo di fiducia Bootstrap N_bootstrap = 10000 bootstrap_means = np.array([