Link to this section콜백(Callbacks)#
Ultralytics 프레임워크는 train, val, export, 및 predict 모드 중 전략적 단계에서 진입점 역할을 하는 콜백을 지원합니다. 각 콜백은 작업 유형에 따라 Trainer, Validator 또는 Predictor 객체를 허용합니다. 이러한 객체의 모든 속성은 문서의 참조 섹션에 자세히 설명되어 있습니다.
Watch: How to use Ultralytics Callbacks | Predict, Train, Validate and Export Callbacks | Ultralytics YOLO🚀
Link to this section예제#
Link to this section예측과 함께 추가 정보 반환하기#
이 예제에서는 각 결과 객체와 함께 원본 프레임을 반환하는 방법을 보여줍니다:
from ultralytics import YOLO
def on_predict_batch_end(predictor):
"""Combine prediction results with corresponding frames."""
_, image, _, _ = predictor.batch
# Ensure that image is a list
image = image if isinstance(image, list) else [image]
# Combine the prediction results with the corresponding frames
predictor.results = zip(predictor.results, image)
# Create a YOLO model instance
model = YOLO("yolo26n.pt")
# Add the custom callback to the model
model.add_callback("on_predict_batch_end", on_predict_batch_end)
# Iterate through the results and frames
for result, frame in model.predict(): # or model.track()
passLink to this sectionon_model_save 콜백을 사용하여 모델 메트릭에 액세스하기#
이 예제는 on_model_save 콜백을 사용하여 체크포인트가 저장된 후 best_fitness 점수, total_loss 및 기타 메트릭과 같은 학습 세부 정보를 검색하는 방법을 보여줍니다.
from ultralytics import YOLO
# Load a YOLO model
model = YOLO("yolo26n.pt")
def print_checkpoint_metrics(trainer):
"""Print trainer metrics and loss details after each checkpoint is saved."""
print(
f"Model details\n"
f"Best fitness: {trainer.best_fitness}, "
f"Loss names: {trainer.loss_names}, " # List of loss names
f"Metrics: {trainer.metrics}, "
f"Total loss: {trainer.tloss}" # Total loss value
)
if __name__ == "__main__":
# Add on_model_save callback.
model.add_callback("on_model_save", print_checkpoint_metrics)
# Run model training on custom dataset.
results = model.train(data="coco8.yaml", epochs=3)Link to this section모든 콜백#
아래는 지원되는 모든 콜백입니다. 자세한 내용은 콜백 소스 코드를 참조하십시오.
Link to this section트레이너(Trainer) 콜백#
| 콜백 | 설명 |
|---|---|
on_pretrain_routine_start | 데이터 로딩 및 모델 설정 전, 사전 학습 루틴 시작 시 트리거됩니다. |
on_pretrain_routine_end | 데이터 로딩 및 모델 설정이 완료된 후, 사전 학습 루틴 종료 시 트리거됩니다. |
on_train_start | 학습이 시작될 때, 첫 번째 에폭(epoch)이 시작되기 전에 트리거됩니다. |
on_train_epoch_start | 각 학습 에폭(epoch) 시작 시, 배치 반복이 시작되기 전에 트리거됩니다. |
on_train_batch_start | 각 학습 배치 시작 시, 순전파(forward pass) 전에 트리거됩니다. |
optimizer_step | 옵티마이저 단계 중에 트리거됩니다. 사용자 지정 통합을 위해 예약되어 있으며 기본 학습 루프에서는 호출되지 않습니다. |
on_before_zero_grad | 기울기(gradient)가 0으로 설정되기 전에 트리거됩니다. 사용자 지정 통합을 위해 예약되어 있으며 기본 학습 루프에서는 호출되지 않습니다. |
on_train_batch_end | 각 학습 배치 종료 시, 역전파(backward pass) 후에 트리거됩니다. 기울기 누적으로 인해 옵티마이저 단계가 지연될 수 있습니다. |
on_train_epoch_end | 각 학습 에폭 종료 시, 모든 배치가 처리된 후 검증 전에 트리거됩니다. 검증 메트릭 및 피트니스 점수는 아직 준비되지 않았을 수 있습니다. |
on_model_save | 모델 체크포인트가 저장될 때, 검증 후에 트리거됩니다. |
on_fit_epoch_end | 각 핏 에폭(학습 + 검증) 종료 시, 검증 및 체크포인트 저장 후에 트리거됩니다. 검증 메트릭을 사용할 수 있으며, 에폭별 학습 호출에 대한 피트니스 점수를 사용할 수 있습니다. 이 콜백은 체크포인트 저장이 발생하지 않고 피트니스 점수가 없을 수 있는 최종 최적 모델 평가 중에도 호출됩니다. |
on_train_end | 최종 최적 모델 평가 후, 학습 프로세스가 종료될 때 트리거됩니다. |
on_params_update | 모델 매개변수가 업데이트될 때 트리거됩니다. 사용자 지정 통합을 위해 예약되어 있으며 기본 학습 루프에서는 호출되지 않습니다. |
teardown | 학습 프로세스가 정리될 때 트리거됩니다. |
Link to this section검증기(Validator) 콜백#
| 콜백 | 설명 |
|---|---|
on_val_start | 검증이 시작될 때 트리거됩니다. |
on_val_batch_start | 각 검증 배치 시작 시 트리거됩니다. |
on_val_batch_end | 각 검증 배치 종료 시 트리거됩니다. |
on_val_end | 검증이 종료될 때 트리거됩니다. |
Link to this section예측기(Predictor) 콜백#
| 콜백 | 설명 |
|---|---|
on_predict_start | 예측 프로세스가 시작될 때 트리거됩니다. |
on_predict_batch_start | 각 예측 배치 시작 시 트리거됩니다. |
on_predict_postprocess_end | 예측 후처리 종료 시 트리거됩니다. |
on_predict_batch_end | 각 예측 배치 종료 시 트리거됩니다. |
on_predict_end | 예측 프로세스가 종료될 때 트리거됩니다. |
Link to this section내보내기(Exporter) 콜백#
| 콜백 | 설명 |
|---|---|
on_export_start | 내보내기 프로세스가 시작될 때 트리거됩니다. |
on_export_end | 내보내기 프로세스가 종료될 때 트리거됩니다. |
Link to this sectionFAQ#
Link to this sectionUltralytics 콜백이란 무엇이며 어떻게 사용합니까?#
Ultralytics 콜백은 학습, 검증, 내보내기, 예측과 같은 모델 작업의 주요 단계에서 트리거되는 특수 진입점입니다. 이러한 콜백을 통해 프로세스의 특정 지점에서 사용자 지정 기능을 활성화하여 워크플로우를 향상하고 수정할 수 있습니다. 각 콜백은 작업 유형에 따라 Trainer, Validator 또는 Predictor 객체를 허용합니다. 이러한 객체의 자세한 속성은 참조 섹션을 참조하십시오.
콜백을 사용하려면 함수를 정의하고 model.add_callback() 메서드를 사용하여 모델에 추가하십시오. 다음은 예측 중에 추가 정보를 반환하는 예제입니다:
from ultralytics import YOLO
def on_predict_batch_end(predictor):
"""Handle prediction batch end by combining results with corresponding frames; modifies predictor results."""
_, image, _, _ = predictor.batch
image = image if isinstance(image, list) else [image]
predictor.results = zip(predictor.results, image)
model = YOLO("yolo26n.pt")
model.add_callback("on_predict_batch_end", on_predict_batch_end)
for result, frame in model.predict():
passLink to this section콜백을 사용하여 Ultralytics 학습 루틴을 어떻게 사용자 지정할 수 있습니까?#
학습 프로세스의 특정 단계에서 로직을 삽입하여 Ultralytics 학습 루틴을 사용자 지정하십시오. Ultralytics YOLO는 on_train_start, on_train_end 및 on_train_batch_end와 같은 다양한 학습 콜백을 제공하여 사용자 지정 메트릭, 처리 또는 로깅을 추가할 수 있습니다.
다음은 콜백으로 레이어를 고정할 때 BatchNorm 통계를 고정하는 방법입니다:
from ultralytics import YOLO
# Add a callback to put the frozen layers in eval mode to prevent BN values from changing
def put_in_eval_mode(trainer):
n_layers = trainer.args.freeze
if not isinstance(n_layers, int):
return
for i, (name, module) in enumerate(trainer.model.named_modules()):
if name.endswith("bn") and int(name.split(".")[1]) < n_layers:
module.eval()
module.track_running_stats = False
model = YOLO("yolo26n.pt")
model.add_callback("on_train_epoch_start", put_in_eval_mode)
model.train(data="coco.yaml", epochs=10)학습 콜백을 효과적으로 사용하는 방법에 대한 자세한 내용은 학습 가이드를 참조하십시오.
Link to this sectionUltralytics YOLO에서 검증 중 콜백을 사용해야 하는 이유는 무엇입니까?#
Ultralytics YOLO 검증 중에 콜백을 사용하면 사용자 지정 처리, 로깅 또는 메트릭 계산을 활성화하여 모델 평가를 향상할 수 있습니다. on_val_start, on_val_batch_end 및 on_val_end와 같은 콜백은 사용자 지정 로직을 삽입하기 위한 진입점을 제공하여 상세하고 포괄적인 검증 프로세스를 보장합니다.
예를 들어, 처음 세 개 배치 대신 모든 검증 배치를 플로팅하려면 다음과 같이 합니다:
import inspect
from ultralytics import YOLO
def plot_samples(validator):
frame = inspect.currentframe().f_back.f_back
v = frame.f_locals
validator.plot_val_samples(v["batch"], v["batch_i"])
validator.plot_predictions(v["batch"], v["preds"], v["batch_i"])
model = YOLO("yolo26n.pt")
model.add_callback("on_val_batch_end", plot_samples)
model.val(data="coco.yaml")검증 프로세스에 콜백을 통합하는 방법에 대한 자세한 내용은 검증 가이드를 참조하십시오.
Link to this sectionUltralytics YOLO에서 예측 모드용 사용자 지정 콜백을 어떻게 연결합니까?#
Ultralytics YOLO에서 예측 모드용 사용자 지정 콜백을 연결하려면 콜백 함수를 정의하고 예측 프로세스에 등록하십시오. 일반적인 예측 콜백에는 on_predict_start, on_predict_batch_end 및 on_predict_end가 있습니다. 이를 통해 예측 출력을 수정하고 데이터 로깅이나 결과 변환과 같은 추가 기능을 통합할 수 있습니다.
다음은 특정 클래스의 객체가 있는지 여부에 따라 예측을 저장하는 사용자 지정 콜백 예제입니다:
from ultralytics import YOLO
model = YOLO("yolo26n.pt")
class_id = 2
def save_on_object(predictor):
r = predictor.results[0]
if class_id in r.boxes.cls:
predictor.args.save = True
else:
predictor.args.save = False
model.add_callback("on_predict_postprocess_end", save_on_object)
results = model("pedestrians.mp4", stream=True, save=True)
for results in results:
pass더 포괄적인 사용법은 상세 지침 및 추가 사용자 지정 옵션이 포함된 예측 가이드를 참조하십시오.
Link to this sectionUltralytics YOLO에서 콜백을 사용하는 실용적인 예는 무엇입니까?#
Ultralytics YOLO는 학습, 검증, 예측과 같은 다양한 단계를 향상하고 사용자 지정하기 위해 콜백의 다양한 실용적인 구현을 지원합니다. 실용적인 예는 다음과 같습니다:
- 사용자 지정 메트릭 로깅: 학습 또는 검증 에폭(epoch) 종료 시 등 여러 단계에서 추가 메트릭을 기록합니다.
- 데이터 증강(Data Augmentation): 예측 또는 학습 배치 중에 사용자 지정 데이터 변환이나 증강을 구현합니다.
- 중간 결과: 추가 분석 또는 시각화를 위해 예측이나 프레임과 같은 중간 결과를 저장합니다.
예제: on_predict_batch_end를 사용하여 예측 중에 프레임과 예측 결과를 결합하기:
from ultralytics import YOLO
def on_predict_batch_end(predictor):
"""Combine prediction results with frames."""
_, image, _, _ = predictor.batch
image = image if isinstance(image, list) else [image]
predictor.results = zip(predictor.results, image)
model = YOLO("yolo26n.pt")
model.add_callback("on_predict_batch_end", on_predict_batch_end)
for result, frame in model.predict():
pass더 많은 옵션과 예제는 콜백 소스 코드를 탐색하십시오.