-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrain.py
More file actions
69 lines (52 loc) · 2.14 KB
/
Copy pathtrain.py
File metadata and controls
69 lines (52 loc) · 2.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import os
import torch
from torch.utils.data import DataLoader
from datasets.dataset import PositioningDataset
from models.model import PositioningModel
from utils.transforms import preprocess_image
from utils.visualization import show_sample
# --- Настройки ---
BATCH_SIZE = 4
LEARNING_RATE = 0.001
NUM_EPOCHS = 20
# --- Пути к данным ---
current_dir = os.path.dirname(os.path.abspath(__file__))
excel_path = os.path.join(current_dir, "data", "choords.xlsx")
images_root = os.path.join(current_dir, "data", "images")
# --- Создание датасета ---
dataset = PositioningDataset(images_root)
# --- Создание DataLoader ---
dataloader = DataLoader(dataset, batch_size=BATCH_SIZE, shuffle=True)
# --- Модель ---
model = PositioningModel()
# --- Оптимизатор и функция потерь ---
optimizer = torch.optim.Adam(model.parameters(), lr=LEARNING_RATE)
criterion = torch.nn.MSELoss()
# --- Обучение модели ---
for epoch in range(NUM_EPOCHS):
print(f"Epoch {epoch + 1}/{NUM_EPOCHS}")
for batch_idx, (images, labels) in enumerate(dataloader):
# Перемещаем данные на GPU, если доступен
if torch.cuda.is_available():
images = images.cuda()
labels = labels.cuda()
# Обнуляем градиенты
optimizer.zero_grad()
# Прямое распространение
outputs = model(images)
# Вычисляем ошибку
loss = criterion(outputs, labels)
# Backward pass
loss.backward()
# Обновляем параметры
optimizer.step()
# Выводим прогресс
if batch_idx % 10 == 0:
print(f"Batch {batch_idx}, Loss: {loss.item():.4f}")
# Визуализация примера после каждой эпохи
if torch.cuda.is_available():
images = images.cpu()
labels = labels.cpu()
outputs = outputs.cpu()
show_sample(images[0], labels[0], outputs[0])
print("Обучение завершено!")