Data types y memory efficiency
int32/int64, float32/float64, memory footprint y casting
Los dtypes definen cómo se almacena cada elemento en memoria. int32 usa 4 bytes, int64 usa 8, float32 usa 4, float64 usa 8. Elegir el tipo correcto impacta directamente memoria (2x menos con float32 vs float64) y velocidad (operaciones en float32 son 2-4x más rápidas en GPUs). En machine learning, float32 es estándar porque es suficientemente preciso pero usa 50% menos memoria.
El casting (conversión de tipos) es frecuente en data pipelines. `array.astype(np.float32)` convierte de float64 a float32. `array.astype(np.int32)` convierte a entero. Cast implícito ocurre cuando operaciones mezclan tipos — NumPy automáticamente promota a tipo más largo (int32 + int64 = int64). Entender esto evita bugs de precisión y sobrecarga de memoria.
import numpy as np
# === DTYPE INSPECTION ===
arr = np.array([1, 2, 3])
print(arr.dtype) # dtype('int64') by default
print(arr.itemsize) # 8 bytes per element
print(arr.nbytes) # total memory: itemsize * size
# === CREATE WITH SPECIFIC DTYPE ===
arr_f32 = np.array([1.0, 2.0, 3.0], dtype=np.float32) # 4 bytes each
arr_f64 = np.array([1.0, 2.0, 3.0], dtype=np.float64) # 8 bytes each
arr_int = np.arange(10, dtype=np.int32) # 4 bytes each
# === MEMORY COMPARISON ===
large_f64 = np.random.randn(10_000_000) # ~80 MB
large_f32 = large_f64.astype(np.float32) # ~40 MB (50% less)
print(f'float64: {large_f64.nbytes / 1e6:.1f} MB')
print(f'float32: {large_f32.nbytes / 1e6:.1f} MB')
# === CASTING ===
arr = np.array([1.9, 2.1, 3.8])
arr_int = arr.astype(np.int32) # [1, 2, 3] — truncates, not rounds
# === PROMOTION IN OPERATIONS ===
a = np.array([1, 2], dtype=np.int32) # 4 bytes each
b = np.array([1.5, 2.5], dtype=np.float32) # 4 bytes each
result = a + b # automatically float32 + int32
print(result.dtype) # float32Debugging lab
Detecta y corrige el error en el código.
- 01
# Load 1GB of float data, memory bloated data = np.random.randn(100_000_000) # 100M floats print(data.nbytes / 1e9) # ~0.8 GB (float64 default)
- 02
# Integer division issue: expects float result result = np.array([1, 2, 3], dtype=np.int32) / 2 print(result[0]) # 0.5 — accidentally promoted to float