الدرس 3 من 8

NumPy متقدم

الأدوات اللي هتستخدمها مع الصور والداتا الحقيقية.

التقطيع في بُعدين

في المصفوفة بتكتب [صفوف, أعمدة]. والـ : لوحدها معناها «كله».

slicing.py
import numpy as np

# Sales: rows = branches, columns = months (Jan..Apr)
sales = np.array([
    [120, 135, 150, 160],   # Nasr City
    [ 90,  85, 100, 110],   # Maadi
    [200, 210, 190, 230],   # Zamalek
])

print(sales[0])          # first branch, all months
print(sales[:, 2])       # all branches, March
print(sales[1:, :2])     # branches 2-3, first two months

الفلترة بالشروط (Boolean Mask)

بتكتب شرط، فيطلعلك array من True و False، وتستخدمه عشان تختار العناصر اللي بتحقق الشرط بس. دي من أقوى حاجات NumPy.

mask.py
import numpy as np

scores = np.array([45, 88, 67, 92, 38, 75])

passed = scores >= 50
print(passed)
print("Passing scores:", scores[passed])
print("How many failed:", (scores < 50).sum())   # True counts as 1

# Replace failing scores with 50 (a curve!)
curved = np.where(scores < 50, 50, scores)
print(curved)

التجميع على محور (axis)

لما تجمع مصفوفة، لازم تقول تجمع في أنهي اتجاه. axis=0 يعني نازل (على الصفوف، فبيطلع نتيجة لكل عمود)، و axis=1 يعني عرضي (على الأعمدة، فبيطلع نتيجة لكل صف).

axis.py
import numpy as np

sales = np.array([
    [120, 135, 150, 160],
    [ 90,  85, 100, 110],
    [200, 210, 190, 230],
])

print("Total per month (axis=0):", sales.sum(axis=0))
print("Total per branch (axis=1):", sales.sum(axis=1))
print("Grand total:", sales.sum())

الـ Broadcasting

لما تعمل عملية بين arrays بأحجام مختلفة، NumPy بيمد الصغير أوتوماتيك عشان يناسب الكبير. مثلاً: عايز تطرح متوسط كل عمود من كل قيمة فيه:

broadcast.py
import numpy as np

data = np.array([
    [120, 3],
    [ 90, 2],
    [150, 4],
])                                   # shape (3, 2)

col_means = data.mean(axis=0)        # shape (2,)
print("Means:", col_means)
print(data - col_means)              # (2,) is "stretched" to every row

تغيير الشكل (reshape)

reshape.py
import numpy as np

pixels = np.arange(12)               # 12 numbers in a flat line
image = pixels.reshape(3, 4)         # make it 3 rows x 4 columns
print(image)
print(image.reshape(-1))             # -1 = "figure it out" -> flatten back
🤖 الصورة = arrayصورة ملونة ٢٢٤×٢٢٤ بكسل عبارة عن array شكلها (224, 224, 3): طول، وعرض، و ٣ ألوان (أحمر وأخضر وأزرق). قص الصورة = slicing، تفتيحها = ضرب في رقم، وتحويلها لمتجه = reshape. كل اللي اتعلمته هنا هتستخدمه على الصور.
الدرس اللي فات