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

train_squirrel_detector.py 5.0 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
  1. import argparse
  2. import glob
  3. import importlib
  4. import json
  5. import matplotlib
  6. import os
  7. import requests
  8. import shutil
  9. import time
  10. import torch
  11. import yaml
  12. from pathlib import Path
  13. from dagshub.streaming import install_hooks
  14. install_hooks()
  15. def download_training_scripts(outpath):
  16. train = 'https://raw.githubusercontent.com/ultralytics/yolov5/master/train.py'
  17. val = 'https://raw.githubusercontent.com/ultralytics/yolov5/master/val.py'
  18. for url in (train, val):
  19. os.makedirs(outpath, exist_ok=True)
  20. script = os.path.join(outpath, os.path.split(url)[-1])
  21. if os.path.exists(script):
  22. continue
  23. res = requests.get(url)
  24. if type(res.content) is bytes:
  25. mode = 'wb'
  26. else:
  27. mode = 'w'
  28. with open(script, mode='wb') as f:
  29. f.write(res.content)
  30. def read_yaml(filename):
  31. with open(filename) as f:
  32. return yaml.safe_load(f)
  33. def save_yaml(filename, data):
  34. with open(filename, mode='w') as f:
  35. f.write(yaml.safe_dump(data))
  36. def custom_img2label_paths(img_paths):
  37. import os
  38. paths, img_names = zip(*[os.path.split(i) for i in img_paths])
  39. paths = [os.path.join(p.rsplit('/data/', 1)[0], 'annotations/labels') for p in paths]
  40. ann_names = [os.path.splitext(i)[0] + '.txt' for i in img_names]
  41. return [os.path.join(p, a) for p, a in zip(paths, ann_names)]
  42. def get_labeled_images():
  43. labeled_imgs = set()
  44. labelstudio_files = glob.glob('../.labelstudio/*.json')
  45. for ls_file in labelstudio_files:
  46. with open(ls_file) as f:
  47. annotations = json.load(f)
  48. # If there's only one annotations, the Label Studio JSON file uses a `dict` as the top
  49. # level structure. However, it will use a `list`, if there are multiple. To make processing
  50. # easier, convert `dict`s to `list`s.
  51. if type(annotations) is dict:
  52. annotations = [annotations]
  53. for annotation in annotations:
  54. img = annotation['data']['image']
  55. _, img = os.path.split(img)
  56. labeled_imgs.add(img)
  57. return labeled_imgs
  58. def main():
  59. parser = argparse.ArgumentParser("Train a YOLOv5 model to detect squirrels")
  60. parser.add_argument("--data", required=True, help="Path to YAML file describing the data to use for training, validation, and testing")
  61. parser.add_argument("--weights", required=True, help="Path to the pretrained YOLOv5 weights to use")
  62. parser.add_argument("--epochs", default=300, type=int, help="Number of epochs to run")
  63. parser.add_argument("--batch-size", default=16, type=int, help="Batch size to use for training")
  64. parser.add_argument("--save-path", required=True, help="Path to save the best training results to")
  65. args = parser.parse_args()
  66. temp_yolov5_path = 'yolov5'
  67. download_training_scripts(temp_yolov5_path)
  68. # This will also locally cache the YOLOv5 repo
  69. _ = torch.hub.load('ultralytics/yolov5', 'custom', path=args.weights)
  70. import utils
  71. utils.dataloaders.img2label_paths = custom_img2label_paths
  72. orig_cache_labels = utils.dataloaders.LoadImagesAndLabels.cache_labels
  73. labeled_imgs = get_labeled_images()
  74. def custom_cache_labels(self, path=Path('./labels.cache'), prefix=''):
  75. data_cnt = len(self.im_files)
  76. for i in reversed(range(data_cnt)):
  77. im_file = self.im_files[i]
  78. _, im_name = os.path.split(im_file)
  79. if im_name not in labeled_imgs:
  80. self.im_files = self.im_files[:i] + self.im_files[i+1:]
  81. self.label_files = self.label_files[:i] + self.label_files[i+1:]
  82. return orig_cache_labels(self, path, prefix)
  83. utils.dataloaders.LoadImagesAndLabels.cache_labels = custom_cache_labels
  84. train = importlib.import_module(f'{temp_yolov5_path}.train')
  85. data_yaml = read_yaml(args.data)
  86. yaml_path, yaml_name =os.path.split(os.path.abspath(args.data))
  87. data_yaml['path'] = os.path.join(yaml_path, data_yaml['path'])
  88. new_yaml = os.path.join(temp_yolov5_path, yaml_name)
  89. save_yaml(new_yaml, data_yaml)
  90. train.run(weights=args.weights, data=new_yaml, hyp='data/hyps/hyp.scratch-low.yaml', epochs=args.epochs, batch_size=args.batch_size, name='squirrel', exist_ok=True)
  91. best_weights = f'{temp_yolov5_path}/runs/train/squirrel/weights/best.pt'
  92. outpath = args.save_path
  93. if outpath.endswith('.pt'):
  94. outdir, outfile = os.path.split(outpath)
  95. else:
  96. outdir = outpath
  97. outfile = f'{str(time.time_ns())[:-6]}.pt'
  98. outpath = os.path.join(outdir, outfile)
  99. if os.path.exists(best_weights):
  100. os.makedirs(outdir, exist_ok=True)
  101. try:
  102. shutil.copy2(best_weights, outpath)
  103. except PermissionError:
  104. print(f"Permission denied when trying to save model to '{outpath}'")
  105. except:
  106. print(f"Error occurred while trying to save model to '{outpath}'")
  107. else:
  108. shutil.rmtree(f'{temp_yolov5_path}/runs', ignore_errors=True)
  109. if __name__ == '__main__':
  110. main()
Tip!

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

Comments

Loading...