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
| def main(opt, callbacks=None): """Runs the main entry point for training or hyperparameter evolution with specified options and optional callbacks.
Args: opt (argparse.Namespace): The command-line arguments parsed for YOLOv5 training and evolution. callbacks (ultralytics.utils.callbacks.Callbacks, optional): Callback functions for various training stages. Defaults to Callbacks().
Returns: None
Notes: For detailed usage, refer to: https://github.com/ultralytics/yolov5/tree/master/models """ if callbacks is None: callbacks = Callbacks() if RANK in {-1, 0}: print_args(vars(opt)) check_git_status() check_requirements(ROOT / "requirements.txt")
if opt.resume and not check_comet_resume(opt) and not opt.evolve: last = Path(check_file(opt.resume) if isinstance(opt.resume, str) else get_latest_run()) opt_yaml = last.parent.parent / "opt.yaml" opt_data = opt.data if opt_yaml.is_file(): with open(opt_yaml, errors="ignore") as f: d = yaml.safe_load(f) else: d = torch_load(last, map_location="cpu")["opt"] opt = argparse.Namespace(**d) opt.cfg, opt.weights, opt.resume = "", str(last), True if is_url(opt_data): opt.data = check_file(opt_data) else: opt.data, opt.cfg, opt.hyp, opt.weights, opt.project = ( check_file(opt.data), check_yaml(opt.cfg), check_yaml(opt.hyp), str(opt.weights), str(opt.project), ) assert len(opt.cfg) or len(opt.weights), "either --cfg or --weights must be specified" if opt.evolve: if opt.project == str(ROOT / "runs/train"): opt.project = str(ROOT / "runs/evolve") opt.exist_ok, opt.resume = opt.resume, False if opt.name == "cfg": opt.name = Path(opt.cfg).stem opt.save_dir = str(increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok))
device = select_device(opt.device, batch_size=opt.batch_size) if LOCAL_RANK != -1: msg = "is not compatible with YOLOv5 Multi-GPU DDP training" assert not opt.image_weights, f"--image-weights {msg}" assert not opt.evolve, f"--evolve {msg}" assert opt.batch_size != -1, f"AutoBatch with --batch-size -1 {msg}, please pass a valid --batch-size" assert opt.batch_size % WORLD_SIZE == 0, f"--batch-size {opt.batch_size} must be multiple of WORLD_SIZE" assert torch.cuda.device_count() > LOCAL_RANK, "insufficient CUDA devices for DDP command" torch.cuda.set_device(LOCAL_RANK) device = torch.device("cuda", LOCAL_RANK) dist.init_process_group( backend="nccl" if dist.is_nccl_available() else "gloo", timeout=timedelta(seconds=10800) )
if not opt.evolve: train(opt.hyp, opt, device, callbacks)
else: meta = { "lr0": (False, 1e-5, 1e-1), "lrf": (False, 0.01, 1.0), "momentum": (False, 0.6, 0.98), "weight_decay": (False, 0.0, 0.001), "warmup_epochs": (False, 0.0, 5.0), "warmup_momentum": (False, 0.0, 0.95), "warmup_bias_lr": (False, 0.0, 0.2), "box": (False, 0.02, 0.2), "cls": (False, 0.2, 4.0), "cls_pw": (False, 0.5, 2.0), "obj": (False, 0.2, 4.0), "obj_pw": (False, 0.5, 2.0), "iou_t": (False, 0.1, 0.7), "anchor_t": (False, 2.0, 8.0), "anchors": (False, 2.0, 10.0), "fl_gamma": (False, 0.0, 2.0), "hsv_h": (True, 0.0, 0.1), "hsv_s": (True, 0.0, 0.9), "hsv_v": (True, 0.0, 0.9), "degrees": (True, 0.0, 45.0), "translate": (True, 0.0, 0.9), "scale": (True, 0.0, 0.9), "shear": (True, 0.0, 10.0), "perspective": (True, 0.0, 0.001), "flipud": (True, 0.0, 1.0), "fliplr": (True, 0.0, 1.0), "mosaic": (True, 0.0, 1.0), "mixup": (True, 0.0, 1.0), "copy_paste": (True, 0.0, 1.0), }
pop_size = 50 mutation_rate_min = 0.01 mutation_rate_max = 0.5 crossover_rate_min = 0.5 crossover_rate_max = 1 min_elite_size = 2 max_elite_size = 5 tournament_size_min = 2 tournament_size_max = 10
with open(opt.hyp, errors="ignore") as f: hyp = yaml.safe_load(f) if "anchors" not in hyp: hyp["anchors"] = 3 if opt.noautoanchor: del hyp["anchors"], meta["anchors"] opt.noval, opt.nosave, save_dir = True, True, Path(opt.save_dir) evolve_yaml, evolve_csv = save_dir / "hyp_evolve.yaml", save_dir / "evolve.csv" if opt.bucket: subprocess.run( [ "gsutil", "cp", f"gs://{opt.bucket}/evolve.csv", str(evolve_csv), ], check=False, )
del_ = [item for item, value_ in meta.items() if value_[0] is False] hyp_GA = hyp.copy() for item in del_: del meta[item] del hyp_GA[item]
lower_limit = np.array([meta[k][1] for k in hyp_GA]) upper_limit = np.array([meta[k][2] for k in hyp_GA])
gene_ranges = [(lower_limit[i], upper_limit[i]) for i in range(len(upper_limit))]
initial_values = []
if opt.resume_evolve is not None: assert os.path.isfile(ROOT / opt.resume_evolve), "evolve population path is wrong!" with open(ROOT / opt.resume_evolve, errors="ignore") as f: evolve_population = yaml.safe_load(f) for value in evolve_population.values(): value = np.array([value[k] for k in hyp_GA]) initial_values.append(list(value))
else: yaml_files = [f for f in os.listdir(opt.evolve_population) if f.endswith(".yaml")] for file_name in yaml_files: with open(os.path.join(opt.evolve_population, file_name)) as yaml_file: value = yaml.safe_load(yaml_file) value = np.array([value[k] for k in hyp_GA]) initial_values.append(list(value))
if not initial_values: population = [generate_individual(gene_ranges, len(hyp_GA)) for _ in range(pop_size)] elif pop_size > 1: population = [generate_individual(gene_ranges, len(hyp_GA)) for _ in range(pop_size - len(initial_values))] for initial_value in initial_values: population = [initial_value, *population]
list_keys = list(hyp_GA.keys()) best_fitness, best_individual = float("-inf"), None for generation in range(opt.evolve): if generation >= 1: save_dict = {} for i in range(len(population)): little_dict = {list_keys[j]: float(population[i][j]) for j in range(len(population[i]))} save_dict[f"gen{generation!s}number{i!s}"] = little_dict
with open(save_dir / "evolve_population.yaml", "w") as outfile: yaml.dump(save_dict, outfile, default_flow_style=False)
elite_size = min_elite_size + int((max_elite_size - min_elite_size) * (generation / opt.evolve)) fitness_scores = [] for individual in population: for key, value in zip(hyp_GA.keys(), individual): hyp_GA[key] = value hyp.update(hyp_GA) results = train(hyp.copy(), opt, device, callbacks) callbacks = Callbacks() keys = ( "metrics/precision", "metrics/recall", "metrics/mAP_0.5", "metrics/mAP_0.5:0.95", "val/box_loss", "val/obj_loss", "val/cls_loss", ) print_mutation(keys, results, hyp.copy(), save_dir, opt.bucket) fitness_scores.append(results[2])
selected_indices = [] for _ in range(pop_size - elite_size): tournament_size = max( max(2, tournament_size_min), int(min(tournament_size_max, pop_size) - (generation / (opt.evolve / 10))), ) tournament_indices = random.sample(range(pop_size), tournament_size) tournament_fitness = [fitness_scores[j] for j in tournament_indices] winner_index = tournament_indices[tournament_fitness.index(max(tournament_fitness))] selected_indices.append(winner_index)
elite_indices = [i for i in range(pop_size) if fitness_scores[i] in sorted(fitness_scores)[-elite_size:]] selected_indices.extend(elite_indices) next_generation = [] for _ in range(pop_size): parent1_index = selected_indices[random.randint(0, pop_size - 1)] parent2_index = selected_indices[random.randint(0, pop_size - 1)] crossover_rate = max( crossover_rate_min, min(crossover_rate_max, crossover_rate_max - (generation / opt.evolve)) ) if random.uniform(0, 1) < crossover_rate: crossover_point = random.randint(1, len(hyp_GA) - 1) child = population[parent1_index][:crossover_point] + population[parent2_index][crossover_point:] else: child = population[parent1_index].copy() mutation_rate = max( mutation_rate_min, min(mutation_rate_max, mutation_rate_max - (generation / opt.evolve)) ) for j in range(len(hyp_GA)): if random.uniform(0, 1) < mutation_rate: child[j] += random.uniform(-0.1, 0.1) child[j] = min(max(child[j], gene_ranges[j][0]), gene_ranges[j][1]) next_generation.append(child) if max(fitness_scores) > best_fitness: best_fitness = max(fitness_scores) best_individual = population[fitness_scores.index(best_fitness)] population = next_generation LOGGER.info(f"Best solution found: {best_individual}") plot_evolve(evolve_csv) LOGGER.info( f"Hyperparameter evolution finished {opt.evolve} generations\n" f"Results saved to {colorstr('bold', save_dir)}\n" f"Usage example: $ python train.py --hyp {evolve_yaml}" )
|