trainer.py 27 KB

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