1.4.4 · HinglishPython & Scientific Computing

NumPy arrays and vectorized operations

1,406 words6 min readRead in English

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 karna
  • arange: Iteration indices
  • linspace: 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 hai

Yeh step kyun?

  • solve LU factorization () use karta hai, phir forward/backward substitution— hai lekin numerically stable hai.
  • Direct np.linalg.inv(A) @ b slower 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

  1. Loops avoid karo: for i in range(n): result[i] = func(data[i]) ko result = func(data) se replace karo.
  2. In-place ops use karo: a += 1 directly memory modify karta hai, a = a + 1 naya array create karta hai.
  3. Preallocate karo: result = np.empty(shape) phir fill karo, loop mein np.append ki bajay (jo copy karta hai).
  4. Profile karo: Approaches compare karne ke liye Jupyter mein %timeit use karo.

Connections


#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?
Jab arrays ki shapes incompatible hon—har dimension ke liye (right se), sizes equal hone chahiye ya ek 1 hona chahiye. Jaise (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?
Memory efficiency ke liye—slices underlying data buffer share karte hain. Har operation ke liye multi-GB arrays copy karna bahut slow hota.
(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?
Boolean indexing: 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?
Universal function: arrays par element-wise kaam karta hai broadcasting support ke saath, compiled C mein implement hai. Examples: np.sin, np.exp, np.maximum.

Concept Map

converted via np.array

has

stored in

enables

powers

element-wise

matrix mul with @

gives

built by

solves

critical for

Python lists

NumPy ndarray

shape dtype strides

Contiguous memory

Cache-friendly SIMD access

Vectorized operations

Hadamard product with *

Optimized BLAS libraries

100x speedup vs loops

Constructors zeros ones arange linspace random

Linear systems Ax = b

ML training on billions of params