Loading
Loading
NumPy هي مكتبة الحسابات الرقمية الأساسية في Python. كل مكتبات AI الكبرى مبنية فوقها.
NumPy تنفّذ عمليات على كل المصفوفة دفعة واحدة (vectorized) — أسرع 100× من Python Lists.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
zeros = np.zeros((3, 4)) # 3×4 من أصفار
ones = np.ones((2, 3)) # 2×3 من واحدات
rng = np.arange(0, 10, 2) # [0 2 4 6 8]
lin = np.linspace(0, 1, 5) # [0. 0.25 0.5 0.75 1.]
np.random.seed(42)
rand = np.random.randn(3, 3) # توزيع طبيعي
arr = np.arange(12)
matrix = arr.reshape(3, 4) # (3, 4)
flat = matrix.reshape(-1) # (12,)
images = np.random.randn(100, 28, 28, 1) # 100 صورة MNIST
print(images.shape) # (100, 28, 28, 1)
m = np.array([[1,2,3],[4,5,6],[7,8,9]])
print(m[0, :]) # الصف الأول: [1 2 3]
print(m[:, 1]) # العمود الثاني: [2 5 8]
data = np.array([1.2, -0.5, 3.1, -1.8])
positive = data[data > 0] # [1.2 3.1]
a = np.array([1, 2, 3, 4])
b = np.array([10, 20, 30, 40])
print(a + b) # [11 22 33 44]
print(a * b) # [10 40 90 160]
data = np.array([85, 92, 78, 96, 88])
print(f"المتوسط: {data.mean():.1f}")
print(f"الانحراف: {data.std():.1f}")
W = np.random.randn(4, 3) # أوزان طبقة
x = np.random.randn(3) # مدخل
output = W @ x # (4,)
# ─── NumPy في تطبيقات AI حقيقية ───
import numpy as np
np.random.seed(42)
print("=" * 45)
print(" محاكاة طبقة شبكة عصبية بـ NumPy")
print("=" * 45)
# 1. تمثيل بيانات الصور
images = np.random.rand(8, 4, 4, 1)
print(f"
الشكل الأصلي : {images.shape}")
flat = images.reshape(8, -1)
print(f"بعد Flatten : {flat.shape} ({flat.shape[1]} ميزة)")
# 2. تطبيع البيانات
images_norm = (images - images.mean()) / (images.std() + 1e-8)
print(f"
قبل التطبيع — mean={images.mean():.3f} | std={images.std():.3f}")
print(f"بعد التطبيع — mean={images_norm.mean():.3f} | std={images_norm.std():.3f}")
# 3. طبقة Dense بسيطة
input_size, hidden_size = 16, 8
W = np.random.randn(input_size, hidden_size) * 0.1
b = np.zeros(hidden_size)
X = flat
Z = X @ W + b # (8,16) @ (16,8) → (8,8)
A = np.maximum(0, Z) # ReLU
print(f"
المدخل : {X.shape}")
print(f"الأوزان : {W.shape}")
print(f"الخرج Z : {Z.shape}")
print(f"بعد ReLU: {A.shape}")
# 4. إحصاء
per_sample_mean = A.mean(axis=1)
print(f"
متوسط تفعيل كل عينة: {np.round(per_sample_mean, 3)}")
# 5. Boolean indexing
scores = np.random.rand(20) * 100
passed = scores[scores >= 60]
print(f"
عدد الناجحين: {len(passed)}/20")
print(f"متوسط درجات الناجحين: {passed.mean():.1f}")