trainer.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  1. import os
  2. import time
  3. from datetime import datetime
  4. import cv2
  5. import numpy as np
  6. import torch
  7. from matplotlib import pyplot as plt
  8. from scipy.ndimage import gaussian_filter
  9. from torch.optim.lr_scheduler import ReduceLROnPlateau
  10. from torch.utils.tensorboard import SummaryWriter
  11. from libs.vision_libs.utils import draw_bounding_boxes, draw_keypoints
  12. from models.base.base_model import BaseModel
  13. from models.base.base_trainer import BaseTrainer
  14. from models.config.config_tool import read_yaml
  15. from models.line_detect.line_dataset import LineDataset
  16. from models.line_net.dataset_LD import WirePointDataset
  17. from models.wirenet.postprocess import postprocess
  18. from tools import utils
  19. from torchvision import transforms
  20. import matplotlib as mpl
  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. import matplotlib.pyplot as plt
  41. from PIL import ImageDraw
  42. from torchvision.transforms import functional as F
  43. import torch
  44. def fit_circle(points):
  45. """
  46. Fit a circle to a set of points (at least 3).
  47. Args:
  48. points: torch.Tensor 或 numpy array, shape (N, 2)
  49. Returns:
  50. center (cx, cy), radius r
  51. """
  52. # 如果是 torch.Tensor,先转为 numpy
  53. if isinstance(points, torch.Tensor):
  54. if points.dim() == 3:
  55. points = points[0] # 去掉 batch 维度
  56. points = points.detach().cpu().numpy()
  57. if not (isinstance(points, np.ndarray) and points.ndim == 2 and points.shape[1] == 2):
  58. raise ValueError(f"Expected points shape (N, 2), got {points.shape}")
  59. x = points[:, 0].astype(float)
  60. y = points[:, 1].astype(float)
  61. # 确保 A 是二维数组
  62. A = np.column_stack((x, y, np.ones_like(x))) # 使用 column_stack 代替 stack 可能更清晰
  63. b = -(x ** 2 + y ** 2)
  64. try:
  65. sol, residuals, rank, s = np.linalg.lstsq(A, b, rcond=None)
  66. except np.linalg.LinAlgError as e:
  67. print(f"Linear algebra error occurred: {e}")
  68. raise ValueError("Could not fit circle to points.")
  69. D, E, F = sol
  70. cx = -D / 2.0
  71. cy = -E / 2.0
  72. r = np.sqrt(cx ** 2 + cy ** 2 - F)
  73. return (cx, cy), r
  74. # 由低到高蓝黄红
  75. def draw_lines_with_scores(tensor_image, lines, scores, width=3, cmap='viridis'):
  76. """
  77. 根据得分对线段着色并绘制
  78. :param tensor_image: (3, H, W) uint8 图像
  79. :param lines: (N, 2, 2) 每条线 [ [x1,y1], [x2,y2] ]
  80. :param scores: (N,) 每条线的得分,范围 [0, 1]
  81. :param width: 线宽
  82. :param cmap: matplotlib colormap 名称,例如 'viridis', 'jet', 'coolwarm'
  83. :return: (3, H, W) uint8 画好线的图像
  84. """
  85. assert tensor_image.dtype == torch.uint8
  86. assert tensor_image.shape[0] == 3
  87. assert lines.shape[0] == scores.shape[0]
  88. # 准备色图
  89. colormap = plt.get_cmap(cmap)
  90. colors = (colormap(scores.cpu().numpy())[:, :3] * 255).astype('uint8') # 去掉 alpha 通道
  91. # 转为 PIL 画图
  92. image_pil = F.to_pil_image(tensor_image)
  93. draw = ImageDraw.Draw(image_pil)
  94. for line, color in zip(lines, colors):
  95. start = tuple(map(float, line[0][:2].tolist()))
  96. end = tuple(map(float, line[1][:2].tolist()))
  97. draw.line([start, end], fill=tuple(color), width=width)
  98. return (F.to_tensor(image_pil) * 255).to(torch.uint8)
  99. class Trainer(BaseTrainer):
  100. def __init__(self, model=None, **kwargs):
  101. super().__init__(model, device, **kwargs)
  102. self.model = model
  103. # print(f'kwargs:{kwargs}')
  104. self.init_params(**kwargs)
  105. def init_params(self, **kwargs):
  106. if kwargs != {}:
  107. print(f'train_params:{kwargs["train_params"]}')
  108. self.freeze_config = kwargs['train_params']['freeze_params']
  109. print(f'freeze_config:{self.freeze_config}')
  110. self.dataset_path = kwargs['io']['datadir']
  111. self.data_type = kwargs['io']['data_type']
  112. self.batch_size = kwargs['train_params']['batch_size']
  113. self.num_workers = kwargs['train_params']['num_workers']
  114. self.logdir = kwargs['io']['logdir']
  115. self.resume_from = kwargs['train_params']['resume_from']
  116. self.optim = ''
  117. self.train_result_ptath = os.path.join(self.logdir, datetime.now().strftime("%Y%m%d_%H%M%S"))
  118. self.wts_path = os.path.join(self.train_result_ptath, 'weights')
  119. self.tb_path = os.path.join(self.train_result_ptath, 'logs')
  120. self.writer = SummaryWriter(self.tb_path)
  121. self.last_model_path = os.path.join(self.wts_path, 'last.pth')
  122. self.best_train_model_path = os.path.join(self.wts_path, 'best_train.pth')
  123. self.best_val_model_path = os.path.join(self.wts_path, 'best_val.pth')
  124. self.max_epoch = kwargs['train_params']['max_epoch']
  125. self.augmentation= kwargs['train_params']["augmentation"]
  126. def move_to_device(self, data, device):
  127. if isinstance(data, (list, tuple)):
  128. return type(data)(self.move_to_device(item, device) for item in data)
  129. elif isinstance(data, dict):
  130. return {key: self.move_to_device(value, device) for key, value in data.items()}
  131. elif isinstance(data, torch.Tensor):
  132. return data.to(device)
  133. else:
  134. return data # 对于非张量类型的数据不做任何改变
  135. def freeze_params(self, model):
  136. """根据配置冻结模型参数"""
  137. default_config = {
  138. 'backbone': True, # 冻结 backbone
  139. 'rpn': False, # 不冻结 rpn
  140. 'roi_heads': {
  141. 'box_head': False,
  142. 'box_predictor': False,
  143. 'line_head': False,
  144. 'line_predictor': {
  145. 'fc1': False,
  146. 'fc2': {
  147. '0': False,
  148. '2': False,
  149. '4': False
  150. }
  151. }
  152. }
  153. }
  154. # 更新默认配置
  155. default_config.update(self.freeze_config)
  156. config = default_config
  157. print("\n===== Parameter Freezing Configuration =====")
  158. for name, module in model.named_children():
  159. if name in config:
  160. if isinstance(config[name], bool):
  161. for param in module.parameters():
  162. param.requires_grad = not config[name]
  163. print(f"{'Frozen' if config[name] else 'Trainable'} module: {name}")
  164. elif isinstance(config[name], dict):
  165. for subname, submodule in module.named_children():
  166. if subname in config[name]:
  167. if isinstance(config[name][subname], bool):
  168. for param in submodule.parameters():
  169. param.requires_grad = not config[name][subname]
  170. print(
  171. f"{'Frozen' if config[name][subname] else 'Trainable'} submodule: {name}.{subname}")
  172. elif isinstance(config[name][subname], dict):
  173. for subsubname, subsubmodule in submodule.named_children():
  174. if subsubname in config[name][subname]:
  175. for param in subsubmodule.parameters():
  176. param.requires_grad = not config[name][subname][subsubname]
  177. print(
  178. f"{'Frozen' if config[name][subname][subsubname] else 'Trainable'} sub-submodule: {name}.{subname}.{subsubname}")
  179. # 打印参数统计
  180. total_params = sum(p.numel() for p in model.parameters())
  181. trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
  182. print(f"\nTotal Parameters: {total_params:,}")
  183. print(f"Trainable Parameters: {trainable_params:,}")
  184. print(f"Frozen Parameters: {total_params - trainable_params:,}")
  185. def load_best_model(self, model, optimizer, save_path, device):
  186. if os.path.exists(save_path):
  187. checkpoint = torch.load(save_path, map_location=device)
  188. model.load_state_dict(checkpoint['model_state_dict'])
  189. if optimizer is not None:
  190. optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
  191. epoch = checkpoint['epoch']
  192. loss = checkpoint['loss']
  193. print(f"Loaded best model from {save_path} at epoch {epoch} with loss {loss:.4f}")
  194. else:
  195. print(f"No saved model found at {save_path}")
  196. return model, optimizer
  197. def writer_predict_result(self, img, result, epoch,):
  198. img = img.cpu().detach()
  199. im = img.permute(1, 2, 0) # [512, 512, 3]
  200. self.writer.add_image("z-ori", im, epoch, dataformats="HWC")
  201. boxed_image = draw_bounding_boxes((img * 255).to(torch.uint8), result["boxes"],
  202. colors="yellow", width=1)
  203. # plt.imshow(boxed_image.permute(1, 2, 0).detach().cpu().numpy())
  204. # plt.show()
  205. self.writer.add_image("z-obj", boxed_image.permute(1, 2, 0), epoch, dataformats="HWC")
  206. if 'points' in result:
  207. keypoint_img = draw_keypoints(boxed_image, result['points'], colors='red', width=3)
  208. self.writer.add_image("z-output", keypoint_img, epoch)
  209. # print("lines shape:", result['lines'].shape)
  210. if 'lines' in result:
  211. # 用自己写的函数画线段
  212. # line_image = draw_lines(boxed_image, result['lines'], color='red', width=3)
  213. print(f"shape of linescore:{result['lines_scores'].shape}")
  214. scores = result['lines_scores'].mean(dim=1) # shape: [31]
  215. line_image = draw_lines_with_scores((img * 255).to(torch.uint8), result['lines'],scores, width=3, cmap='jet')
  216. self.writer.add_image("z-output_line", line_image.permute(1, 2, 0), epoch, dataformats="HWC")
  217. if 'arcs' in result:
  218. arcs = result['arcs'][0]
  219. # img_rgb = cv2.cvtColor(img_np, cv2.COLOR_BGR2RGB)
  220. # img_tensor =torch.tensor(img_rgb)
  221. # img_tensor = np.transpose(img_tensor)
  222. self.writer.add_image('z-out-arc', arcs, global_step=epoch)
  223. if 'circles' in result:
  224. # points=result['circles']
  225. # points=points.squeeze(1)
  226. ppp=result['circles']
  227. bbb=result['boxes']
  228. print(f'boxes shape:{bbb.shape}')
  229. print(f'ppp:{ppp.shape}')
  230. points = result['circles']
  231. points = points.squeeze(1)
  232. print(f'points shape:{points.shape}')
  233. features = result['features']
  234. circle_image = img.cpu().numpy().transpose((1, 2, 0)) # CHW -> HWC
  235. circle_image = (circle_image * 255).clip(0, 255).astype(np.uint8)
  236. sum_mask = points.sum(dim=0, keepdim=True)
  237. sum_mask = sum_mask / (sum_mask.max() + 1e-8)
  238. # if isinstance(points, torch.Tensor):
  239. # points = points.cpu().numpy()
  240. #
  241. # for point_set in points:
  242. # center, radius = fit_circle(point_set)
  243. # cx, cy = map(int, center)
  244. #
  245. # circle_image = cv2.circle(circle_image, (cx, cy), int(radius), (0, 0, 255), 2)
  246. #
  247. # for point in point_set:
  248. # px, py = map(int, point)
  249. # circle_image = cv2.circle(circle_image, (px, py), 3, (0, 255, 255), -1)
  250. #
  251. # img_rgb = cv2.cvtColor(circle_image, cv2.COLOR_BGR2RGB)
  252. # img_tensor = img_rgb.transpose((2, 0, 1)) # HWC -> CHW
  253. # img_tensor = img_tensor / 255.0 # 归一化到 [0, 1]
  254. # keypoint_img = draw_keypoints((img * 255).to(torch.uint8), points, colors='red', width=3)
  255. self.writer.add_image('z-out-circle', sum_mask.squeeze(0), global_step=epoch)
  256. features=self.apply_gaussian_blur_to_tensor(features,sigma=3)
  257. self.writer.add_image('z-feature', features, global_step=epoch)
  258. # cv2.imshow('arc', img_rgb)
  259. # cv2.waitKey(1000000)
  260. def normalize_tensor(self,tensor):
  261. """Normalize tensor to [0, 1]"""
  262. min_val = tensor.min()
  263. max_val = tensor.max()
  264. return (tensor - min_val) / (max_val - min_val)
  265. def apply_gaussian_blur_to_tensor(self,feature_map, sigma=3):
  266. """
  267. Apply Gaussian blur to a feature map and convert it into an RGB heatmap.
  268. :param feature_map: Tensor of shape (H, W) or (1, H, W)
  269. :param sigma: Standard deviation for Gaussian kernel
  270. :return: Tensor of shape (3, H, W) representing the RGB heatmap
  271. """
  272. if feature_map.dim() == 3:
  273. if feature_map.shape[0] != 1:
  274. raise ValueError("Only single-channel feature map supported.")
  275. feature_map = feature_map.squeeze(0)
  276. # Normalize to [0, 1]
  277. normalized_feat = self.normalize_tensor(feature_map).cpu().numpy()
  278. # Apply Gaussian blur
  279. blurred_feat = gaussian_filter(normalized_feat, sigma=sigma)
  280. # Convert to colormap (e.g., 'jet')
  281. colormap = plt.get_cmap('jet')
  282. colored = colormap(blurred_feat) # shape: (H, W, 4) RGBA
  283. # Convert to (3, H, W), drop alpha channel
  284. colored_rgb = colored[:, :, :3] # (H, W, 3)
  285. colored_tensor = torch.from_numpy(colored_rgb).permute(2, 0, 1) # (3, H, W)
  286. return colored_tensor.float()
  287. def writer_loss(self, losses, epoch, phase='train'):
  288. try:
  289. for key, value in losses.items():
  290. if key == 'loss_wirepoint':
  291. for subdict in losses['loss_wirepoint']['losses']:
  292. for subkey, subvalue in subdict.items():
  293. self.writer.add_scalar(f'{phase}/loss/{subkey}',
  294. subvalue.item() if hasattr(subvalue, 'item') else subvalue,
  295. epoch)
  296. elif isinstance(value, torch.Tensor):
  297. self.writer.add_scalar(f'{phase}/loss/{key}', value.item(), epoch)
  298. except Exception as e:
  299. print(f"TensorBoard logging error: {e}")
  300. def train_from_cfg(self, model: BaseModel, cfg, freeze_config=None): # 新增:支持传入冻结配置
  301. cfg = read_yaml(cfg)
  302. # print(f'cfg:{cfg}')
  303. # self.freeze_config = freeze_config or {} # 更新冻结配置
  304. self.train(model, **cfg)
  305. def train(self, model, **kwargs):
  306. self.init_params(**kwargs)
  307. dataset_train = LineDataset(dataset_path=self.dataset_path,augmentation=self.augmentation, data_type=self.data_type, dataset_type='train')
  308. dataset_val = LineDataset(dataset_path=self.dataset_path,augmentation=self.augmentation, data_type=self.data_type, dataset_type='val')
  309. train_sampler = torch.utils.data.RandomSampler(dataset_train)
  310. val_sampler = torch.utils.data.RandomSampler(dataset_val)
  311. train_batch_sampler = torch.utils.data.BatchSampler(train_sampler, batch_size=self.batch_size, drop_last=True)
  312. val_batch_sampler = torch.utils.data.BatchSampler(val_sampler, batch_size=self.batch_size, drop_last=True)
  313. train_collate_fn = utils.collate_fn
  314. val_collate_fn = utils.collate_fn
  315. data_loader_train = torch.utils.data.DataLoader(
  316. dataset_train, batch_sampler=train_batch_sampler, num_workers=self.num_workers, collate_fn=train_collate_fn
  317. )
  318. data_loader_val = torch.utils.data.DataLoader(
  319. dataset_val, batch_sampler=val_batch_sampler, num_workers=self.num_workers, collate_fn=val_collate_fn
  320. )
  321. model.to(device)
  322. optimizer = torch.optim.Adam(
  323. filter(lambda p: p.requires_grad, model.parameters()),
  324. lr=kwargs['train_params']['optim']['lr'],
  325. weight_decay=kwargs['train_params']['optim']['weight_decay'],
  326. )
  327. model, optimizer = self.load_best_model(model, optimizer,
  328. r"\\192.168.50.222\share\rlq\weights\250725_arc_res152_best_val.pth",
  329. device)
  330. # scheduler = StepLR(optimizer, step_size=10, gamma=0.1)
  331. scheduler = ReduceLROnPlateau(optimizer, 'min', patience=30)
  332. for epoch in range(self.max_epoch):
  333. print(f"train epoch:{epoch}")
  334. model, epoch_train_loss = self.one_epoch(model, data_loader_train, epoch, optimizer)
  335. scheduler.step(epoch_train_loss)
  336. # ========== Validation ==========
  337. with torch.no_grad():
  338. model, epoch_val_loss = self.one_epoch(model, data_loader_val, epoch, optimizer, phase='val')
  339. scheduler.step(epoch_val_loss)
  340. if epoch==0:
  341. best_train_loss = epoch_train_loss
  342. best_val_loss = epoch_val_loss
  343. self.save_last_model(model,self.last_model_path, epoch, optimizer)
  344. best_train_loss = self.save_best_model(model, self.best_train_model_path, epoch, epoch_train_loss,
  345. best_train_loss,
  346. optimizer)
  347. best_val_loss = self.save_best_model(model, self.best_val_model_path, epoch, epoch_val_loss, best_val_loss,
  348. optimizer)
  349. def one_epoch(self, model, data_loader, epoch, optimizer, phase='train'):
  350. if phase == 'train':
  351. model.train()
  352. if phase == 'val':
  353. model.eval()
  354. total_loss = 0
  355. epoch_step = 0
  356. global_step = epoch * len(data_loader)
  357. for imgs, targets in data_loader:
  358. imgs = self.move_to_device(imgs, device)
  359. targets = self.move_to_device(targets, device)
  360. if phase== 'val':
  361. result,loss_dict = model(imgs, targets)
  362. losses = sum(loss_dict.values())
  363. print(f'val losses:{losses}')
  364. # print(f'val result:{result}')
  365. else:
  366. loss_dict = model(imgs, targets)
  367. losses = sum(loss_dict.values())
  368. print(f'train losses:{losses}')
  369. # loss = _loss(losses)
  370. loss=losses
  371. total_loss += loss.item()
  372. if phase == 'train':
  373. optimizer.zero_grad()
  374. loss.backward()
  375. optimizer.step()
  376. self.writer_loss(loss_dict, global_step, phase=phase)
  377. global_step += 1
  378. if epoch_step == 0 and phase == 'val':
  379. t_start = time.time()
  380. print(f'start to predict:{t_start}')
  381. result = model(self.move_to_device(imgs, self.device))
  382. # print(f'result:{result}')
  383. t_end = time.time()
  384. print(f'predict used:{t_end - t_start}')
  385. self.writer_predict_result(img=imgs[0], result=result[0], epoch=epoch)
  386. epoch_step+=1
  387. avg_loss = total_loss / len(data_loader)
  388. print(f'{phase}/loss epoch{epoch}:{avg_loss:4f}')
  389. self.writer.add_scalar(f'loss/{phase}', avg_loss, epoch)
  390. return model, avg_loss
  391. def save_best_model(self, model, save_path, epoch, current_loss, best_loss, optimizer=None):
  392. os.makedirs(os.path.dirname(save_path), exist_ok=True)
  393. if current_loss <= best_loss:
  394. checkpoint = {
  395. 'epoch': epoch,
  396. 'model_state_dict': model.state_dict(),
  397. 'loss': current_loss
  398. }
  399. if optimizer is not None:
  400. checkpoint['optimizer_state_dict'] = optimizer.state_dict()
  401. torch.save(checkpoint, save_path)
  402. print(f"Saved best model at epoch {epoch} with loss {current_loss:.4f}")
  403. return current_loss
  404. return best_loss
  405. def save_last_model(self, model, save_path, epoch, optimizer=None):
  406. if os.path.exists(f'{self.wts_path}/last.pt'):
  407. os.remove(f'{self.wts_path}/last.pt')
  408. os.makedirs(os.path.dirname(save_path), exist_ok=True)
  409. checkpoint = {
  410. 'epoch': epoch,
  411. 'model_state_dict': model.state_dict(),
  412. }
  413. if optimizer is not None:
  414. checkpoint['optimizer_state_dict'] = optimizer.state_dict()
  415. torch.save(checkpoint, save_path)
  416. if __name__ == '__main__':
  417. print('')