fundamentos · temario
1.4tema 4 de 13

NumPy

ndarray, broadcasting, vectorización e indexing

NumPy es la librería fundamental para computación numérica en Python. Su tipo principal es `ndarray` (n-dimensional array), que es un contenedor de elementos homogéneos (todos del mismo tipo: int, float, etc.) en memoria contigua. A diferencia de listas de Python que pueden mezclar tipos y son lentas, arrays de NumPy están optimizadas para operaciones matemáticas masivas. Una lista de Python es un arreglo de punteros; un ndarray de NumPy es un bloque de memoria sólido que permite operaciones vectorizadas muy rápidas.

La vectorización es la clave: en lugar de usar bucles Python (lento), expresas operaciones sobre arrays enteros. Comparación: `for x in lista: resultado = x * 2` es lento porque ejecuta bytecode Python por cada elemento. `numpy_array * 2` es 100x más rápido porque delega a código C compilado que procesa múltiples elementos por instrucción. NumPy usa SIMD (instrucciones que operan en múltiples elementos simultáneamente) y es cerca de velocidad C.

Broadcasting es el mecanismo que permite operar arrays de formas diferentes sin copiar datos innecesariamente. Si sumas un array (3, 4) con un array (3, 1), NumPy automáticamente expande el (3, 1) a (3, 4) conceptualmente sin copiar memoria. Las reglas: dimensiones se alinean a la derecha, si una es 1 se expande, si son incompatibles se falla. Broadcasting reduce código y es tremendamente eficiente.

El indexing y slicing son más poderosos que listas Python. `arr[0:3]` selecciona primeros 3 elementos, `arr[0:3, 1:4]` selecciona un sub-rectángulo de una matriz, `arr[arr > 5]` selecciona solo elementos mayores a 5 (fancy indexing). Boolean indexing (`arr[condition]`) es especialmente útil para filtrar datos sin bucles. El output es siempre una vista (no una copia) cuando es posible, preservando memoria.

Los dtypes (data types) definen cómo se almacena cada elemento: `int32`, `float64`, `bool`, `complex128`, `object` (Python objects), etc. Elegir el tipo correcto es crítico: `int32` usa 4 bytes, `int64` usa 8, `float16` es más rápido pero menos preciso. En ML, `float32` es estándar porque es 2x más rápido que `float64` con precisión suficiente. Los dtypes también controlan cómo se comportan operaciones (ej. división entera vs. float).

Operaciones de reducción resumen un eje o toda la matriz: `sum()`, `mean()`, `std()`, `min()`, `max()`. El parámetro `axis` es crítico: `axis=0` reduce columnas (suma cada columna), `axis=1` reduce filas (suma cada fila), `axis=None` suma todo. Muchos errores vienen de confundir qué eje se reduce. Las reducciones son O(n) pero ultra-optimizadas en código C.

structure.txt
# === CREATING ARRAYS ===
import numpy as np

arr = np.array([1, 2, 3, 4, 5])           # from list
zeros = np.zeros((3, 4))                   # 3x4 matrix of 0s
ones = np.ones((2, 3), dtype=np.float32)  # 2x3 matrix of 1s, float32
range_arr = np.arange(0, 10, 2)           # [0, 2, 4, 6, 8]
linspace_arr = np.linspace(0, 1, 5)       # 5 evenly spaced in [0, 1]
random_arr = np.random.randn(3, 4)        # 3x4 random from N(0,1)

# === SHAPE AND DTYPE ===
matrix = np.array([[1, 2, 3], [4, 5, 6]]) # 2x3
matrix.shape          # (2, 3)
matrix.dtype          # dtype('int64')
matrix.ndim           # 2 (number of dimensions)
matrix.size           # 6 (total elements)

# === VECTORIZATION (no loop needed) ===
result = matrix * 2   # multiply all elements by 2 — O(n) in C
result = matrix + 5   # add 5 to all elements
result = np.sqrt(matrix)  # square root of all elements

# === BROADCASTING ===
A = np.array([[1, 2, 3], [4, 5, 6]])  # shape (2, 3)
B = np.array([[10], [20]])              # shape (2, 1)
C = A + B  # B broadcasts to (2, 3), result is (2, 3)
           # [[11, 12, 13], [24, 25, 26]]

# === INDEXING AND SLICING ===
matrix[0]              # first row
matrix[0, 1]           # element at row 0, col 1
matrix[0:2, 1:3]       # rows 0-1, cols 1-2
matrix[:, 0]           # all rows, first column
matrix[matrix > 3]     # boolean indexing: only elements > 3

# === REDUCTION OPERATIONS ===
matrix.sum()           # sum all elements
matrix.sum(axis=0)     # sum along columns (reduce rows)
matrix.sum(axis=1)     # sum along rows (reduce columns)
matrix.mean(axis=0)    # mean of each column
matrix.std()           # standard deviation of all elements
matrix.max()           # maximum element

Katas (6)

Debugging lab

Detecta y corrige el error en el código.

0/6 tests passing0%
  1. 1.4.5.1

    # Normalize a dataset: subtract mean, divide by std data = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # Wrong: using loops normalized = [] for row in data: new_row = [] for val in row: # ... manual subtraction and division

  2. 1.4.5.2

    # Filter rows where column 0 > 5 data = np.array([[1, 2], [6, 7], [3, 4], [8, 9]]) # Wrong: loop filtered = [] for i in range(len(data)): if data[i, 0] > 5: filtered.append(data[i]) filtered = np.array(filtered)

  3. 1.4.5.3

    # Compute pairwise distances between two sets of points X = np.random.randn(1000, 50) # 1000 points in 50D Y = np.random.randn(100, 50) # 100 points in 50D # Wrong: O(n*m*d) loop distances = np.zeros((1000, 100)) for i in range(1000): for j in range(100): dist = np.sum((X[i] - Y[j]) ** 2) ** 0.5 distances[i, j] = dist

  4. 1.4.5.4

    # Compute column-wise mean and subtract from each row data = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # Wrong: didn't understand axis or broadcasting mean = data.mean() # scalar, loses structure centered = data - mean # not what we want

  5. 1.4.5.5

    # Select rows where ANY column > 5 data = np.array([[1, 2], [6, 3], [3, 7]]) # Attempt: multiple conditions confusing mask = (data[:, 0] > 5) or (data[:, 1] > 5) # ERROR: or doesn't work with arrays

  6. 1.4.5.6

    # Reshape and compute sum per group arr = np.array([1, 2, 3, 4, 5, 6]) # Want: sum of groups of 2: [1+2, 3+4, 5+6] = [3, 7, 11] # Confused: reshape wrong reshaped = arr.reshape(2, 3) # NO, this is 2x3, not 3x2 result = reshaped.sum(axis=0) # gives [5, 7, 9], wrong