Callback
Framework Ultralytics hỗ trợ callback, đóng vai trò là điểm truy cập tại các giai đoạn quan trọng của các mode train, val, predict và export. Tùy theo loại thao tác, mỗi callback nhận một đối tượng Trainer, Validator, Predictor hoặc Exporter.
Xem: Cách sử dụng callback của Ultralytics | Callback dự đoán, huấn luyện, xác thực và xuất model | Ultralytics YOLO26 🚀
Ví dụ#
Trả về thông tin bổ sung cùng với kết quả dự đoán#
Ví dụ này trả về khung hình ban đầu cùng với từng đối tượng kết quả:
from ultralytics import YOLO
def on_predict_batch_end(predictor):
"""Combine prediction results with corresponding frames."""
_, image, _ = predictor.batch
# Đảm bảo image là một danh sách
image = image if isinstance(image, list) else [image]
# Kết hợp kết quả dự đoán với các frame tương ứng
predictor.results = zip(predictor.results, image)
# Tạo một instance YOLO model
model = YOLO("yolo26n.pt")
# Thêm callback tùy chỉnh vào model
model.add_callback("on_predict_batch_end", on_predict_batch_end)
# Lặp qua các kết quả và frame
for result, frame in model.predict(): # hoặc model.track()
passĐăng ký PyTorch Forward Hook trước khi huấn luyện#
model.train() tạo model huấn luyện từ cấu hình model và nạp các trọng số đã tải vào model đó. Các hook PyTorch được đăng ký trực tiếp trên model.model trước lời gọi này là trạng thái runtime, vì vậy model huấn luyện được tạo lại sẽ không kế thừa chúng. Hãy đăng ký hook huấn luyện trong on_pretrain_routine_end, sau khi hoàn tất thiết lập model:
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() xử lý cả hoạt động huấn luyện trên một thiết bị lẫn hoạt động huấn luyện DistributedDataParallel. Không gắn hook được định nghĩa cục bộ vào trainer.ema.ema, vì checkpoint huấn luyện tuần tự hóa model EMA và một tiến trình khác có thể không nhập được callback khi tải checkpoint. Nếu cần chạy cùng một bước tiền xử lý trong quá trình validation khi huấn luyện, hãy triển khai bước đó dưới dạng thành phần model có thể import thay vì hook runtime. Cơ chế khôi phục NaN tạo lại EMA từ model huấn luyện, do đó hook đăng ký theo cách này sẽ được sao chép vào EMA và các checkpoint đã lưu sau khi khôi phục; hãy định nghĩa hàm hook trong một module có thể import nếu cần tải checkpoint trong một tiến trình khác.
model.val() độc lập sao chép model đã tải cho mỗi lần gọi. Prediction tạo và lưu cache một bản sao trong lần gọi đầu tiên, vì vậy hãy đăng ký hook trên model.model trước lần gọi model.predict() hoặc model.track() đầu tiên; các hook được thêm sau đó sẽ không được áp dụng cho predictor đã lưu cache. Đăng ký lại hook runtime sau khi tải checkpoint trong một tiến trình mới.
Truy cập các metric của model bằng callback on_model_save#
Ví dụ này minh họa cách lấy thông tin chi tiết về quá trình huấn luyện, chẳng hạn như điểm best_fitness, total_loss và các metric khác, sau khi checkpoint được lưu bằng callback on_model_save.
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)Tất cả callback#
Dưới đây là tất cả callback được hỗ trợ. Để biết thêm chi tiết, hãy tham khảo mã nguồn của callback.
Callback của Trainer#
| Callback | Mô tả |
|---|---|
on_pretrain_routine_start | Được kích hoạt khi bắt đầu quy trình tiền huấn luyện, trước khi tải dữ liệu và thiết lập model. |
on_pretrain_routine_end | Được kích hoạt khi kết thúc quy trình tiền huấn luyện, sau khi hoàn tất tải dữ liệu và thiết lập model. |
on_train_start | Được kích hoạt khi bắt đầu huấn luyện, trước khi epoch đầu tiên bắt đầu. |
on_train_epoch_start | Được kích hoạt vào đầu mỗi epoch huấn luyện, trước khi bắt đầu lặp qua các batch. |
on_train_batch_start | Được kích hoạt khi bắt đầu mỗi batch huấn luyện, trước lượt forward. |
optimizer_step | Được kích hoạt trong bước optimizer. Dành cho các tích hợp tùy chỉnh; vòng lặp huấn luyện mặc định không gọi callback này. |
on_before_zero_grad | Được kích hoạt trước khi đặt gradient về 0. Dành cho các tích hợp tùy chỉnh; vòng lặp huấn luyện mặc định không gọi callback này. |
on_train_batch_end | Được kích hoạt khi kết thúc mỗi batch huấn luyện, sau lượt backward. Bước optimizer có thể được hoãn do tích lũy gradient. |
on_train_epoch_end | Được kích hoạt khi kết thúc mỗi epoch huấn luyện, sau khi xử lý tất cả batch nhưng trước validation. Metric validation và fitness có thể chưa khả dụng. |
on_model_save | Được kích hoạt khi lưu checkpoint của model, sau validation. |
on_fit_epoch_end | Được kích hoạt khi kết thúc mỗi epoch fit (train + val), sau validation và mọi thao tác lưu checkpoint. Metric validation khả dụng, và fitness khả dụng cho lời gọi huấn luyện theo từng epoch. Callback này cũng được gọi trong quá trình đánh giá model tốt nhất cuối cùng, khi không lưu checkpoint và fitness có thể không hiện diện. |
on_train_end | Được kích hoạt khi quy trình huấn luyện kết thúc, sau khi đánh giá cuối cùng model tốt nhất. |
on_params_update | Được kích hoạt khi các tham số của model được cập nhật. Dành cho các tích hợp tùy chỉnh; vòng lặp huấn luyện mặc định không gọi callback này. |
teardown | Được kích hoạt khi quy trình huấn luyện đang được dọn dẹp. |
Callback của Validator#
| Callback | Mô tả |
|---|---|
on_val_start | Được kích hoạt khi bắt đầu validation. |
on_val_batch_start | Được kích hoạt khi bắt đầu mỗi batch validation. |
on_val_batch_end | Được kích hoạt khi kết thúc mỗi batch validation. |
on_val_end | Được kích hoạt khi validation kết thúc. |
Callback của Predictor#
| Callback | Mô tả |
|---|---|
on_predict_start | Được kích hoạt khi quy trình prediction bắt đầu. |
on_predict_batch_start | Được kích hoạt khi bắt đầu mỗi batch prediction. |
on_predict_postprocess_end | Được kích hoạt khi kết thúc quá trình hậu xử lý prediction. |
on_predict_batch_end | Được kích hoạt khi kết thúc mỗi batch prediction. |
on_predict_end | Được kích hoạt khi quy trình prediction kết thúc. |
Callback của Exporter#
| Callback | Mô tả |
|---|---|
on_export_start | Được kích hoạt khi bắt đầu quy trình export. |
on_export_end | Được kích hoạt khi kết thúc quy trình export. |
Câu hỏi thường gặp#
Callback Ultralytics là các điểm truy cập được kích hoạt trong những giai đoạn quan trọng của hoạt động model, chẳng hạn như huấn luyện, xác thực, dự đoán và export. Callback cho phép bạn thêm chức năng tùy chỉnh tại các thời điểm cụ thể trong quy trình mà không cần sửa đổi thư viện. Tùy theo loại thao tác, mỗi callback nhận một đối tượng
Trainer,Validator,PredictorhoặcExporter.Để sử dụng callback, hãy định nghĩa một hàm và thêm hàm đó vào model bằng phương thức
model.add_callback(). Sau đây là ví dụ về cách trả về thông tin bổ sung trong quá trình prediction: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(): passTùy chỉnh quy trình huấn luyện Ultralytics bằng cách chèn logic vào các giai đoạn cụ thể của quá trình huấn luyện. Ultralytics YOLO cung cấp nhiều callback huấn luyện, chẳng hạn như
on_train_start,on_train_endvàon_train_batch_end, cho phép bạn thêm metric, xử lý hoặc ghi log tùy chỉnh.Sau đây là cách ghi log learning rate của từng nhóm tham số optimizer vào cuối mỗi epoch huấn luyện:
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)MẹoBạn không cần callback để đóng băng các thống kê BatchNorm khi sử dụng
freeze: trainer tự động chuyển các layer BatchNorm thuộc những layer bị đóng băng sang chế độ eval khi bắt đầu mỗi epoch.Để biết thêm chi tiết về cách sử dụng callback huấn luyện hiệu quả, hãy xem Hướng dẫn huấn luyện.
Callback validation cho phép bạn thêm xử lý tùy chỉnh, ghi log hoặc tính metric trong quá trình đánh giá model. Các callback như
on_val_start,on_val_batch_endvàon_val_endcung cấp điểm truy cập để chèn logic tùy chỉnh ở từng giai đoạn validation.Ví dụ: vẽ tất cả batch validation thay vì chỉ ba batch đầu tiên:
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")Để tìm hiểu thêm về cách tích hợp callback vào quy trình validation, hãy xem Hướng dẫn validation.
Để gắn callback tùy chỉnh cho chế độ prediction trong Ultralytics YOLO, hãy định nghĩa một hàm callback và đăng ký hàm đó với quy trình prediction. Các callback prediction thường dùng gồm
on_predict_start,on_predict_batch_endvàon_predict_end. Các callback này cho phép sửa đổi đầu ra prediction và tích hợp thêm chức năng, chẳng hạn như ghi log dữ liệu hoặc chuyển đổi kết quả.Sau đây là ví dụ về callback tùy chỉnh lưu các kết quả prediction dựa trên việc có hay không có một đối tượng thuộc lớp cụ thể:
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Để tìm hiểu cách sử dụng toàn diện hơn, hãy tham khảo Hướng dẫn prediction, bao gồm hướng dẫn chi tiết và các tùy chọn tùy chỉnh bổ sung.
Ultralytics YOLO hỗ trợ nhiều cách triển khai callback thiết thực để cải tiến và tùy chỉnh các giai đoạn khác nhau như huấn luyện, validation và prediction. Một số ví dụ thực tế gồm:
- Ghi log metric tùy chỉnh: Ghi log các metric bổ sung ở những giai đoạn khác nhau, chẳng hạn như cuối epoch huấn luyện hoặc validation.
- Tăng cường dữ liệu: Triển khai các phép biến đổi hoặc tăng cường dữ liệu tùy chỉnh trong quá trình prediction hoặc trong các batch huấn luyện.
- Kết quả trung gian: Lưu các kết quả trung gian, chẳng hạn như prediction hoặc frame, để phân tích hoặc trực quan hóa thêm.
Ví dụ: Kết hợp frame với kết quả prediction trong quá trình prediction bằng
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(): passKhám phá mã nguồn callback để xem thêm tùy chọn và ví dụ.
Bình luận15
Đặt câu hỏi, chia sẻ kết quả hoặc giúp đỡ người khác.
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(đã chỉnh sửa)@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(đã chỉnh sửa)
@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(đã chỉnh sửa)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(đã chỉnh sửa)
@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.