NumPy arrays and vectorized operations
1.4.4· AI-ML › Python & Scientific Computing
NumPy Arrays Kya Hain?
Arrays Banana: Scratch Se Derivation
Python lists se ndarrays tak kaise jaate hain?
import numpy as np
# Method 1: Python list se
a = np.array([1, 2, 3, 4]) # shape (4,), dtype inferred as int64
# Method 2: Built-in constructors
zeros = np.zeros((3, 4)) # 3×4 array of 0.0
ones = np.ones((2, 5)) # 2×5 array of 1.0
arange = np.arange(0, 10, 2) # [0, 2, 4, 6, 8], like range()
linspace = np.linspace(0, 1, 5) # [0, 0.25, 0.5, 0.75, 1.0], 5 evenly spaced
# Method 3: Random
rand = np.random.rand(3, 3) # uniform [0,1), shape (3,3)
randn = np.random.randn(100) # standard normal, shape (100,)Alag-alag constructors kyun? Har ek ek use case ke liye optimize hai:
zeros/ones: Weights, masks initialize karnaarange: Iteration indiceslinspace: Continuous domains sample karna (plotting, integrals)random: Monte Carlo, initialization
Vectorized Operations: Core Principle
Example 4: Linear Systems Solve Karna
# Ax = b solve karo
A = np.array([[3, 1], [1, 2]])
b = np.array([9, 8])
x = np.linalg.solve(A, b) # [2., 3.], LU decomposition se solve karta hai
# Verify karo
print(A @ x) # [9., 8.], b se match karta haiYeh step kyun?
solveLU factorization () use karta hai, phir forward/backward substitution— hai lekin numerically stable hai.- Direct
np.linalg.inv(A) @ bslower aur less accurate hai (conditioning issues ki wajah se).
Recall Ek 12-saal ke bachche ko explain karo
Socho tumhare paas Lego bricks ka ek bahut bada dher hai (ek million), aur tum har ek ko red colour karna chahte ho. Slow tarika: har brick uthao, colour karo, rakh do. Bahut time lagta hai kyunki tum ek waqt mein ek hi kaam kar rahe ho.
NumPy ek jaadu ki conveyor belt ki tarah hai: tum saari bricks uspe dump karo, ek button dabaao, aur belt sab ko ek saath painting machine se gujarti hai. Tumhe saari painted bricks ek hi baar milti hain—same result, 100 guna fast.
Broadcasting toh aur bhi cool hai: maan lo tumhare paas ek checkerboard hai 100 rows ka, aur tum har column ke har square mein 10 points add karna chahte ho. 100 rows mein loop karne ki bajay, tum NumPy ko bas bolo "har row mein yeh [10, 20, 30, ...] add karo," aur woh ek hi magic swoop mein kar deta hai apni chhoti list ko bade board se match karke stretch karke.
Performance Tips
- Loops avoid karo:
for i in range(n): result[i] = func(data[i])koresult = func(data)se replace karo. - In-place ops use karo:
a += 1directly memory modify karta hai,a = a + 1naya array create karta hai. - Preallocate karo:
result = np.empty(shape)phir fill karo, loop meinnp.appendki bajay (jo copy karta hai). - Profile karo: Approaches compare karne ke liye Jupyter mein
%timeituse karo.
Connections
- 1.4.01-Python-fundamentals - NumPy Python data structures ke upar build hota hai
- 1.4.02-List-comprehensions-and-generators - Vectorization comprehensions ko replace karta hai
- 1.4.05-Pandas-DataFrames - DataFrames NumPy arrays pe built hain
- 2.1.03-Matrix-operations-for-ML - NumPy ke saath linear algebra neural nets ko power deta hai
- 2.2.04-Batch-gradient-descent - Vectorized gradient computation
- 3.1.02-Tensor-operations-in-PyTorch - PyTorch tensors NumPy API mirror karte hain
#flashcards/ai-ml
NumPy vectorized operations Python loops se 10-100× faster kyun hain? :: NumPy computation ko optimized C/Fortran code pe push karta hai jo CPU SIMD parallelism exploit karta hai aur Python interpreter overhead (type checks, reference counting per element) avoid karta hai.
np.arange(0, 10, 2) kya return karta hai?
array([0, 2, 4, 6, 8]), 0 se <10 tak step 2 ke saath integers (range jaisa lekin ndarray return karta hai).2D arrays ke liye NumPy mein A * B aur A @ B mein kya fark hai?
A * B element-wise (Hadamard) product hai; A @ B matrix multiplication hai (rows aur columns ka dot product).NumPy broadcasting kab fail hoti hai?
(3,4) aur (5,) fail hote hain (4 ≠ 5, koi bhi 1 nahin hai).NumPy slices jaise A[1:3,:] copies ki jagah views kyun hain?
(4, 1, 3) aur (5, 3) ko broadcast karne par output shape kya hogi?
(4, 5, 3). Right se align karo: (4,1,3) aur (1,5,3) (1 prepend karo), phir size 1 wale dimensions stretch karo.Ax = b solve karne ke liye kaunsa NumPy function use karna chahiye aur inv(A) @ b kyun nahin?
np.linalg.solve(A, b) LU decomposition use karke—inverse compute karne se faster aur numerically zyada stable hai.data[data > 0] NumPy mein kya karta hai?
data ke sirf wahi elements ka naya array return karta hai jo 0 se bade hain (fancy indexing, ek copy banata hai).np.arange(0, 1, 0.01) ki jagah np.linspace(0, 100) kyun use karte hain? :: linspace endpoints including exactly 100 points guarantee karta hai, floating-point errors avoid karke. arange float step ke saath rounding issues ho sakti hain aur endpoint exclude ho sakta hai.
Ufunc kya hai aur do examples do?
np.sin, np.exp, np.maximum.