الدرس 3 من 8

أساسيات PyTorch

المكتبة اللي بيستخدمها أغلب الباحثين والشركات.

التسطيب

terminal
# CPU version (fine for learning)
pip install torch torchvision

# With an NVIDIA GPU: get the exact command from pytorch.org
# Easiest: use Google Colab -> Runtime -> Change runtime type -> GPU

الـ Tensor = NumPy array بقدرات زيادة

الـ tensor شبه الـ array بالظبط، وكل اللي اتعلمته في NumPy (slicing و shapes و broadcasting) شغال هنا. الفرق إنه يقدر يشتغل على GPU، ويحسب المشتقات لوحده.

tensors.py
import torch

t = torch.tensor([[1.0, 2.0, 3.0],
                  [4.0, 5.0, 6.0]])
print(t.shape, t.dtype)

print(t * 10)                 # element-wise, like NumPy
print(t.sum(dim=0))           # dim = axis in NumPy
print(t @ t.T)                # matrix multiplication

zeros = torch.zeros(2, 3)
rand = torch.rand(2, 3)       # uniform random 0..1
print(rand.shape)

الـ GPU

كارت الشاشة فيه آلاف الأنوية الصغيرة بتعمل ضرب مصفوفات بالتوازي، فبيدرّب الموديلات أسرع بعشرات المرات. بتنقل الـ tensor والموديل ليه بـ .to(device).

device.py
import torch

device = "cuda" if torch.cuda.is_available() else "cpu"
print("Using:", device)          # on Colab with a GPU: cuda

x = torch.rand(1000, 1000).to(device)   # move data to the GPU (if available)
y = x @ x                               # runs on that device
print(y.device)
⚠ لازم كله يبقى على نفس الجهازلو الموديل على الـ GPU والداتا على الـ CPU، هيطلعلك خطأ فيه Expected all tensors to be on the same device. انقل الاتنين بـ .to(device).

الـ Autograd: المشتقات أوتوماتيك

لو قلت للـ tensor requires_grad=True، PyTorch بيسجل كل العمليات اللي حصلت عليه، ولما تنادي .backward() بيحسب المشتقة بالـ chain rule لوحده. فاكر إن مشتقة x² عند 3 كانت 6؟

autograd.py
import torch

x = torch.tensor(3.0, requires_grad=True)
y = x ** 2
y.backward()                 # compute dy/dx
print("dy/dx at x=3:", x.grad.item())

# Works through any chain of operations
w = torch.tensor(2.0, requires_grad=True)
loss = (w * 4 - 10) ** 2     # prediction w*4, target 10
loss.backward()
print("gradient of loss w.r.t. w:", w.grad.item())

الرقم التاني سالب، يعني لو زودنا w الـ loss هيقل. وده صح: 2×4=8 أقل من 10، فمحتاجين w أكبر. كل الـ backpropagation اللي كتبناه بإيدنا في الدرس اللي فات، PyTorch بيعمله كده.

💡 من NumPy ولـ NumPytorch.from_numpy(arr) بتحول array لـ tensor، و t.numpy() العكس. هتحتاجهم كتير لأن الداتا بتيجي من Pandas و NumPy.
الدرس اللي فات