콜백
Ultralytics 프레임워크는 train, val, predict 및 export 모드의 주요 단계에서 진입점 역할을 하는 콜백을 지원합니다. 작업 유형에 따라 각 콜백은 Trainer, Validator, Predictor 또는 Exporter 객체를 받습니다.
시청: Ultralytics 콜백 사용 방법 | 예측, 학습, 검증 및 내보내기 콜백 | Ultralytics YOLO26 🚀
예제#
예측 결과에 추가 정보 반환#
이 예시는 각 결과 객체와 함께 원본 프레임을 반환합니다:
from ultralytics import YOLO
def on_predict_batch_end(predictor):
"""Combine prediction results with corresponding frames."""
_, image, _ = predictor.batch
# 이미지가 리스트인지 확인합니다
image = image if isinstance(image, list) else [image]
# 예측 결과를 해당 프레임과 결합합니다
predictor.results = zip(predictor.results, image)
# YOLO 모델 인스턴스를 생성합니다
model = YOLO("yolo26n.pt")
# 사용자 지정 콜백을 모델에 추가합니다
model.add_callback("on_predict_batch_end", on_predict_batch_end)
# 결과와 프레임을 순회합니다
for result, frame in model.predict(): # 또는 model.track()
pass학습 전에 PyTorch Forward Hooks 등록하기#
model.train()은 모델 구성에서 학습 모델을 생성하고 로드된 가중치를 모델에 전달합니다. 이 호출 전에 model.model에 직접 등록한 PyTorch 훅은 런타임 상태이므로, 다시 생성된 학습 모델은 해당 훅을 상속하지 않습니다. 모델 설정이 완료된 후 on_pretrain_routine_end에서 학습 훅을 등록합니다.
from ultralytics import YOLO
from ultralytics.utils.torch_utils import unwrap_model
def preprocess_input(module, inputs):
"""Center each input channel before the first model layer."""
images = inputs[0]
return (images - images.mean(dim=(-2, -1), keepdim=True),)
def register_forward_pre_hook(trainer):
"""Attach preprocessing to the active training model."""
train_model = unwrap_model(trainer.model)
train_model.model[0].register_forward_pre_hook(preprocess_input)
model = YOLO("yolo26n.pt")
model.add_callback("on_pretrain_routine_end", register_forward_pre_hook)
model.train(data="coco8.yaml", epochs=1)unwrap_model()은 단일 장치 학습과 DistributedDataParallel 학습을 모두 처리합니다. 학습 체크포인트는 EMA 모델을 직렬화하며, 체크포인트를 로드할 때 다른 프로세스에서 콜백을 가져오지 못할 수 있으므로 로컬에서 정의한 훅을 trainer.ema.ema에 연결하지 마세요. 학습 검증 중에도 동일한 전처리를 실행해야 한다면 런타임 훅 대신 가져올 수 있는 모델 컴포넌트로 구현하세요. NaN 복구 시 학습 모델에서 EMA를 다시 생성하므로, 이 방식으로 등록한 훅은 EMA와 복구 후 저장되는 체크포인트에 복사됩니다. 체크포인트를 다른 프로세스에서 로드해야 한다면 가져올 수 있는 모듈에 훅 함수를 정의하세요.
독립 실행형 model.val()은 호출할 때마다 로드된 모델을 복사합니다. 예측은 첫 호출에서 복사본을 생성하고 캐시하므로, 첫 번째 model.predict() 또는 model.track() 호출 전에 model.model에 훅을 등록하세요. 이후에 추가한 훅은 캐시된 predictor에 적용되지 않습니다. 새 프로세스에서 체크포인트를 로드한 후에는 런타임 훅을 다시 등록하세요.
on_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)모든 콜백#
아래는 지원되는 모든 콜백입니다. 자세한 내용은 콜백 소스 코드를 참조하세요.
Trainer 콜백#
| 콜백 | 설명 |
|---|---|
on_pretrain_routine_start | 데이터 로딩 및 모델 설정 전에 사전 학습 루틴이 시작될 때 트리거됩니다. |
on_pretrain_routine_end | 데이터 로딩 및 모델 설정이 완료된 후 사전 학습 루틴이 끝날 때 트리거됩니다. |
on_train_start | 첫 번째 epoch가 시작되기 전에 학습이 시작될 때 트리거됩니다. |
on_train_epoch_start | 각 학습 에포크가 시작될 때, 배치 반복이 시작되기 전에 트리거됩니다. |
on_train_batch_start | Forward pass 전에 각 학습 배치가 시작될 때 트리거됩니다. |
optimizer_step | optimizer 단계 중에 트리거됩니다. 사용자 지정 통합을 위해 예약되어 있으며 기본 학습 루프에서는 호출되지 않습니다. |
on_before_zero_grad | gradient를 0으로 설정하기 전에 트리거됩니다. 사용자 지정 통합을 위해 예약되어 있으며 기본 학습 루프에서는 호출되지 않습니다. |
on_train_batch_end | Backward pass 후 각 학습 배치가 끝날 때 트리거됩니다. gradient accumulation으로 인해 optimizer 단계가 연기될 수 있습니다. |
on_train_epoch_end | 모든 배치가 처리된 후, 검증 전에 각 학습 epoch가 끝날 때 트리거됩니다. 검증 메트릭과 fitness는 아직 제공되지 않을 수 있습니다. |
on_model_save | 검증 후 모델 체크포인트가 저장될 때 트리거됩니다. |
on_fit_epoch_end | 검증 및 체크포인트 저장이 완료된 후, 각 fit epoch(학습 + 검증)가 끝날 때 트리거됩니다. 검증 메트릭을 사용할 수 있으며, epoch별 학습 호출에서는 fitness도 사용할 수 있습니다. 이 콜백은 체크포인트 저장이 발생하지 않고 fitness가 없을 수 있는 최종 최고 모델 평가 중에도 호출됩니다. |
on_train_end | 최고 모델의 최종 평가 후 학습 프로세스가 종료될 때 트리거됩니다. |
on_params_update | 모델 파라미터가 업데이트될 때 트리거됩니다. 사용자 지정 통합을 위해 예약되어 있으며 기본 학습 루프에서는 호출되지 않습니다. |
teardown | 학습 프로세스 정리가 진행될 때 트리거됩니다. |
Validator 콜백#
| 콜백 | 설명 |
|---|---|
on_val_start | 검증이 시작될 때 트리거됩니다. |
on_val_batch_start | 각 검증 배치가 시작될 때 트리거됩니다. |
on_val_batch_end | 각 검증 배치가 끝날 때 트리거됩니다. |
on_val_end | 검증이 끝날 때 트리거됩니다. |
Predictor 콜백#
| 콜백 | 설명 |
|---|---|
on_predict_start | 예측 프로세스가 시작될 때 트리거됩니다. |
on_predict_batch_start | 각 예측 배치가 시작될 때 트리거됩니다. |
on_predict_postprocess_end | 예측 후처리가 끝날 때 트리거됩니다. |
on_predict_batch_end | 각 예측 배치가 끝날 때 트리거됩니다. |
on_predict_end | 예측 프로세스가 끝날 때 트리거됩니다. |
Exporter 콜백#
| 콜백 | 설명 |
|---|---|
on_export_start | 내보내기 프로세스가 시작될 때 트리거됩니다. |
on_export_end | 내보내기 프로세스가 끝날 때 트리거됩니다. |
자주 묻는 질문#
Ultralytics 콜백은 학습, 검증, 예측 및 내보내기와 같은 모델 작업의 주요 단계에서 트리거되는 진입점입니다. 라이브러리를 수정하지 않고도 프로세스의 특정 지점에 커스텀 기능을 추가할 수 있습니다. 작업 유형에 따라 각 콜백은
Trainer,Validator,Predictor또는Exporter객체를 받습니다.콜백을 사용하려면 함수를 정의하고
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(): pass학습 프로세스의 특정 단계에 로직을 삽입하여 Ultralytics 학습 루틴을 사용자 지정할 수 있습니다. Ultralytics YOLO는
on_train_start,on_train_end,on_train_batch_end와 같은 다양한 학습 콜백을 제공하여 사용자 지정 메트릭, 처리 또는 로깅을 추가할 수 있도록 합니다.각 학습 epoch가 끝날 때 모든 optimizer 파라미터 그룹의 learning rate를 기록하는 방법은 다음과 같습니다.
from ultralytics import YOLO def log_learning_rates(trainer): """Print the current learning rates after each training epoch.""" print(f"Epoch {trainer.epoch + 1}: {trainer.lr}") model = YOLO("yolo26n.pt") model.add_callback("on_train_epoch_end", log_learning_rates) model.train(data="coco8.yaml", epochs=3)팁freeze을 사용할 때 BatchNorm 통계를 고정하기 위해 콜백을 사용할 필요는 없습니다. trainer가 매 epoch 시작 시 고정된 레이어의 BatchNorm 레이어를 자동으로 eval 모드로 설정합니다.학습 콜백을 효과적으로 사용하는 방법에 관한 자세한 내용은 학습 가이드를 참조하세요.
검증 콜백을 사용하면 모델 평가에 커스텀 처리, 로깅 또는 지표 계산을 추가할 수 있습니다.
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")검증 프로세스에 콜백을 적용하는 방법에 관한 자세한 내용은 검증 가이드를 참조하세요.
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_stream = model("pedestrians.mp4", stream=True, save=True) for result in results_stream: pass더 자세한 사용 방법은 상세한 지침과 추가 사용자 지정 옵션을 포함하는 예측 가이드를 참조하세요.
Ultralytics YOLO는 학습, 검증, 예측과 같은 여러 단계를 개선하고 사용자 지정할 수 있도록 다양한 실용적인 콜백 구현을 지원합니다. 실용적인 예제는 다음과 같습니다.
- 커스텀 지표 로깅: 학습 또는 검증 에포크 종료 시점 등 각 단계에서 추가 지표를 기록합니다.
- 데이터 증강: 예측 또는 학습 배치 중에 사용자 지정 데이터 변환이나 증강을 구현합니다.
- 중간 결과: 추가 분석 또는 시각화를 위해 예측이나 프레임과 같은 중간 결과를 저장합니다.
예:
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더 많은 옵션과 예제를 보려면 콜백 소스 코드를 확인하세요.
댓글15
질문을 하거나 결과를 공유하거나 다른 사람을 도와주세요.
drbilal216
Hi can i and how use callback to freeze initial layers for number of epochs and unfreeze after that, is there any builtin function for that? i used freeze builtin function but it freezes for all the epochs.
drbilal216
also, after certain epochs the change in model training is minimal can we use callback then to change lr, how and what parameter to change ?
Glenn JocherUltralytics@drbilal216 yes, you can use callbacks to freeze/unfreeze layers dynamically during training. Here's how to freeze initial layers for specific epochs then unfreeze them:
from ultralytics import YOLO def dynamic_freeze_callback(trainer): freeze_epochs = 10 # Freeze for first 10 epochs freeze_layers = 10 # Number of layers to freeze if trainer.epoch < freeze_epochs: # Freeze layers for i, (name, param) in enumerate(trainer.model.named_parameters()): if i < freeze_layers: param.requires_grad = False else: # Unfreeze all layers for param in trainer.model.parameters(): param.requires_grad = True model = YOLO("yolo11n.pt") model.add_callback("on_train_epoch_start", dynamic_freeze_callback) model.train(data="coco8.yaml", epochs=20)For dynamic learning rate adjustment when training plateaus, you can modify the scheduler within a callback:
def dynamic_lr_callback(trainer): if trainer.epoch > 50 and trainer.epoch % 10 == 0: # Every 10 epochs after epoch 50 for param_group in trainer.optimizer.param_groups: param_group['lr'] *= 0.9 # Reduce LR by 10% model.add_callback("on_train_epoch_end", dynamic_lr_callback)1drbilal216
@glenn-jocher Thanks for the code! I'm working on a low-quality PPE dataset. With a custom YAML, I improved YOLOv12n accuracy by 3%, and got similar results on YOLOv11n with better FPS.
The default Nano model lets me use pretrained=True, but custom architectures start from scratch. Still, I can reuse best.pt as pretrained weights on the same YAML later.
I'm now exploring argument tuning and callbacks for further improvements. I also tried freezing/unfreezing layers mid-training but saw no gains.
Lastly, I integrated Flash into YOLOv12, but I don’t see any sign that it’s being used during training (tested on Colab and A100 80GB-server).
jnance34
Hello,
I'm trying to implement a custom
on_pretrain_routine_endcallback with amodel.tune()call, but it appears that the Tuner class isn't adding my custom callback function to theTuner.callbackslist. Here's some pseudo code of what I'm trying to do:def my_custom_callback(trainer): print("I'm in my custom callback function!") model = YOLO("model/yolo11n.pt") model.add_callback('on_pretrain_routine_end', my_custom_function) model.tune(...) # Expect to see "I'm in my custom callback function" for each trial run...For some reason my custom callback function isn't getting called for each training run of the Tuner. Am I missing a step here? I've taken a look at the source code but don't see anything obviously wrong...
Thanks!
-James
RizwanMunawar
@jnance34 Hi! At the moment, callbacks are not supported for model.tone(...). You can find a complete list of all supported callbacks here: https://docs.ultralytics.com/usage/callbacks/#all-callbacks
ruslanraupoff
When I'm using single device add_callback works well but multi gpu's not working any solution for this?
Glenn JocherUltralytics@ruslanraupoff for multi-GPU training with callbacks, ensure your callback function is properly registered in all processes. When using DDP mode, callbacks need to be added before the training starts and should be compatible with distributed training environments. If you're experiencing issues, verify that your callback logic is thread-safe and doesn't rely on process-specific resources. For implementation details, refer to our callbacks documentation: https://docs.ultralytics.com/usage/callbacks
1
D3RK0
Hi, in the documentation above, I see that
predictor.batchis used, which I assume refers to the current batch of the predictor. Is there a similartrainer.batchfor a trainer? I need it in order to apply data augmentation during the training of my YOLOv8 classifier.D3RK0
I forgot to ask which (callback) event do I need to select?
Glenn JocherUltralytics(수정됨)@D3RK0 trainer callbacks only receive the
trainerobject, so the current batch is not available there astrainer.batch. To apply custom augmentation to each training batch, subclass your trainer (e.g.ClassificationTrainer) and overridepreprocess_batch(self, batch), which receives every training batch before the forward pass.D3RK0(수정됨)
@glenn-jocher Many thanks for your quick response!
I am dealing with following problem though:
Problem
When I do
trainer.batch, I get the following error:Traceback (most recent call last): File "C:\Program Files\JetBrains\PyCharm Community Edition 2022.3.3\plugins\python-ce\helpers\pydev\pydevd.py", line 1534, in _exec pydev_imports.execfile(file, globals, locals) # execute the script ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\JetBrains\PyCharm Community Edition 2022.3.3\plugins\python-ce\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile exec(compile(contents+"\n", file, 'exec'), glob, loc) File "C:\Users\derk_\Documents\Universiteit\IRP\Research_Project\main.py", line 397, in <module> main() File "C:\Users\derk_\Documents\Universiteit\IRP\Research_Project\main.py", line 377, in main model.train(mode="classify", File "C:\Users\derk_\anaconda3\envs\cobra\Lib\site-packages\ultralytics\engine\model.py", line 802, in train self.trainer.train() File "C:\Users\derk_\anaconda3\envs\cobra\Lib\site-packages\ultralytics\engine\trainer.py", line 207, in train self._do_train(world_size) File "C:\Users\derk_\anaconda3\envs\cobra\Lib\site-packages\ultralytics\engine\trainer.py", line 368, in _do_train self.run_callbacks("on_train_batch_start") File "C:\Users\derk_\anaconda3\envs\cobra\Lib\site-packages\ultralytics\engine\trainer.py", line 168, in run_callbacks callback(self) File "C:\Users\derk_\Documents\Universiteit\IRP\Research_Project\main.py", line 185, in batch_augmentation_callback batch = trainer.batch # Access the current batch ^^^^^^^^^^^^^ AttributeError: 'ClassificationTrainer' object has no attribute 'batch'My code
model = YOLO("yolov8m-cls.pt") model.add_callback("on_train_batch_start", batch_augmentation_callback) model.train(mode="classify", data=data_file_dir, epochs=args.n_epochs) # Where batch_augmentation_callback is my callback function def batch_augmentation_callback(trainer): batch = trainer.batch # This code line causes the error reported above images, labels = batch['img'], batch['label'] # More code below to create data augmentationContent of
trainerobject that is passed intobatch_augmentation_callback(my callback function)- trainer = {ClassificationTrainer} <ultralytics.models.yolo.classify.train.ClassificationTrainer object at 0x0000016929FA5010>
- accumulate = {int} 4
- amp = {bool} False
- args = {IterableSimpleNamespace} IterableSimpleNamespace(task='classify', mode='train', model='yolov8m-cls.pt', data='C:/Users/derk_/Documents/Universiteit/IRP...ugment='randaugment', erasing=0.4, crop_fraction=1.0, cfg=None, tracker='botsort.yaml', save_dir='C:\runs\classify\train53')
- batch_size = {int} 16
- best = {WindowsPath} WindowsPath('C:/runs/classify/train53/weights/best.pt')
- best_fitness = {NoneType} None
- callbacks = {defaultdict: 25} defaultdict(<class 'list'>, {'on_pretrain_routine_start': [<function on_pretrain_routine_start at 0x0000016929C79440>, <functi...C7A2A0>, <function on_export_start at 0x000001692A55C220>], 'on_export_end': [<function on_export_end at 0x0000016929C7A340>]})
- csv = {WindowsPath} WindowsPath('C:/runs/classify/train53/results.csv')
- data = {dict: 5} {'names': {0: '1', 1: '10', 2: '100', 3: '101', 4: '102', 5: '11', 6: '12', 7: '13', 8: '14', 9: '15', 10: '16', 11: '17', 12: '18', 13: '19', 14: '2', 15: '20', 16: '21', 17: '22', 18: '23', 19: '24', 20: '25', 21: '26', 22: '27', 23: '28', 24: '29', 25:
- device = {device} device(type='cpu')
- ema = {ModelEMA} <ultralytics.utils.torch_utils.ModelEMA object at 0x000001692AC80C90>
- epoch = {int} 0
- epoch_time = {NoneType} None
- epoch_time_start = {float} 1731355033.8569636
- epochs = {int} 1
- fitness = {NoneType} None
- hub_session = {NoneType} None
- last = {WindowsPath} WindowsPath('C:/runs/classify/train53/weights/last.pt')
- loss = {NoneType} None
- loss_names = {list: 1} ['loss']
- metrics = {dict: 3} {'metrics/accuracy_top1': 0, 'metrics/accuracy_top5': 0, 'val/loss': 0}
- model = {ClassificationModel} ClassificationModel(\n (model): Sequential(\n (0): Conv(\n (conv): Conv2d(3, 48, kernel_size=(3, 3), stride=(2, 2), padd...1)\n (drop): Dropout(p=0.0, inplace=True)\n (linear): Linear(in_features=1280, out_features=102, bias=True)\n )\n )\n)
- optimizer = {AdamW} AdamW (\nParameter Group 0\n amsgrad: False\n base_momentum: 0.85\n betas: (0.9499811807836418, 0.999)\n capturable: Fa... lr: 0.004018066447703833\n max_lr: 0.1\n max_momentum: 0.95\n maximize: False\n min_lr: 4e-07\n weight_decay: 0.0\n)
- plot_idx = {list: 6} [0, 1, 2, -3465, -3464, -3463]
- plots = {dict: 0} {}
- resume = {bool} False
- save_dir = {WindowsPath} WindowsPath('C:/runs/classify/train53')
- save_period = {int} 1
- scaler = {GradScaler} <torch.amp.grad_scaler.GradScaler object at 0x000001692921A0D0>
- scheduler = {OneCycleLR} <torch.optim.lr_scheduler.OneCycleLR object at 0x000001692ACF5210>
- start_epoch = {int} 0
- stop = {bool} False
- stopper = {EarlyStopping} <ultralytics.utils.torch_utils.EarlyStopping object at 0x000001692ACF7190>
- stride = {int} 32
- test_loader = {InfiniteDataLoader: 32} <ultralytics.data.build.InfiniteDataLoader object at 0x000001692AAD7B50>
- testset = {WindowsPath} WindowsPath('C:/Users/derk_/Documents/Universiteit/IRP/Research_Project/Oxford-Flower-dataset/jpg/val')
- tloss = {NoneType} None
- train_loader = {InfiniteDataLoader: 385} <ultralytics.data.build.InfiniteDataLoader object at 0x00000169297FFDD0>
- train_time_start = {float} 1731355033.8569636
- trainset = {WindowsPath} WindowsPath('C:/Users/derk_/Documents/Universiteit/IRP/Research_Project/Oxford-Flower-dataset/jpg/train')
- validator = {ClassificationValidator} <ultralytics.models.yolo.classify.val.ClassificationValidator object at 0x000001692AC80BD0>
- wdir = {WindowsPath} WindowsPath('C:/runs/classify/train53/weights')
Question
If it is right that
trainer.batchdoes not exist (in this case), which other object in trainer - as listed above in the content of trainer - can I extract the current batch?
Glenn JocherUltralytics(수정됨)The
trainer.batchattribute does not exist in the current implementation, and iteratingtrainer.train_loaderinside a callback would draw a different batch rather than the current one. Instead, overridepreprocess_batch(self, batch)in a custom trainer subclass to modify each batch before it is used.D3RK0(수정됨)
@glenn-jocher Many thanks for answering!
Okay, I have been able to access the batches via
trainer.train_loaderand subsequently apply data augmentation to each batch. However, ...Problem
... assigning the batch back (see also the code below) to
trainer.train_loaderis not possible, as I get:trainer.train_loader[i] = batch ~~~~~~~~~~~~~~~~~~~~^^^ TypeError: 'InfiniteDataLoader' object does not support item assignmentCode
def batches_augmentation_callback(trainer): for i, batch in enumerate(trainer.train_loader): images, labels = batch['img'], batch['cls'] cutmix_or_mixup = LoadOxfordFlowerDataset.data_augmentation(n_classes_in_batch=args.n_classes) images, labels = cutmix_or_mixup(images, labels) batch = {"img": images, "cls": labels} trainer.train_loader[i] = batch # BUG: trainer.train_loader object does not support item assignmentQuestion
How can I return the augmented batch to the
trainerobject if assignment does not work?
Glenn JocherUltralyticsYou cannot directly assign to
trainer.train_loader. Instead, apply your augmentation within the loop and yield the modified batch back to the training process. Consider using a custom data loader or modifying the dataset directly for more complex augmentations.