trainer.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672
  1. import os
  2. import time
  3. from datetime import datetime
  4. import cv2
  5. import numpy as np
  6. import torch
  7. from PIL.ImageDraw import ImageDraw
  8. from matplotlib import pyplot as plt
  9. from scipy.ndimage import gaussian_filter
  10. from torch.optim.lr_scheduler import ReduceLROnPlateau
  11. from torch.utils.tensorboard import SummaryWriter
  12. from libs.vision_libs.utils import draw_bounding_boxes, draw_keypoints
  13. from models.base.base_model import BaseModel
  14. from models.base.base_trainer import BaseTrainer
  15. from models.config.config_tool import read_yaml
  16. from models.line_detect.line_dataset import LineDataset
  17. import torch.nn.functional as F
  18. from tools import utils
  19. import matplotlib as mpl
  20. from utils.data_process.show_prams import print_params
  21. cmap = plt.get_cmap("jet")
  22. norm = mpl.colors.Normalize(vmin=0.4, vmax=1.0)
  23. sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)
  24. sm.set_array([])
  25. def _loss(losses):
  26. total_loss = 0
  27. for i in losses.keys():
  28. if i != "loss_wirepoint":
  29. total_loss += losses[i]
  30. else:
  31. loss_labels = losses[i]["losses"]
  32. loss_labels_k = list(loss_labels[0].keys())
  33. for j, name in enumerate(loss_labels_k):
  34. loss = loss_labels[0][name].mean()
  35. total_loss += loss
  36. return total_loss
  37. def c(x):
  38. return sm.to_rgba(x)
  39. device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
  40. def draw_ellipses_on_image(image, masks_pred, threshold=0.5, color=(0, 255, 0), thickness=2):
  41. """
  42. 在单张原始图像上绘制从 masks 拟合出的椭圆。
  43. 自动将 masks resize 到 image 的空间尺寸。
  44. Args:
  45. image: Tensor [3, H_img, W_img] —— 原始图像(如 [3, 2000, 2000])
  46. masks_pred: Tensor [N, 1, H_mask, W_mask] or [N, H_mask, W_mask] —— 模型输出 mask(如 [2, 1, 672, 672])
  47. threshold: 二值化阈值
  48. color: BGR color for OpenCV
  49. thickness: ellipse line thickness
  50. Returns:
  51. drawn_image: numpy array [H_img, W_img, 3] in RGB
  52. """
  53. # Step 1: 标准化 masks_pred to [N, H, W]
  54. if masks_pred.ndim == 4:
  55. if masks_pred.shape[1] == 1:
  56. masks_pred = masks_pred.squeeze(1) # [N, 1, H, W] -> [N, H, W]
  57. else:
  58. raise ValueError(f"Expected channel=1 in masks_pred, got shape {masks_pred.shape}")
  59. elif masks_pred.ndim != 3:
  60. raise ValueError(f"masks_pred must be 3D (N, H, W) or 4D (N, 1, H, W), got {masks_pred.shape}")
  61. N, H_mask, W_mask = masks_pred.shape
  62. C, H_img, W_img = image.shape
  63. # Step 2: Resize masks to original image size using bilinear interpolation
  64. masks_resized = F.interpolate(
  65. masks_pred.unsqueeze(1).float(), # [N, 1, H_mask, W_mask]
  66. size=(H_img, W_img),
  67. mode='bilinear',
  68. align_corners=False
  69. ).squeeze(1) # [N, H_img, W_img]
  70. # Step 3: Convert image to numpy RGB
  71. img_tensor = image.detach().cpu()
  72. if img_tensor.max() <= 1.0:
  73. img_np = (img_tensor * 255).byte().numpy() # [3, H, W]
  74. else:
  75. img_np = img_tensor.byte().numpy()
  76. img_rgb = np.transpose(img_np, (1, 2, 0)) # [H, W, 3]
  77. img_out = img_rgb.copy()
  78. # Step 4: Process each mask
  79. for mask in masks_resized:
  80. mask_cpu = mask.detach().cpu()
  81. mask_prob = torch.sigmoid(mask_cpu) if mask_cpu.min() < 0 else mask_cpu
  82. binary = (mask_prob > threshold).numpy().astype(np.uint8) * 255 # [H_img, W_img]
  83. contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  84. if contours:
  85. largest_contour = max(contours, key=cv2.contourArea)
  86. if len(largest_contour) >= 5:
  87. try:
  88. ellipse = cv2.fitEllipse(largest_contour)
  89. img_bgr = cv2.cvtColor(img_out, cv2.COLOR_RGB2BGR)
  90. cv2.ellipse(img_bgr, ellipse, color=color, thickness=thickness)
  91. img_out = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)
  92. except cv2.error as e:
  93. print(f"Warning: Failed to fit ellipse: {e}")
  94. return img_out
  95. def fit_circle(points):
  96. """
  97. Fit a circle to a set of points (at least 3).
  98. Args:
  99. points: torch.Tensor 或 numpy array, shape (N, 2)
  100. Returns:
  101. center (cx, cy), radius r
  102. """
  103. # 如果是 torch.Tensor,先转为 numpy
  104. if isinstance(points, torch.Tensor):
  105. if points.dim() == 3:
  106. points = points[0] # 去掉 batch 维度
  107. points = points.detach().cpu().numpy()
  108. if not (isinstance(points, np.ndarray) and points.ndim == 2 and points.shape[1] == 2):
  109. raise ValueError(f"Expected points shape (N, 2), got {points.shape}")
  110. x = points[:, 0].astype(float)
  111. y = points[:, 1].astype(float)
  112. # 确保 A 是二维数组
  113. A = np.column_stack((x, y, np.ones_like(x))) # 使用 column_stack 代替 stack 可能更清晰
  114. b = -(x ** 2 + y ** 2)
  115. try:
  116. sol, residuals, rank, s = np.linalg.lstsq(A, b, rcond=None)
  117. except np.linalg.LinAlgError as e:
  118. print(f"Linear algebra error occurred: {e}")
  119. raise ValueError("Could not fit circle to points.")
  120. D, E, F = sol
  121. cx = -D / 2.0
  122. cy = -E / 2.0
  123. r = np.sqrt(cx ** 2 + cy ** 2 - F)
  124. return (cx, cy), r
  125. from PIL import ImageDraw, Image
  126. import io
  127. def draw_el(all, background_img):
  128. """
  129. all = [x_center, y_center, a, b, theta, x1, y1, x2, y2]
  130. theta: ellipse rotation (degrees)
  131. (x1, y1): start point
  132. (x2, y2): end point
  133. """
  134. if isinstance(all, torch.Tensor):
  135. all = all.cpu().numpy()
  136. # Unpack parameters
  137. cx, cy, a, b, theta_deg, x1, y1, x2, y2 = all
  138. theta = np.radians(theta_deg)
  139. # ====== Draw ellipse ======
  140. phi = np.linspace(0, np.pi * 2, 500)
  141. x_ellipse = cx + a * np.cos(phi) * np.cos(theta) - b * np.sin(phi) * np.sin(theta)
  142. y_ellipse = cy + a * np.cos(phi) * np.sin(theta) + b * np.sin(phi) * np.cos(theta)
  143. # ====== Draw image ======
  144. plt.figure(figsize=(10, 10))
  145. plt.imshow(background_img)
  146. # Ellipse
  147. plt.plot(x_ellipse, y_ellipse, 'b-', linewidth=2)
  148. # Center
  149. plt.plot(cx, cy, 'ko', markersize=8)
  150. # Start & End points (now real coordinates)
  151. plt.plot(x1, y1, 'ro', markersize=10)
  152. plt.plot(x2, y2, 'go', markersize=10)
  153. # ====== Convert to tensor ======
  154. buf = io.BytesIO()
  155. plt.savefig(buf, format='png', bbox_inches='tight')
  156. buf.seek(0)
  157. result_img = Image.open(buf).convert('RGB')
  158. img_tensor = torch.from_numpy(np.array(result_img)).permute(2, 0, 1)
  159. plt.close()
  160. return img_tensor
  161. # from PIL import ImageDraw, Image
  162. # import io
  163. # # 绘制椭圆
  164. # def draw_el(all, background_img):
  165. # # 解析椭圆参数
  166. # if isinstance(all, torch.Tensor):
  167. # all = all.cpu().numpy()
  168. # print_params(all)
  169. # x, y, a, b, q, q1, q2 = all
  170. # theta = np.radians(q)
  171. # phi1 = np.radians(q1) # 第一个点的参数角
  172. # phi2 = np.radians(q2) # 第二个点的参数角
  173. #
  174. # # 生成椭圆上的点
  175. # phi = np.linspace(0, 2 * np.pi, 500)
  176. # x_ellipse = x + a * np.cos(phi) * np.cos(theta) - b * np.sin(phi) * np.sin(theta)
  177. # y_ellipse = y + a * np.cos(phi) * np.sin(theta) + b * np.sin(phi) * np.cos(theta)
  178. #
  179. # # 计算两个指定点的坐标
  180. # def param_to_point(phi, xc, yc, a, b, theta):
  181. # x = xc + a * np.cos(phi) * np.cos(theta) - b * np.sin(phi) * np.sin(theta)
  182. # y = yc + a * np.cos(phi) * np.sin(theta) + b * np.sin(phi) * np.cos(theta)
  183. # return x, y
  184. #
  185. # P1 = param_to_point(phi1, x, y, a, b, theta)
  186. # P2 = param_to_point(phi2, x, y, a, b, theta)
  187. #
  188. # # 创建画布并显示背景图片(使用传入的background_img,shape为[H, W, C])
  189. # plt.figure(figsize=(10, 10))
  190. # plt.imshow(background_img) # 直接显示背景图
  191. #
  192. # # 绘制椭圆及相关元素
  193. # plt.plot(x_ellipse, y_ellipse, 'b-', linewidth=2)
  194. # plt.plot(x, y, 'ko', markersize=8)
  195. # plt.plot(P1[0], P1[1], 'ro', markersize=10)
  196. # plt.plot(P2[0], P2[1], 'go', markersize=10)
  197. # 转换为TensorBoard所需的张量格式 [C, H, W]
  198. # buf = io.BytesIO()
  199. # plt.savefig(buf, format='png', bbox_inches='tight')
  200. # buf.seek(0)
  201. # result_img = Image.open(buf).convert('RGB')
  202. # img_tensor = torch.from_numpy(np.array(result_img)).permute(2, 0, 1)
  203. # plt.close()
  204. #
  205. # return img_tensor
  206. # 由低到高蓝黄红
  207. def draw_lines_with_scores(tensor_image, lines, scores, width=3, cmap='viridis'):
  208. """
  209. 根据得分对线段着色并绘制
  210. :param tensor_image: (3, H, W) uint8 图像
  211. :param lines: (N, 2, 2) 每条线 [ [x1,y1], [x2,y2] ]
  212. :param scores: (N,) 每条线的得分,范围 [0, 1]
  213. :param width: 线宽
  214. :param cmap: matplotlib colormap 名称,例如 'viridis', 'jet', 'coolwarm'
  215. :return: (3, H, W) uint8 画好线的图像
  216. """
  217. assert tensor_image.dtype == torch.uint8
  218. assert tensor_image.shape[0] == 3
  219. assert lines.shape[0] == scores.shape[0]
  220. # 准备色图
  221. colormap = plt.get_cmap(cmap)
  222. colors = (colormap(scores.cpu().numpy())[:, :3] * 255).astype('uint8') # 去掉 alpha 通道
  223. # 转为 PIL 画图
  224. image_pil = F.to_pil_image(tensor_image)
  225. draw = ImageDraw.Draw(image_pil)
  226. for line, color in zip(lines, colors):
  227. start = tuple(map(float, line[0][:2].tolist()))
  228. end = tuple(map(float, line[1][:2].tolist()))
  229. draw.line([start, end], fill=tuple(color), width=width)
  230. return (F.to_tensor(image_pil) * 255).to(torch.uint8)
  231. class Trainer(BaseTrainer):
  232. def __init__(self, model=None, **kwargs):
  233. super().__init__(model, device, **kwargs)
  234. self.model = model
  235. # print(f'kwargs:{kwargs}')
  236. self.init_params(**kwargs)
  237. def init_params(self, **kwargs):
  238. if kwargs != {}:
  239. print(f'train_params:{kwargs["train_params"]}')
  240. self.freeze_config = kwargs['train_params']['freeze_params']
  241. print(f'freeze_config:{self.freeze_config}')
  242. self.dataset_path = kwargs['io']['datadir']
  243. self.data_type = kwargs['io']['data_type']
  244. self.batch_size = kwargs['train_params']['batch_size']
  245. self.num_workers = kwargs['train_params']['num_workers']
  246. self.logdir = kwargs['io']['logdir']
  247. self.resume_from = kwargs['train_params']['resume_from']
  248. self.optim = ''
  249. self.train_result_ptath = os.path.join(self.logdir, datetime.now().strftime("%Y%m%d_%H%M%S"))
  250. self.wts_path = os.path.join(self.train_result_ptath, 'weights')
  251. self.tb_path = os.path.join(self.train_result_ptath, 'logs')
  252. self.writer = SummaryWriter(self.tb_path)
  253. self.last_model_path = os.path.join(self.wts_path, 'last.pth')
  254. self.best_train_model_path = os.path.join(self.wts_path, 'best_train.pth')
  255. self.best_val_model_path = os.path.join(self.wts_path, 'best_val.pth')
  256. self.max_epoch = kwargs['train_params']['max_epoch']
  257. self.augmentation= kwargs['train_params']["augmentation"]
  258. def move_to_device(self, data, device):
  259. if isinstance(data, (list, tuple)):
  260. return type(data)(self.move_to_device(item, device) for item in data)
  261. elif isinstance(data, dict):
  262. return {key: self.move_to_device(value, device) for key, value in data.items()}
  263. elif isinstance(data, torch.Tensor):
  264. return data.to(device)
  265. else:
  266. return data # 对于非张量类型的数据不做任何改变
  267. def freeze_params(self, model):
  268. """根据配置冻结模型参数"""
  269. default_config = {
  270. 'backbone': True, # 冻结 backbone
  271. 'rpn': False, # 不冻结 rpn
  272. 'roi_heads': {
  273. 'box_head': False,
  274. 'box_predictor': False,
  275. 'line_head': False,
  276. 'line_predictor': {
  277. 'fc1': False,
  278. 'fc2': {
  279. '0': False,
  280. '2': False,
  281. '4': False
  282. }
  283. }
  284. }
  285. }
  286. # 更新默认配置
  287. default_config.update(self.freeze_config)
  288. config = default_config
  289. print("\n===== Parameter Freezing Configuration =====")
  290. for name, module in model.named_children():
  291. if name in config:
  292. if isinstance(config[name], bool):
  293. for param in module.parameters():
  294. param.requires_grad = not config[name]
  295. print(f"{'Frozen' if config[name] else 'Trainable'} module: {name}")
  296. elif isinstance(config[name], dict):
  297. for subname, submodule in module.named_children():
  298. if subname in config[name]:
  299. if isinstance(config[name][subname], bool):
  300. for param in submodule.parameters():
  301. param.requires_grad = not config[name][subname]
  302. print(
  303. f"{'Frozen' if config[name][subname] else 'Trainable'} submodule: {name}.{subname}")
  304. elif isinstance(config[name][subname], dict):
  305. for subsubname, subsubmodule in submodule.named_children():
  306. if subsubname in config[name][subname]:
  307. for param in subsubmodule.parameters():
  308. param.requires_grad = not config[name][subname][subsubname]
  309. print(
  310. f"{'Frozen' if config[name][subname][subsubname] else 'Trainable'} sub-submodule: {name}.{subname}.{subsubname}")
  311. # 打印参数统计
  312. total_params = sum(p.numel() for p in model.parameters())
  313. trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
  314. print(f"\nTotal Parameters: {total_params:,}")
  315. print(f"Trainable Parameters: {trainable_params:,}")
  316. print(f"Frozen Parameters: {total_params - trainable_params:,}")
  317. def load_best_model(self, model, optimizer, save_path, device):
  318. if os.path.exists(save_path):
  319. checkpoint = torch.load(save_path, map_location=device)
  320. model.load_state_dict(checkpoint['model_state_dict'])
  321. if optimizer is not None:
  322. optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
  323. epoch = checkpoint['epoch']
  324. loss = checkpoint['loss']
  325. print(f"Loaded best model from {save_path} at epoch {epoch} with loss {loss:.4f}")
  326. else:
  327. print(f"No saved model found at {save_path}")
  328. return model, optimizer
  329. def writer_predict_result(self, img, result, epoch,):
  330. img = img.cpu().detach()
  331. im = img.permute(1, 2, 0) # [512, 512, 3]
  332. self.writer.add_image("z-ori", im, epoch, dataformats="HWC")
  333. boxed_image = draw_bounding_boxes((img * 255).to(torch.uint8), result["boxes"],
  334. colors="yellow", width=1)
  335. # plt.imshow(boxed_image.permute(1, 2, 0).detach().cpu().numpy())
  336. # plt.show()
  337. self.writer.add_image("z-obj", boxed_image.permute(1, 2, 0), epoch, dataformats="HWC")
  338. if 'points' in result:
  339. keypoint_img = draw_keypoints(boxed_image, result['points'], colors='red', width=3)
  340. self.writer.add_image("z-output", keypoint_img, epoch)
  341. # print("lines shape:", result['lines'].shape)
  342. if 'lines' in result:
  343. # 用自己写的函数画线段
  344. # line_image = draw_lines(boxed_image, result['lines'], color='red', width=3)
  345. print(f"shape of linescore:{result['lines_scores'].shape}")
  346. scores = result['lines_scores'].mean(dim=1) # shape: [31]
  347. line_image = draw_lines_with_scores((img * 255).to(torch.uint8), result['lines'],scores, width=3, cmap='jet')
  348. self.writer.add_image("z-output_line", line_image.permute(1, 2, 0), epoch, dataformats="HWC")
  349. if 'arcs' in result:
  350. arcs = result['arcs'][0]
  351. print(f'arcs in dra w:{arcs}')
  352. ellipse_img = draw_el(arcs, background_img=im)
  353. # img_rgb = cv2.cvtColor(img_np, cv2.COLOR_BGR2RGB)
  354. #
  355. # img_tensor =torch.tensor(img_rgb)
  356. # img_tensor = np.transpose(img_tensor)
  357. self.writer.add_image('z-out-arc', ellipse_img, global_step=epoch)
  358. if 'ins_masks' in result:
  359. # points=result['circles']
  360. # points=points.squeeze(1)
  361. ppp=result['ins_masks']
  362. bbb=result['boxes']
  363. print(f'boxes shape:{bbb.shape}')
  364. print(f'ppp:{ppp.shape}')
  365. ins_masks = result['ins_masks']
  366. ins_masks = ins_masks.squeeze(1)
  367. print(f'ins_masks shape:{ins_masks.shape}')
  368. features = result['features']
  369. circle_image = img.cpu().numpy().transpose((1, 2, 0)) # CHW -> HWC
  370. circle_image = (circle_image * 255).clip(0, 255).astype(np.uint8)
  371. sum_mask = ins_masks.sum(dim=0, keepdim=True)
  372. sum_mask = sum_mask / (sum_mask.max() + 1e-8)
  373. # keypoint_img = draw_keypoints((img * 255).to(torch.uint8), points, colors='red', width=3)
  374. self.writer.add_image('z-ins-masks', sum_mask.squeeze(0), global_step=epoch)
  375. result_imgs = draw_ellipses_on_image(img, ins_masks, threshold=0.5)
  376. self.writer.add_image('z-out-ellipses', result_imgs, dataformats='HWC', global_step= epoch)
  377. features=self.apply_gaussian_blur_to_tensor(features,sigma=3)
  378. self.writer.add_image('z-feature', features, global_step=epoch)
  379. # cv2.imshow('arc', img_rgb)
  380. # cv2.waitKey(1000000)
  381. def normalize_tensor(self,tensor):
  382. """Normalize tensor to [0, 1]"""
  383. min_val = tensor.min()
  384. max_val = tensor.max()
  385. return (tensor - min_val) / (max_val - min_val)
  386. def apply_gaussian_blur_to_tensor(self,feature_map, sigma=3):
  387. """
  388. Apply Gaussian blur to a feature map and convert it into an RGB heatmap.
  389. :param feature_map: Tensor of shape (H, W) or (1, H, W)
  390. :param sigma: Standard deviation for Gaussian kernel
  391. :return: Tensor of shape (3, H, W) representing the RGB heatmap
  392. """
  393. if feature_map.dim() == 3:
  394. if feature_map.shape[0] != 1:
  395. raise ValueError("Only single-channel feature map supported.")
  396. feature_map = feature_map.squeeze(0)
  397. # Normalize to [0, 1]
  398. normalized_feat = self.normalize_tensor(feature_map).cpu().numpy()
  399. # Apply Gaussian blur
  400. blurred_feat = gaussian_filter(normalized_feat, sigma=sigma)
  401. # Convert to colormap (e.g., 'jet')
  402. colormap = plt.get_cmap('jet')
  403. colored = colormap(blurred_feat) # shape: (H, W, 4) RGBA
  404. # Convert to (3, H, W), drop alpha channel
  405. colored_rgb = colored[:, :, :3] # (H, W, 3)
  406. colored_tensor = torch.from_numpy(colored_rgb).permute(2, 0, 1) # (3, H, W)
  407. return colored_tensor.float()
  408. def writer_loss(self, losses, epoch, phase='train'):
  409. try:
  410. for key, value in losses.items():
  411. if key == 'loss_wirepoint':
  412. for subdict in losses['loss_wirepoint']['losses']:
  413. for subkey, subvalue in subdict.items():
  414. self.writer.add_scalar(f'{phase}/loss/{subkey}',
  415. subvalue.item() if hasattr(subvalue, 'item') else subvalue,
  416. epoch)
  417. elif isinstance(value, torch.Tensor):
  418. self.writer.add_scalar(f'{phase}/loss/{key}', value.item(), epoch)
  419. except Exception as e:
  420. print(f"TensorBoard logging error: {e}")
  421. def train_from_cfg(self, model: BaseModel, cfg, freeze_config=None): # 新增:支持传入冻结配置
  422. cfg = read_yaml(cfg)
  423. # print(f'cfg:{cfg}')
  424. # self.freeze_config = freeze_config or {} # 更新冻结配置
  425. self.train(model, **cfg)
  426. def train(self, model, **kwargs):
  427. self.init_params(**kwargs)
  428. dataset_train = LineDataset(dataset_path=self.dataset_path,augmentation=self.augmentation, data_type=self.data_type, dataset_type='train')
  429. dataset_val = LineDataset(dataset_path=self.dataset_path,augmentation=self.augmentation, data_type=self.data_type, dataset_type='val')
  430. train_sampler = torch.utils.data.RandomSampler(dataset_train)
  431. val_sampler = torch.utils.data.RandomSampler(dataset_val)
  432. train_batch_sampler = torch.utils.data.BatchSampler(train_sampler, batch_size=self.batch_size, drop_last=True)
  433. val_batch_sampler = torch.utils.data.BatchSampler(val_sampler, batch_size=self.batch_size, drop_last=True)
  434. train_collate_fn = utils.collate_fn
  435. val_collate_fn = utils.collate_fn
  436. data_loader_train = torch.utils.data.DataLoader(
  437. dataset_train, batch_sampler=train_batch_sampler, num_workers=self.num_workers, collate_fn=train_collate_fn
  438. )
  439. data_loader_val = torch.utils.data.DataLoader(
  440. dataset_val, batch_sampler=val_batch_sampler, num_workers=self.num_workers, collate_fn=val_collate_fn
  441. )
  442. model.to(device)
  443. optimizer = torch.optim.Adam(
  444. filter(lambda p: p.requires_grad, model.parameters()),
  445. lr=kwargs['train_params']['optim']['lr'],
  446. weight_decay=kwargs['train_params']['optim']['weight_decay'],
  447. )
  448. model, optimizer = self.load_best_model(model, optimizer,
  449. r"\\192.168.50.222\share\rlq\weights\250725_arc_res152_best_val.pth",
  450. device)
  451. # scheduler = StepLR(optimizer, step_size=10, gamma=0.1)
  452. scheduler = ReduceLROnPlateau(optimizer, 'min', patience=30)
  453. for epoch in range(self.max_epoch):
  454. print(f"train epoch:{epoch}")
  455. model, epoch_train_loss = self.one_epoch(model, data_loader_train, epoch, optimizer)
  456. scheduler.step(epoch_train_loss)
  457. # ========== Validation ==========
  458. with torch.no_grad():
  459. model, epoch_val_loss = self.one_epoch(model, data_loader_val, epoch, optimizer, phase='val')
  460. scheduler.step(epoch_val_loss)
  461. if epoch==0:
  462. best_train_loss = epoch_train_loss
  463. best_val_loss = epoch_val_loss
  464. self.save_last_model(model,self.last_model_path, epoch, optimizer)
  465. best_train_loss = self.save_best_model(model, self.best_train_model_path, epoch, epoch_train_loss,
  466. best_train_loss,
  467. optimizer)
  468. best_val_loss = self.save_best_model(model, self.best_val_model_path, epoch, epoch_val_loss, best_val_loss,
  469. optimizer)
  470. def one_epoch(self, model, data_loader, epoch, optimizer, phase='train'):
  471. if phase == 'train':
  472. model.train()
  473. if phase == 'val':
  474. model.eval()
  475. total_loss = 0
  476. epoch_step = 0
  477. global_step = epoch * len(data_loader)
  478. for imgs, targets in data_loader:
  479. imgs = self.move_to_device(imgs, device)
  480. targets = self.move_to_device(targets, device)
  481. if phase== 'val':
  482. result,loss_dict = model(imgs, targets)
  483. losses = sum(loss_dict.values())
  484. print(f'val losses:{losses}')
  485. # print(f'val result:{result}')
  486. else:
  487. loss_dict = model(imgs, targets)
  488. losses = sum(loss_dict.values())
  489. print(f'train losses:{losses}')
  490. # loss = _loss(losses)
  491. loss=losses
  492. total_loss += loss.item()
  493. if phase == 'train':
  494. optimizer.zero_grad()
  495. loss.backward()
  496. optimizer.step()
  497. self.writer_loss(loss_dict, global_step, phase=phase)
  498. global_step += 1
  499. if epoch_step == 0 and phase == 'val':
  500. t_start = time.time()
  501. print(f'start to predict:{t_start}')
  502. result = model(self.move_to_device(imgs, self.device))
  503. # print(f'result:{result}')
  504. t_end = time.time()
  505. print(f'predict used:{t_end - t_start}')
  506. from utils.data_process.show_prams import print_params
  507. print_params(imgs[0], result[0], epoch)
  508. self.writer_predict_result(img=imgs[0], result=result[0], epoch=epoch)
  509. epoch_step+=1
  510. avg_loss = total_loss / len(data_loader)
  511. print(f'{phase}/loss epoch{epoch}:{avg_loss:4f}')
  512. self.writer.add_scalar(f'loss/{phase}', avg_loss, epoch)
  513. return model, avg_loss
  514. def save_best_model(self, model, save_path, epoch, current_loss, best_loss, optimizer=None):
  515. os.makedirs(os.path.dirname(save_path), exist_ok=True)
  516. if current_loss <= best_loss:
  517. checkpoint = {
  518. 'epoch': epoch,
  519. 'model_state_dict': model.state_dict(),
  520. 'loss': current_loss
  521. }
  522. if optimizer is not None:
  523. checkpoint['optimizer_state_dict'] = optimizer.state_dict()
  524. torch.save(checkpoint, save_path)
  525. print(f"Saved best model at epoch {epoch} with loss {current_loss:.4f}")
  526. return current_loss
  527. return best_loss
  528. def save_last_model(self, model, save_path, epoch, optimizer=None):
  529. if os.path.exists(f'{self.wts_path}/last.pt'):
  530. os.remove(f'{self.wts_path}/last.pt')
  531. os.makedirs(os.path.dirname(save_path), exist_ok=True)
  532. checkpoint = {
  533. 'epoch': epoch,
  534. 'model_state_dict': model.state_dict(),
  535. }
  536. if optimizer is not None:
  537. checkpoint['optimizer_state_dict'] = optimizer.state_dict()
  538. torch.save(checkpoint, save_path)
  539. if __name__ == '__main__':
  540. print('')