Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

plots.py 18 KB

You have to be logged in to leave a comment. Sign In
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
  1. # Plotting utils
  2. import glob
  3. import math
  4. import os
  5. import random
  6. from copy import copy
  7. from pathlib import Path
  8. import cv2
  9. import matplotlib
  10. import matplotlib.pyplot as plt
  11. import numpy as np
  12. import pandas as pd
  13. import seaborn as sns
  14. import torch
  15. import yaml
  16. from PIL import Image, ImageDraw, ImageFont
  17. from utils.general import xywh2xyxy, xyxy2xywh
  18. from utils.metrics import fitness
  19. # Settings
  20. matplotlib.rc('font', **{'size': 11})
  21. matplotlib.use('Agg') # for writing to files only
  22. class Colors:
  23. # Ultralytics color palette https://ultralytics.com/
  24. def __init__(self):
  25. self.palette = [self.hex2rgb(c) for c in matplotlib.colors.TABLEAU_COLORS.values()]
  26. self.n = len(self.palette)
  27. def __call__(self, i, bgr=False):
  28. c = self.palette[int(i) % self.n]
  29. return (c[2], c[1], c[0]) if bgr else c
  30. @staticmethod
  31. def hex2rgb(h): # rgb order (PIL)
  32. return tuple(int(h[1 + i:1 + i + 2], 16) for i in (0, 2, 4))
  33. colors = Colors() # create instance for 'from utils.plots import colors'
  34. def hist2d(x, y, n=100):
  35. # 2d histogram used in labels.png and evolve.png
  36. xedges, yedges = np.linspace(x.min(), x.max(), n), np.linspace(y.min(), y.max(), n)
  37. hist, xedges, yedges = np.histogram2d(x, y, (xedges, yedges))
  38. xidx = np.clip(np.digitize(x, xedges) - 1, 0, hist.shape[0] - 1)
  39. yidx = np.clip(np.digitize(y, yedges) - 1, 0, hist.shape[1] - 1)
  40. return np.log(hist[xidx, yidx])
  41. def butter_lowpass_filtfilt(data, cutoff=1500, fs=50000, order=5):
  42. from scipy.signal import butter, filtfilt
  43. # https://stackoverflow.com/questions/28536191/how-to-filter-smooth-with-scipy-numpy
  44. def butter_lowpass(cutoff, fs, order):
  45. nyq = 0.5 * fs
  46. normal_cutoff = cutoff / nyq
  47. return butter(order, normal_cutoff, btype='low', analog=False)
  48. b, a = butter_lowpass(cutoff, fs, order=order)
  49. return filtfilt(b, a, data) # forward-backward filter
  50. def plot_one_box(x, im, color=None, label=None, line_thickness=3):
  51. # Plots one bounding box on image 'im' using OpenCV
  52. assert im.data.contiguous, 'Image not contiguous. Apply np.ascontiguousarray(im) to plot_on_box() input image.'
  53. tl = line_thickness or round(0.002 * (im.shape[0] + im.shape[1]) / 2) + 1 # line/font thickness
  54. color = color or [random.randint(0, 255) for _ in range(3)]
  55. c1, c2 = (int(x[0]), int(x[1])), (int(x[2]), int(x[3]))
  56. cv2.rectangle(im, c1, c2, color, thickness=tl, lineType=cv2.LINE_AA)
  57. if label:
  58. tf = max(tl - 1, 1) # font thickness
  59. t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0]
  60. c2 = c1[0] + t_size[0], c1[1] - t_size[1] - 3
  61. cv2.rectangle(im, c1, c2, color, -1, cv2.LINE_AA) # filled
  62. cv2.putText(im, label, (c1[0], c1[1] - 2), 0, tl / 3, [225, 255, 255], thickness=tf, lineType=cv2.LINE_AA)
  63. def plot_one_box_PIL(box, im, color=None, label=None, line_thickness=None):
  64. # Plots one bounding box on image 'im' using PIL
  65. im = Image.fromarray(im)
  66. draw = ImageDraw.Draw(im)
  67. line_thickness = line_thickness or max(int(min(im.size) / 200), 2)
  68. draw.rectangle(box, width=line_thickness, outline=tuple(color)) # plot
  69. if label:
  70. fontsize = max(round(max(im.size) / 40), 12)
  71. font = ImageFont.truetype("Arial.ttf", fontsize)
  72. txt_width, txt_height = font.getsize(label)
  73. draw.rectangle([box[0], box[1] - txt_height + 4, box[0] + txt_width, box[1]], fill=tuple(color))
  74. draw.text((box[0], box[1] - txt_height + 1), label, fill=(255, 255, 255), font=font)
  75. return np.asarray(im)
  76. def plot_wh_methods(): # from utils.plots import *; plot_wh_methods()
  77. # Compares the two methods for width-height anchor multiplication
  78. # https://github.com/ultralytics/yolov3/issues/168
  79. x = np.arange(-4.0, 4.0, .1)
  80. ya = np.exp(x)
  81. yb = torch.sigmoid(torch.from_numpy(x)).numpy() * 2
  82. fig = plt.figure(figsize=(6, 3), tight_layout=True)
  83. plt.plot(x, ya, '.-', label='YOLOv3')
  84. plt.plot(x, yb ** 2, '.-', label='YOLOv5 ^2')
  85. plt.plot(x, yb ** 1.6, '.-', label='YOLOv5 ^1.6')
  86. plt.xlim(left=-4, right=4)
  87. plt.ylim(bottom=0, top=6)
  88. plt.xlabel('input')
  89. plt.ylabel('output')
  90. plt.grid()
  91. plt.legend()
  92. fig.savefig('comparison.png', dpi=200)
  93. def output_to_target(output):
  94. # Convert model output to target format [batch_id, class_id, x, y, w, h, conf]
  95. targets = []
  96. for i, o in enumerate(output):
  97. for *box, conf, cls in o.cpu().numpy():
  98. targets.append([i, cls, *list(*xyxy2xywh(np.array(box)[None])), conf])
  99. return np.array(targets)
  100. def plot_images(images, targets, paths=None, fname='images.jpg', names=None, max_size=640, max_subplots=16):
  101. # Plot image grid with labels
  102. if isinstance(images, torch.Tensor):
  103. images = images.cpu().float().numpy()
  104. if isinstance(targets, torch.Tensor):
  105. targets = targets.cpu().numpy()
  106. # un-normalise
  107. if np.max(images[0]) <= 1:
  108. images *= 255
  109. tl = 3 # line thickness
  110. tf = max(tl - 1, 1) # font thickness
  111. bs, _, h, w = images.shape # batch size, _, height, width
  112. bs = min(bs, max_subplots) # limit plot images
  113. ns = np.ceil(bs ** 0.5) # number of subplots (square)
  114. # Check if we should resize
  115. scale_factor = max_size / max(h, w)
  116. if scale_factor < 1:
  117. h = math.ceil(scale_factor * h)
  118. w = math.ceil(scale_factor * w)
  119. mosaic = np.full((int(ns * h), int(ns * w), 3), 255, dtype=np.uint8) # init
  120. for i, img in enumerate(images):
  121. if i == max_subplots: # if last batch has fewer images than we expect
  122. break
  123. block_x = int(w * (i // ns))
  124. block_y = int(h * (i % ns))
  125. img = img.transpose(1, 2, 0)
  126. if scale_factor < 1:
  127. img = cv2.resize(img, (w, h))
  128. mosaic[block_y:block_y + h, block_x:block_x + w, :] = img
  129. if len(targets) > 0:
  130. image_targets = targets[targets[:, 0] == i]
  131. boxes = xywh2xyxy(image_targets[:, 2:6]).T
  132. classes = image_targets[:, 1].astype('int')
  133. labels = image_targets.shape[1] == 6 # labels if no conf column
  134. conf = None if labels else image_targets[:, 6] # check for confidence presence (label vs pred)
  135. if boxes.shape[1]:
  136. if boxes.max() <= 1.01: # if normalized with tolerance 0.01
  137. boxes[[0, 2]] *= w # scale to pixels
  138. boxes[[1, 3]] *= h
  139. elif scale_factor < 1: # absolute coords need scale if image scales
  140. boxes *= scale_factor
  141. boxes[[0, 2]] += block_x
  142. boxes[[1, 3]] += block_y
  143. for j, box in enumerate(boxes.T):
  144. cls = int(classes[j])
  145. color = colors(cls)
  146. cls = names[cls] if names else cls
  147. if labels or conf[j] > 0.25: # 0.25 conf thresh
  148. label = '%s' % cls if labels else '%s %.1f' % (cls, conf[j])
  149. plot_one_box(box, mosaic, label=label, color=color, line_thickness=tl)
  150. # Draw image filename labels
  151. if paths:
  152. label = Path(paths[i]).name[:40] # trim to 40 char
  153. t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0]
  154. cv2.putText(mosaic, label, (block_x + 5, block_y + t_size[1] + 5), 0, tl / 3, [220, 220, 220], thickness=tf,
  155. lineType=cv2.LINE_AA)
  156. # Image border
  157. cv2.rectangle(mosaic, (block_x, block_y), (block_x + w, block_y + h), (255, 255, 255), thickness=3)
  158. if fname:
  159. r = min(1280. / max(h, w) / ns, 1.0) # ratio to limit image size
  160. mosaic = cv2.resize(mosaic, (int(ns * w * r), int(ns * h * r)), interpolation=cv2.INTER_AREA)
  161. # cv2.imwrite(fname, cv2.cvtColor(mosaic, cv2.COLOR_BGR2RGB)) # cv2 save
  162. Image.fromarray(mosaic).save(fname) # PIL save
  163. return mosaic
  164. def plot_lr_scheduler(optimizer, scheduler, epochs=300, save_dir=''):
  165. # Plot LR simulating training for full epochs
  166. optimizer, scheduler = copy(optimizer), copy(scheduler) # do not modify originals
  167. y = []
  168. for _ in range(epochs):
  169. scheduler.step()
  170. y.append(optimizer.param_groups[0]['lr'])
  171. plt.plot(y, '.-', label='LR')
  172. plt.xlabel('epoch')
  173. plt.ylabel('LR')
  174. plt.grid()
  175. plt.xlim(0, epochs)
  176. plt.ylim(0)
  177. plt.savefig(Path(save_dir) / 'LR.png', dpi=200)
  178. plt.close()
  179. def plot_test_txt(): # from utils.plots import *; plot_test()
  180. # Plot test.txt histograms
  181. x = np.loadtxt('test.txt', dtype=np.float32)
  182. box = xyxy2xywh(x[:, :4])
  183. cx, cy = box[:, 0], box[:, 1]
  184. fig, ax = plt.subplots(1, 1, figsize=(6, 6), tight_layout=True)
  185. ax.hist2d(cx, cy, bins=600, cmax=10, cmin=0)
  186. ax.set_aspect('equal')
  187. plt.savefig('hist2d.png', dpi=300)
  188. fig, ax = plt.subplots(1, 2, figsize=(12, 6), tight_layout=True)
  189. ax[0].hist(cx, bins=600)
  190. ax[1].hist(cy, bins=600)
  191. plt.savefig('hist1d.png', dpi=200)
  192. def plot_targets_txt(): # from utils.plots import *; plot_targets_txt()
  193. # Plot targets.txt histograms
  194. x = np.loadtxt('targets.txt', dtype=np.float32).T
  195. s = ['x targets', 'y targets', 'width targets', 'height targets']
  196. fig, ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)
  197. ax = ax.ravel()
  198. for i in range(4):
  199. ax[i].hist(x[i], bins=100, label='%.3g +/- %.3g' % (x[i].mean(), x[i].std()))
  200. ax[i].legend()
  201. ax[i].set_title(s[i])
  202. plt.savefig('targets.jpg', dpi=200)
  203. def plot_study_txt(path='', x=None): # from utils.plots import *; plot_study_txt()
  204. # Plot study.txt generated by test.py
  205. fig, ax = plt.subplots(2, 4, figsize=(10, 6), tight_layout=True)
  206. # ax = ax.ravel()
  207. fig2, ax2 = plt.subplots(1, 1, figsize=(8, 4), tight_layout=True)
  208. # for f in [Path(path) / f'study_coco_{x}.txt' for x in ['yolov5s6', 'yolov5m6', 'yolov5l6', 'yolov5x6']]:
  209. for f in sorted(Path(path).glob('study*.txt')):
  210. y = np.loadtxt(f, dtype=np.float32, usecols=[0, 1, 2, 3, 7, 8, 9], ndmin=2).T
  211. x = np.arange(y.shape[1]) if x is None else np.array(x)
  212. s = ['P', 'R', 'mAP@.5', 'mAP@.5:.95', 't_inference (ms/img)', 't_NMS (ms/img)', 't_total (ms/img)']
  213. # for i in range(7):
  214. # ax[i].plot(x, y[i], '.-', linewidth=2, markersize=8)
  215. # ax[i].set_title(s[i])
  216. j = y[3].argmax() + 1
  217. ax2.plot(y[6, 1:j], y[3, 1:j] * 1E2, '.-', linewidth=2, markersize=8,
  218. label=f.stem.replace('study_coco_', '').replace('yolo', 'YOLO'))
  219. ax2.plot(1E3 / np.array([209, 140, 97, 58, 35, 18]), [34.6, 40.5, 43.0, 47.5, 49.7, 51.5],
  220. 'k.-', linewidth=2, markersize=8, alpha=.25, label='EfficientDet')
  221. ax2.grid(alpha=0.2)
  222. ax2.set_yticks(np.arange(20, 60, 5))
  223. ax2.set_xlim(0, 57)
  224. ax2.set_ylim(30, 55)
  225. ax2.set_xlabel('GPU Speed (ms/img)')
  226. ax2.set_ylabel('COCO AP val')
  227. ax2.legend(loc='lower right')
  228. plt.savefig(str(Path(path).name) + '.png', dpi=300)
  229. def plot_labels(labels, names=(), save_dir=Path(''), loggers=None):
  230. # plot dataset labels
  231. print('Plotting labels... ')
  232. c, b = labels[:, 0], labels[:, 1:].transpose() # classes, boxes
  233. nc = int(c.max() + 1) # number of classes
  234. x = pd.DataFrame(b.transpose(), columns=['x', 'y', 'width', 'height'])
  235. # seaborn correlogram
  236. sns.pairplot(x, corner=True, diag_kind='auto', kind='hist', diag_kws=dict(bins=50), plot_kws=dict(pmax=0.9))
  237. plt.savefig(save_dir / 'labels_correlogram.jpg', dpi=200)
  238. plt.close()
  239. # matplotlib labels
  240. matplotlib.use('svg') # faster
  241. ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)[1].ravel()
  242. ax[0].hist(c, bins=np.linspace(0, nc, nc + 1) - 0.5, rwidth=0.8)
  243. ax[0].set_ylabel('instances')
  244. if 0 < len(names) < 30:
  245. ax[0].set_xticks(range(len(names)))
  246. ax[0].set_xticklabels(names, rotation=90, fontsize=10)
  247. else:
  248. ax[0].set_xlabel('classes')
  249. sns.histplot(x, x='x', y='y', ax=ax[2], bins=50, pmax=0.9)
  250. sns.histplot(x, x='width', y='height', ax=ax[3], bins=50, pmax=0.9)
  251. # rectangles
  252. labels[:, 1:3] = 0.5 # center
  253. labels[:, 1:] = xywh2xyxy(labels[:, 1:]) * 2000
  254. img = Image.fromarray(np.ones((2000, 2000, 3), dtype=np.uint8) * 255)
  255. for cls, *box in labels[:1000]:
  256. ImageDraw.Draw(img).rectangle(box, width=1, outline=colors(cls)) # plot
  257. ax[1].imshow(img)
  258. ax[1].axis('off')
  259. for a in [0, 1, 2, 3]:
  260. for s in ['top', 'right', 'left', 'bottom']:
  261. ax[a].spines[s].set_visible(False)
  262. plt.savefig(save_dir / 'labels.jpg', dpi=200)
  263. matplotlib.use('Agg')
  264. plt.close()
  265. # loggers
  266. for k, v in loggers.items() or {}:
  267. if k == 'wandb' and v:
  268. v.log({"Labels": [v.Image(str(x), caption=x.name) for x in save_dir.glob('*labels*.jpg')]}, commit=False)
  269. def plot_evolution(yaml_file='data/hyp.finetune.yaml'): # from utils.plots import *; plot_evolution()
  270. # Plot hyperparameter evolution results in evolve.txt
  271. with open(yaml_file) as f:
  272. hyp = yaml.safe_load(f)
  273. x = np.loadtxt('evolve.txt', ndmin=2)
  274. f = fitness(x)
  275. # weights = (f - f.min()) ** 2 # for weighted results
  276. plt.figure(figsize=(10, 12), tight_layout=True)
  277. matplotlib.rc('font', **{'size': 8})
  278. for i, (k, v) in enumerate(hyp.items()):
  279. y = x[:, i + 7]
  280. # mu = (y * weights).sum() / weights.sum() # best weighted result
  281. mu = y[f.argmax()] # best single result
  282. plt.subplot(6, 5, i + 1)
  283. plt.scatter(y, f, c=hist2d(y, f, 20), cmap='viridis', alpha=.8, edgecolors='none')
  284. plt.plot(mu, f.max(), 'k+', markersize=15)
  285. plt.title('%s = %.3g' % (k, mu), fontdict={'size': 9}) # limit to 40 characters
  286. if i % 5 != 0:
  287. plt.yticks([])
  288. print('%15s: %.3g' % (k, mu))
  289. plt.savefig('evolve.png', dpi=200)
  290. print('\nPlot saved as evolve.png')
  291. def profile_idetection(start=0, stop=0, labels=(), save_dir=''):
  292. # Plot iDetection '*.txt' per-image logs. from utils.plots import *; profile_idetection()
  293. ax = plt.subplots(2, 4, figsize=(12, 6), tight_layout=True)[1].ravel()
  294. s = ['Images', 'Free Storage (GB)', 'RAM Usage (GB)', 'Battery', 'dt_raw (ms)', 'dt_smooth (ms)', 'real-world FPS']
  295. files = list(Path(save_dir).glob('frames*.txt'))
  296. for fi, f in enumerate(files):
  297. try:
  298. results = np.loadtxt(f, ndmin=2).T[:, 90:-30] # clip first and last rows
  299. n = results.shape[1] # number of rows
  300. x = np.arange(start, min(stop, n) if stop else n)
  301. results = results[:, x]
  302. t = (results[0] - results[0].min()) # set t0=0s
  303. results[0] = x
  304. for i, a in enumerate(ax):
  305. if i < len(results):
  306. label = labels[fi] if len(labels) else f.stem.replace('frames_', '')
  307. a.plot(t, results[i], marker='.', label=label, linewidth=1, markersize=5)
  308. a.set_title(s[i])
  309. a.set_xlabel('time (s)')
  310. # if fi == len(files) - 1:
  311. # a.set_ylim(bottom=0)
  312. for side in ['top', 'right']:
  313. a.spines[side].set_visible(False)
  314. else:
  315. a.remove()
  316. except Exception as e:
  317. print('Warning: Plotting error for %s; %s' % (f, e))
  318. ax[1].legend()
  319. plt.savefig(Path(save_dir) / 'idetection_profile.png', dpi=200)
  320. def plot_results_overlay(start=0, stop=0): # from utils.plots import *; plot_results_overlay()
  321. # Plot training 'results*.txt', overlaying train and val losses
  322. s = ['train', 'train', 'train', 'Precision', 'mAP@0.5', 'val', 'val', 'val', 'Recall', 'mAP@0.5:0.95'] # legends
  323. t = ['Box', 'Objectness', 'Classification', 'P-R', 'mAP-F1'] # titles
  324. for f in sorted(glob.glob('results*.txt') + glob.glob('../../Downloads/results*.txt')):
  325. results = np.loadtxt(f, usecols=[2, 3, 4, 8, 9, 12, 13, 14, 10, 11], ndmin=2).T
  326. n = results.shape[1] # number of rows
  327. x = range(start, min(stop, n) if stop else n)
  328. fig, ax = plt.subplots(1, 5, figsize=(14, 3.5), tight_layout=True)
  329. ax = ax.ravel()
  330. for i in range(5):
  331. for j in [i, i + 5]:
  332. y = results[j, x]
  333. ax[i].plot(x, y, marker='.', label=s[j])
  334. # y_smooth = butter_lowpass_filtfilt(y)
  335. # ax[i].plot(x, np.gradient(y_smooth), marker='.', label=s[j])
  336. ax[i].set_title(t[i])
  337. ax[i].legend()
  338. ax[i].set_ylabel(f) if i == 0 else None # add filename
  339. fig.savefig(f.replace('.txt', '.png'), dpi=200)
  340. def plot_results(start=0, stop=0, bucket='', id=(), labels=(), save_dir=''):
  341. # Plot training 'results*.txt'. from utils.plots import *; plot_results(save_dir='runs/train/exp')
  342. fig, ax = plt.subplots(2, 5, figsize=(12, 6), tight_layout=True)
  343. ax = ax.ravel()
  344. s = ['Box', 'Objectness', 'Classification', 'Precision', 'Recall',
  345. 'val Box', 'val Objectness', 'val Classification', 'mAP@0.5', 'mAP@0.5:0.95']
  346. if bucket:
  347. # files = ['https://storage.googleapis.com/%s/results%g.txt' % (bucket, x) for x in id]
  348. files = ['results%g.txt' % x for x in id]
  349. c = ('gsutil cp ' + '%s ' * len(files) + '.') % tuple('gs://%s/results%g.txt' % (bucket, x) for x in id)
  350. os.system(c)
  351. else:
  352. files = list(Path(save_dir).glob('results*.txt'))
  353. assert len(files), 'No results.txt files found in %s, nothing to plot.' % os.path.abspath(save_dir)
  354. for fi, f in enumerate(files):
  355. try:
  356. results = np.loadtxt(f, usecols=[2, 3, 4, 8, 9, 12, 13, 14, 10, 11], ndmin=2).T
  357. n = results.shape[1] # number of rows
  358. x = range(start, min(stop, n) if stop else n)
  359. for i in range(10):
  360. y = results[i, x]
  361. if i in [0, 1, 2, 5, 6, 7]:
  362. y[y == 0] = np.nan # don't show zero loss values
  363. # y /= y[0] # normalize
  364. label = labels[fi] if len(labels) else f.stem
  365. ax[i].plot(x, y, marker='.', label=label, linewidth=2, markersize=8)
  366. ax[i].set_title(s[i])
  367. # if i in [5, 6, 7]: # share train and val loss y axes
  368. # ax[i].get_shared_y_axes().join(ax[i], ax[i - 5])
  369. except Exception as e:
  370. print('Warning: Plotting error for %s; %s' % (f, e))
  371. ax[1].legend()
  372. fig.savefig(Path(save_dir) / 'results.png', dpi=200)
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...