Loading
Loading
عمليات المصفوفات هي التحويلات الحسابية الأساسية التي تُنفَّذ في كل طبقة من طبقات الشبكة العصبية.
كل Layer في Neural Network هو: output = activation(input @ W + b) حيث W هي أوزان المصفوفة وb هو التحيز (bias)
في NumPy وPyTorch، يمكن جمع مصفوفة 100×4 مع متجه 4 تلقائياً (تُكرَّر أفقياً). هذا يجعل إضافة التحيز للدفعات فعّالاً جداً.
import math
from typing import List, Optional
class Matrix:
def __init__(self, data: List[List[float]]):
self.data = data
self.rows = len(data)
self.cols = len(data[0]) if data else 0
@classmethod
def zeros(cls, r: int, c: int) -> "Matrix":
return cls([[0.0]*c for _ in range(r)])
def transpose(self) -> "Matrix":
return Matrix([[self.data[r][c] for r in range(self.rows)]
for c in range(self.cols)])
def matmul(self, B: "Matrix") -> "Matrix":
C = Matrix.zeros(self.rows, B.cols)
for i in range(self.rows):
for j in range(B.cols):
C.data[i][j] = sum(self.data[i][k]*B.data[k][j]
for k in range(self.cols))
return C
def det2(self) -> float:
assert self.rows == self.cols == 2
return self.data[0][0]*self.data[1][1] - self.data[0][1]*self.data[1][0]
def inverse2(self) -> "Matrix":
d = self.det2()
assert abs(d) > 1e-10, "المصفوفة منفردة (singular) — لا معكوس لها"
return Matrix([[ self.data[1][1]/d, -self.data[0][1]/d],
[-self.data[1][0]/d, self.data[0][0]/d]])
def add_bias(self, bias: List[float]) -> "Matrix":
"""Broadcasting: إضافة متجه تحيز لكل صف"""
return Matrix([[self.data[i][j] + bias[j]
for j in range(self.cols)]
for i in range(self.rows)])
def apply(self, fn) -> "Matrix":
return Matrix([[fn(x) for x in row] for row in self.data])
def show(self, label: str = ""):
shape = f"{self.rows}×{self.cols}"
if label: print(f"\n{label} ({shape}):")
for row in self.data:
cells = " ".join(f"{x:7.3f}" for x in row)
print(f" [ {cells} ]")
# ─── عمليات أساسية ─────────────────────────────────────────
print("📊 عمليات المصفوفات:")
print("=" * 50)
A = Matrix([[1, 2, 3], [4, 5, 6]])
B = Matrix([[7, 8], [9, 10], [11, 12]])
A.show("A (2×3)")
B.show("B (3×2)")
C = A.matmul(B)
C.show("A @ B = C (2×2)")
AT = A.transpose()
AT.show("Aᵀ (3×2)")
# المعكوسة
print(f"\n🔄 المعكوسة (Inverse) وتطبيقها:")
M = Matrix([[4.0, 7.0], [2.0, 6.0]])
MI = M.inverse2()
I = M.matmul(MI)
M.show("M")
MI.show("M⁻¹")
I.show("M @ M⁻¹ ≈ Identity")
det_str = f"{M.det2():.2f}"
print(f" det(M) = {det_str}")
# ─── Forward Pass في Neural Network ───────────────────────
print(f"\n\n🧠 Forward Pass — Neural Network Layer:")
print("-" * 48)
def relu(x: float) -> float: return max(0.0, x)
def sigmoid(x: float) -> float: return 1 / (1 + math.exp(-x))
# Batch: 4 عينات، 3 ميزات
X = Matrix([[0.9, 0.1, 0.8],
[0.2, 0.7, 0.4],
[0.5, 0.5, 0.6],
[0.1, 0.9, 0.2]])
# Layer 1: 3 → 4
W1 = Matrix([[0.2, 0.4, 0.1, 0.3],
[0.5, 0.1, 0.6, 0.2],
[0.3, 0.3, 0.2, 0.4]])
b1 = [0.1, 0.1, 0.1, 0.1]
# Layer 2: 4 → 2
W2 = Matrix([[0.3, 0.7],
[0.5, 0.2],
[0.4, 0.6],
[0.1, 0.8]])
b2 = [0.05, 0.05]
X.show("X — Input batch (4×3)")
Z1 = X.matmul(W1).add_bias(b1)
A1 = Z1.apply(relu)
A1.show("A1 = ReLU(X@W1+b1) (4×4)")
Z2 = A1.matmul(W2).add_bias(b2)
A2 = Z2.apply(sigmoid)
A2.show("Output = σ(A1@W2+b2) (4×2)")
print(f"\n✅ هذا هو Forward Pass في Neural Network!")