Utilizziamo i cookie per migliorare la tua esperienza sul sito
CodeWorlds

PyTorch - podstawy deep learning

PyTorch to framework do deep learning od Facebook AI. Elastyczny i pythonowy!

Instalacja

1pip install torch torchvision

Tensory - podstawowa struktura

1import torch
2
3# Tworzenie tensorów
4tensor = torch.tensor([1, 2, 3, 4, 5])
5matrix = torch.tensor([[1, 2], [3, 4], [5, 6]])
6
7# Specjalne tensory
8zeros = torch.zeros(3, 4)       # Macierz 3x4 zer
9ones = torch.ones(2, 3)         # Macierz 2x3 jedynek
10random = torch.rand(3, 3)       # Losowe 0-1
11randn = torch.randn(3, 3)       # Losowe z rozkładu normalnego
12eye = torch.eye(3)              # Macierz jednostkowa
13
14# Z NumPy
15import numpy as np
16np_array = np.array([1, 2, 3])
17tensor = torch.from_numpy(np_array)
18back_to_numpy = tensor.numpy()
19
20# Atrybuty
21print(tensor.shape)    # rozmiar
22print(tensor.dtype)    # typ danych
23print(tensor.device)   # cpu lub cuda

Operacje na tensorach

1a = torch.tensor([[1, 2], [3, 4]], dtype=torch.float32)
2b = torch.tensor([[5, 6], [7, 8]], dtype=torch.float32)
3
4# Operacje element-wise
5c = a + b       # dodawanie
6c = a * b       # mnożenie
7c = a / b       # dzielenie
8c = a ** 2      # potęgowanie
9
10# Mnożenie macierzowe
11c = a @ b                    # operator @
12c = torch.matmul(a, b)       # funkcja
13c = torch.mm(a, b)           # tylko 2D
14
15# Statystyki
16print(a.sum())          # suma
17print(a.mean())         # średnia
18print(a.std())          # odchylenie std
19print(a.max())          # maximum
20print(a.argmax())       # indeks max
21
22# Reshape
23tensor = torch.arange(12)
24reshaped = tensor.reshape(3, 4)
25reshaped = tensor.view(3, 4)    # wymaga contiguous
26flattened = reshaped.flatten()

GPU acceleration

1# Sprawdź dostępność GPU
2print(torch.cuda.is_available())
3print(torch.cuda.device_count())
4
5# Przenieś tensor na GPU
6device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
7tensor = torch.tensor([1, 2, 3]).to(device)
8
9# Stwórz bezpośrednio na GPU
10tensor_gpu = torch.rand(3, 3, device='cuda')
11
12# Przenieś z powrotem na CPU
13tensor_cpu = tensor_gpu.cpu()

Autograd - automatyczne różniczkowanie

1# Włącz śledzenie gradientów
2x = torch.tensor([2.0], requires_grad=True)
3y = x ** 2 + 3 * x + 1
4
5# Oblicz gradienty
6y.backward()
7print(x.grad)  # dy/dx = 2x + 3 = 7
8
9# Przykład z wieloma zmiennymi
10w = torch.tensor([1.0], requires_grad=True)
11b = torch.tensor([0.0], requires_grad=True)
12
13x = torch.tensor([2.0])
14y_true = torch.tensor([5.0])
15
16# Forward pass
17y_pred = w * x + b
18loss = (y_pred - y_true) ** 2
19
20# Backward pass
21loss.backward()
22
23print(f"w.grad: {w.grad}")  # dL/dw
24print(f"b.grad: {b.grad}")  # dL/db

Dataset i DataLoader

1from torch.utils.data import Dataset, DataLoader
2
3# Custom Dataset
4class SafariDataset(Dataset):
5    def __init__(self, X, y):
6        self.X = torch.tensor(X, dtype=torch.float32)
7        self.y = torch.tensor(y, dtype=torch.long)
8
9    def __len__(self):
10        return len(self.X)
11
12    def __getitem__(self, idx):
13        return self.X[idx], self.y[idx]
14
15# Utwórz dataset
16dataset = SafariDataset(X_train, y_train)
17
18# DataLoader - batching i shuffling
19dataloader = DataLoader(
20    dataset,
21    batch_size=32,
22    shuffle=True,
23    num_workers=4
24)
25
26# Iteruj po batchach
27for batch_X, batch_y in dataloader:
28    print(batch_X.shape, batch_y.shape)
29    break
Vai a CodeWorlds