الدرس 2 من 8

أساسيات NumPy

المكتبة اللي تحت كل مكتبات الـ AI.

ليه مش list عادية؟

الـ NumPy array شبه الـ list، بس كل عناصرها من نفس النوع ومتخزنة جنب بعض في الذاكرة. ده بيخليها أسرع بعشرات المرات، وبيخليك تعمل العملية على كل العناصر مرة واحدة من غير loop. الطريقة دي اسمها Vectorization.

speed.py
import numpy as np
import time

prices = list(range(1_000_000))
arr = np.array(prices)

start = time.time()
with_vat_list = [p * 1.14 for p in prices]
list_time = time.time() - start

start = time.time()
with_vat_arr = arr * 1.14          # no loop! applies to every element
numpy_time = time.time() - start

print(f"list:  {list_time:.4f}s")
print(f"numpy: {numpy_time:.4f}s")
print(f"NumPy is ~{list_time / numpy_time:.0f}x faster")

طرق عمل array

create.py
import numpy as np

a = np.array([10, 20, 30])
print(a, a.dtype)                 # dtype = type of elements

print(np.zeros(4))                # [0. 0. 0. 0.]
print(np.ones((2, 3)))            # 2 rows, 3 columns of ones
print(np.arange(0, 10, 2))        # like range(), but an array
print(np.linspace(0, 1, 5))       # 5 evenly spaced numbers from 0 to 1

العمليات على كل العناصر

elementwise.py
import numpy as np

temps_c = np.array([18, 24, 31, 36, 29])     # a week in Cairo
temps_f = temps_c * 9 / 5 + 32               # convert all at once
print(temps_f)

print("Mean:", temps_c.mean())
print("Max:", temps_c.max(), "on day", temps_c.argmax())  # argmax = index of max
print("Hot days:", temps_c > 30)              # comparison -> array of True/False

أرقام عشوائية

هتحتاجها كتير: بيانات تجريبية، تقسيم الداتا، والأوزان الأولية للموديلات.

random.py
import numpy as np

rng = np.random.default_rng(seed=42)       # seed -> reproducible results

dice = rng.integers(1, 7, size=10)         # 10 dice rolls
heights = rng.normal(loc=170, scale=8, size=5)   # normal distribution
print(dice)
print(heights.round(1))
💡 الـ seed مهمةلو ثبّت الـ seed، الأرقام العشوائية هتطلع هي هي كل مرة. ده مهم جداً في الـ AI عشان لما تجرب حاجة وتقارن نتايج، تبقى متأكد إن الفرق من التغيير اللي عملته مش من الصدفة.
الدرس اللي فات