─░├žeri─če ge├ž

Referans i├žin ultralytics/engine/model.py

Not

Bu dosya https://github.com/ultralytics/ultralytics/blob/main/ ultralytics/engine/model .py adresinde mevcuttur. Bir sorun tespit ederseniz, l├╝tfen bir ├çekme ─░ste─či ­čŤá´ŞĆ ile katk─▒da bulunarak d├╝zeltmeye yard─▒mc─▒ olun. Te┼čekk├╝rler ­čÖĆ!



ultralytics.engine.model.Model

├ťsler: Module

Farkl─▒ model t├╝rleri aras─▒nda API'leri birle┼čtiren YOLO modellerini uygulamak i├žin bir temel s─▒n─▒f.

Bu s─▒n─▒f, e─čitim gibi YOLO modelleriyle ilgili ├že┼čitli i┼člemler i├žin ortak bir aray├╝z sa─člar, do─črulama, tahmin, d─▒┼ča aktarma ve k─▒yaslama. A┼ča─č─▒dakiler de dahil olmak ├╝zere farkl─▒ model t├╝rlerini ele al─▒r yerel dosyalardan, Ultralytics HUB veya Triton Server'dan y├╝klenebilir. S─▒n─▒f esnek olacak ┼čekilde tasarlanm─▒┼čt─▒r ve Farkl─▒ g├Ârevler ve model konfig├╝rasyonlar─▒ i├žin geni┼čletilebilir.

Parametreler:

─░sim Tip A├ž─▒klama Varsay─▒lan
model Union[str, Path]

Y├╝klenecek veya olu┼čturulacak modelin yolu veya ad─▒. Bu yerel bir dosya olabilir yolu, Ultralytics HUB'dan bir model ad─▒ veya bir Triton Sunucu modeli. Varsay─▒lan de─čer 'yolov8n.pt' ┼čeklindedir.

'yolov8n.pt'
task Any

YOLO modeliyle ili┼čkili g├Ârev t├╝r├╝. Bu, modelin g├Ârev t├╝r├╝n├╝ belirtmek i├žin kullan─▒labilir. Nesne alg─▒lama, segmentasyon vb. gibi uygulama alan─▒. Varsay─▒lan de─čer Yok'tur.

None
verbose bool

True ise, modelin i┼člemleri s─▒ras─▒nda ayr─▒nt─▒l─▒ ├ž─▒kt─▒y─▒ etkinle┼čtirir. Varsay─▒lan de─čer False'dir.

False

Nitelikler:

─░sim Tip A├ž─▒klama
callbacks dict

Model i┼člemleri s─▒ras─▒nda ├že┼čitli olaylar i├žin geri arama i┼člevleri s├Âzl├╝─č├╝.

predictor BasePredictor

Tahmin yapmak i├žin kullan─▒lan tahmin edici nesne.

model Module

Altta yatan PyTorch modeli.

trainer BaseTrainer

Modeli e─čitmek i├žin kullan─▒lan e─čitmen nesnesi.

ckpt dict

Model bir *.pt dosyas─▒ndan y├╝klenmi┼čse kontrol noktas─▒ verileri.

cfg str

Bir *.yaml dosyas─▒ndan y├╝klenmi┼čse modelin yap─▒land─▒rmas─▒.

ckpt_path str

Kontrol noktas─▒ dosyas─▒n─▒n yolu.

overrides dict

Model yap─▒land─▒rmas─▒ i├žin ge├žersiz k─▒lmalar s├Âzl├╝─č├╝.

metrics dict

En son e─čitim/do─črulama ├Âl├ž├╝mleri.

session HUBTrainingSession

Varsa, Ultralytics HUB oturumu.

task str

Modelin ama├žland─▒─č─▒ g├Ârev t├╝r├╝.

model_name str

Modelin ad─▒.

Y├Ântemler:

─░sim A├ž─▒klama
__call__

Model ├Ârne─činin ├ža─čr─▒labilir olmas─▒n─▒ sa─člayan tahmin y├Ântemi i├žin takma ad.

_new

Bir yap─▒land─▒rma dosyas─▒na dayal─▒ olarak yeni bir model ba┼člat─▒r.

_load

Bir kontrol noktas─▒ dosyas─▒ndan bir model y├╝kler.

_check_is_pytorch_model

Modelin bir PyTorch modeli olmas─▒n─▒ sa─člar.

reset_weights

Modelin a─č─▒rl─▒klar─▒n─▒ ilk durumlar─▒na s─▒f─▒rlar.

load

Model a─č─▒rl─▒klar─▒n─▒ belirtilen bir dosyadan y├╝kler.

save

Modelin ge├žerli durumunu bir dosyaya kaydeder.

info

Model hakk─▒ndaki bilgileri g├╝nl├╝─če kaydeder veya d├Ând├╝r├╝r.

fuse

Optimize edilmi┼č ├ž─▒kar─▒m i├žin Conv2d ve BatchNorm2d katmanlar─▒n─▒ birle┼čtirir.

predict

Nesne alg─▒lama tahminlerini ger├žekle┼čtirir.

track

Nesne takibi ger├žekle┼čtirir.

val

Modeli bir veri k├╝mesi ├╝zerinde do─črular.

benchmark

Modeli ├že┼čitli d─▒┼ča aktarma formatlar─▒nda k─▒yaslar.

export

Modeli farkl─▒ formatlarda d─▒┼ča aktar─▒r.

train

Modeli bir veri k├╝mesi ├╝zerinde e─čitir.

tune

Hiperparametre ayarlamas─▒ ger├žekle┼čtirir.

_apply

Modelin tens├Ârlerine bir fonksiyon uygular.

add_callback

Bir olay i├žin geri arama i┼člevi ekler.

clear_callback

Bir olay i├žin t├╝m geri ├ža─č─▒rmalar─▒ temizler.

reset_callbacks

T├╝m geri ├ža─č─▒rmalar─▒ varsay─▒lan i┼člevlerine s─▒f─▒rlar.

_get_hub_session

Bir Ultralytics HUB oturumu al─▒r veya olu┼čturur.

is_triton_model

Bir modelin Triton Server modeli olup olmad─▒─č─▒n─▒ kontrol eder.

is_hub_model

Bir modelin Ultralytics HUB modeli olup olmad─▒─č─▒n─▒ kontrol eder.

_reset_ckpt_args

Bir PyTorch modeli y├╝klenirken kontrol noktas─▒ arg├╝manlar─▒n─▒ s─▒f─▒rlar.

_smart_load

Model g├Ârevine g├Âre uygun mod├╝l├╝ y├╝kler.

task_map

Model g├Ârevlerinden kar┼č─▒l─▒k gelen s─▒n─▒flara bir e┼čleme sa─člar.

Zamlar:

Tip A├ž─▒klama
FileNotFoundError

Belirtilen model dosyas─▒ mevcut de─čilse veya eri┼čilemiyorsa.

ValueError

Model dosyas─▒ veya yap─▒land─▒rma ge├žersizse veya desteklenmiyorsa.

ImportError

Belirli model t├╝rleri i├žin gerekli ba─č─▒ml─▒l─▒klar (HUB SDK gibi) y├╝klenmemi┼čse.

TypeError

Model gerekti─činde bir PyTorch modeli de─čilse.

AttributeError

Gerekli nitelikler veya y├Ântemler uygulanmam─▒┼čsa veya mevcut de─čilse.

NotImplementedError

Belirli bir model g├Ârevi veya modu desteklenmiyorsa.

Kaynak kodu ultralytics/engine/model.py
 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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
class Model(nn.Module):
    """
    A base class for implementing YOLO models, unifying APIs across different model types.

    This class provides a common interface for various operations related to YOLO models, such as training,
    validation, prediction, exporting, and benchmarking. It handles different types of models, including those
    loaded from local files, Ultralytics HUB, or Triton Server. The class is designed to be flexible and
    extendable for different tasks and model configurations.

    Args:
        model (Union[str, Path], optional): Path or name of the model to load or create. This can be a local file
            path, a model name from Ultralytics HUB, or a Triton Server model. Defaults to 'yolov8n.pt'.
        task (Any, optional): The task type associated with the YOLO model. This can be used to specify the model's
            application domain, such as object detection, segmentation, etc. Defaults to None.
        verbose (bool, optional): If True, enables verbose output during the model's operations. Defaults to False.

    Attributes:
        callbacks (dict): A dictionary of callback functions for various events during model operations.
        predictor (BasePredictor): The predictor object used for making predictions.
        model (nn.Module): The underlying PyTorch model.
        trainer (BaseTrainer): The trainer object used for training the model.
        ckpt (dict): The checkpoint data if the model is loaded from a *.pt file.
        cfg (str): The configuration of the model if loaded from a *.yaml file.
        ckpt_path (str): The path to the checkpoint file.
        overrides (dict): A dictionary of overrides for model configuration.
        metrics (dict): The latest training/validation metrics.
        session (HUBTrainingSession): The Ultralytics HUB session, if applicable.
        task (str): The type of task the model is intended for.
        model_name (str): The name of the model.

    Methods:
        __call__: Alias for the predict method, enabling the model instance to be callable.
        _new: Initializes a new model based on a configuration file.
        _load: Loads a model from a checkpoint file.
        _check_is_pytorch_model: Ensures that the model is a PyTorch model.
        reset_weights: Resets the model's weights to their initial state.
        load: Loads model weights from a specified file.
        save: Saves the current state of the model to a file.
        info: Logs or returns information about the model.
        fuse: Fuses Conv2d and BatchNorm2d layers for optimized inference.
        predict: Performs object detection predictions.
        track: Performs object tracking.
        val: Validates the model on a dataset.
        benchmark: Benchmarks the model on various export formats.
        export: Exports the model to different formats.
        train: Trains the model on a dataset.
        tune: Performs hyperparameter tuning.
        _apply: Applies a function to the model's tensors.
        add_callback: Adds a callback function for an event.
        clear_callback: Clears all callbacks for an event.
        reset_callbacks: Resets all callbacks to their default functions.
        _get_hub_session: Retrieves or creates an Ultralytics HUB session.
        is_triton_model: Checks if a model is a Triton Server model.
        is_hub_model: Checks if a model is an Ultralytics HUB model.
        _reset_ckpt_args: Resets checkpoint arguments when loading a PyTorch model.
        _smart_load: Loads the appropriate module based on the model task.
        task_map: Provides a mapping from model tasks to corresponding classes.

    Raises:
        FileNotFoundError: If the specified model file does not exist or is inaccessible.
        ValueError: If the model file or configuration is invalid or unsupported.
        ImportError: If required dependencies for specific model types (like HUB SDK) are not installed.
        TypeError: If the model is not a PyTorch model when required.
        AttributeError: If required attributes or methods are not implemented or available.
        NotImplementedError: If a specific model task or mode is not supported.
    """

    def __init__(
        self,
        model: Union[str, Path] = "yolov8n.pt",
        task: str = None,
        verbose: bool = False,
    ) -> None:
        """
        Initializes a new instance of the YOLO model class.

        This constructor sets up the model based on the provided model path or name. It handles various types of model
        sources, including local files, Ultralytics HUB models, and Triton Server models. The method initializes several
        important attributes of the model and prepares it for operations like training, prediction, or export.

        Args:
            model (Union[str, Path], optional): The path or model file to load or create. This can be a local
                file path, a model name from Ultralytics HUB, or a Triton Server model. Defaults to 'yolov8n.pt'.
            task (Any, optional): The task type associated with the YOLO model, specifying its application domain.
                Defaults to None.
            verbose (bool, optional): If True, enables verbose output during the model's initialization and subsequent
                operations. Defaults to False.

        Raises:
            FileNotFoundError: If the specified model file does not exist or is inaccessible.
            ValueError: If the model file or configuration is invalid or unsupported.
            ImportError: If required dependencies for specific model types (like HUB SDK) are not installed.
        """
        super().__init__()
        self.callbacks = callbacks.get_default_callbacks()
        self.predictor = None  # reuse predictor
        self.model = None  # model object
        self.trainer = None  # trainer object
        self.ckpt = None  # if loaded from *.pt
        self.cfg = None  # if loaded from *.yaml
        self.ckpt_path = None
        self.overrides = {}  # overrides for trainer object
        self.metrics = None  # validation/training metrics
        self.session = None  # HUB session
        self.task = task  # task type
        model = str(model).strip()

        # Check if Ultralytics HUB model from https://hub.ultralytics.com
        if self.is_hub_model(model):
            # Fetch model from HUB
            checks.check_requirements("hub-sdk>=0.0.6")
            self.session = self._get_hub_session(model)
            model = self.session.model_file

        # Check if Triton Server model
        elif self.is_triton_model(model):
            self.model_name = self.model = model
            self.task = task
            return

        # Load or create new YOLO model
        if Path(model).suffix in {".yaml", ".yml"}:
            self._new(model, task=task, verbose=verbose)
        else:
            self._load(model, task=task)

    def __call__(
        self,
        source: Union[str, Path, int, list, tuple, np.ndarray, torch.Tensor] = None,
        stream: bool = False,
        **kwargs,
    ) -> list:
        """
        An alias for the predict method, enabling the model instance to be callable.

        This method simplifies the process of making predictions by allowing the model instance to be called directly
        with the required arguments for prediction.

        Args:
            source (str | Path | int | PIL.Image | np.ndarray, optional): The source of the image for making
                predictions. Accepts various types, including file paths, URLs, PIL images, and numpy arrays.
                Defaults to None.
            stream (bool, optional): If True, treats the input source as a continuous stream for predictions.
                Defaults to False.
            **kwargs (any): Additional keyword arguments for configuring the prediction process.

        Returns:
            (List[ultralytics.engine.results.Results]): A list of prediction results, encapsulated in the Results class.
        """
        return self.predict(source, stream, **kwargs)

    @staticmethod
    def _get_hub_session(model: str):
        """Creates a session for Hub Training."""
        from ultralytics.hub.session import HUBTrainingSession

        session = HUBTrainingSession(model)
        return session if session.client.authenticated else None

    @staticmethod
    def is_triton_model(model: str) -> bool:
        """Is model a Triton Server URL string, i.e. <scheme>://<netloc>/<endpoint>/<task_name>"""
        from urllib.parse import urlsplit

        url = urlsplit(model)
        return url.netloc and url.path and url.scheme in {"http", "grpc"}

    @staticmethod
    def is_hub_model(model: str) -> bool:
        """Check if the provided model is a HUB model."""
        return any(
            (
                model.startswith(f"{HUB_WEB_ROOT}/models/"),  # i.e. https://hub.ultralytics.com/models/MODEL_ID
                [len(x) for x in model.split("_")] == [42, 20],  # APIKEY_MODEL
                len(model) == 20 and not Path(model).exists() and all(x not in model for x in "./\\"),  # MODEL
            )
        )

    def _new(self, cfg: str, task=None, model=None, verbose=False) -> None:
        """
        Initializes a new model and infers the task type from the model definitions.

        Args:
            cfg (str): model configuration file
            task (str | None): model task
            model (BaseModel): Customized model.
            verbose (bool): display model info on load
        """
        cfg_dict = yaml_model_load(cfg)
        self.cfg = cfg
        self.task = task or guess_model_task(cfg_dict)
        self.model = (model or self._smart_load("model"))(cfg_dict, verbose=verbose and RANK == -1)  # build model
        self.overrides["model"] = self.cfg
        self.overrides["task"] = self.task

        # Below added to allow export from YAMLs
        self.model.args = {**DEFAULT_CFG_DICT, **self.overrides}  # combine default and model args (prefer model args)
        self.model.task = self.task
        self.model_name = cfg

    def _load(self, weights: str, task=None) -> None:
        """
        Initializes a new model and infers the task type from the model head.

        Args:
            weights (str): model checkpoint to be loaded
            task (str | None): model task
        """
        if weights.lower().startswith(("https://", "http://", "rtsp://", "rtmp://", "tcp://")):
            weights = checks.check_file(weights)  # automatically download and return local filename
        weights = checks.check_model_file_from_stem(weights)  # add suffix, i.e. yolov8n -> yolov8n.pt

        if Path(weights).suffix == ".pt":
            self.model, self.ckpt = attempt_load_one_weight(weights)
            self.task = self.model.args["task"]
            self.overrides = self.model.args = self._reset_ckpt_args(self.model.args)
            self.ckpt_path = self.model.pt_path
        else:
            weights = checks.check_file(weights)  # runs in all cases, not redundant with above call
            self.model, self.ckpt = weights, None
            self.task = task or guess_model_task(weights)
            self.ckpt_path = weights
        self.overrides["model"] = weights
        self.overrides["task"] = self.task
        self.model_name = weights

    def _check_is_pytorch_model(self) -> None:
        """Raises TypeError is model is not a PyTorch model."""
        pt_str = isinstance(self.model, (str, Path)) and Path(self.model).suffix == ".pt"
        pt_module = isinstance(self.model, nn.Module)
        if not (pt_module or pt_str):
            raise TypeError(
                f"model='{self.model}' should be a *.pt PyTorch model to run this method, but is a different format. "
                f"PyTorch models can train, val, predict and export, i.e. 'model.train(data=...)', but exported "
                f"formats like ONNX, TensorRT etc. only support 'predict' and 'val' modes, "
                f"i.e. 'yolo predict model=yolov8n.onnx'.\nTo run CUDA or MPS inference please pass the device "
                f"argument directly in your inference command, i.e. 'model.predict(source=..., device=0)'"
            )

    def reset_weights(self) -> "Model":
        """
        Resets the model parameters to randomly initialized values, effectively discarding all training information.

        This method iterates through all modules in the model and resets their parameters if they have a
        'reset_parameters' method. It also ensures that all parameters have 'requires_grad' set to True, enabling them
        to be updated during training.

        Returns:
            self (ultralytics.engine.model.Model): The instance of the class with reset weights.

        Raises:
            AssertionError: If the model is not a PyTorch model.
        """
        self._check_is_pytorch_model()
        for m in self.model.modules():
            if hasattr(m, "reset_parameters"):
                m.reset_parameters()
        for p in self.model.parameters():
            p.requires_grad = True
        return self

    def load(self, weights: Union[str, Path] = "yolov8n.pt") -> "Model":
        """
        Loads parameters from the specified weights file into the model.

        This method supports loading weights from a file or directly from a weights object. It matches parameters by
        name and shape and transfers them to the model.

        Args:
            weights (str | Path): Path to the weights file or a weights object. Defaults to 'yolov8n.pt'.

        Returns:
            self (ultralytics.engine.model.Model): The instance of the class with loaded weights.

        Raises:
            AssertionError: If the model is not a PyTorch model.
        """
        self._check_is_pytorch_model()
        if isinstance(weights, (str, Path)):
            weights, self.ckpt = attempt_load_one_weight(weights)
        self.model.load(weights)
        return self

    def save(self, filename: Union[str, Path] = "saved_model.pt", use_dill=True) -> None:
        """
        Saves the current model state to a file.

        This method exports the model's checkpoint (ckpt) to the specified filename.

        Args:
            filename (str | Path): The name of the file to save the model to. Defaults to 'saved_model.pt'.
            use_dill (bool): Whether to try using dill for serialization if available. Defaults to True.

        Raises:
            AssertionError: If the model is not a PyTorch model.
        """
        self._check_is_pytorch_model()
        from datetime import datetime

        from ultralytics import __version__

        updates = {
            "date": datetime.now().isoformat(),
            "version": __version__,
            "license": "AGPL-3.0 License (https://ultralytics.com/license)",
            "docs": "https://docs.ultralytics.com",
        }
        torch.save({**self.ckpt, **updates}, filename, use_dill=use_dill)

    def info(self, detailed: bool = False, verbose: bool = True):
        """
        Logs or returns model information.

        This method provides an overview or detailed information about the model, depending on the arguments passed.
        It can control the verbosity of the output.

        Args:
            detailed (bool): If True, shows detailed information about the model. Defaults to False.
            verbose (bool): If True, prints the information. If False, returns the information. Defaults to True.

        Returns:
            (list): Various types of information about the model, depending on the 'detailed' and 'verbose' parameters.

        Raises:
            AssertionError: If the model is not a PyTorch model.
        """
        self._check_is_pytorch_model()
        return self.model.info(detailed=detailed, verbose=verbose)

    def fuse(self):
        """
        Fuses Conv2d and BatchNorm2d layers in the model.

        This method optimizes the model by fusing Conv2d and BatchNorm2d layers, which can improve inference speed.

        Raises:
            AssertionError: If the model is not a PyTorch model.
        """
        self._check_is_pytorch_model()
        self.model.fuse()

    def embed(
        self,
        source: Union[str, Path, int, list, tuple, np.ndarray, torch.Tensor] = None,
        stream: bool = False,
        **kwargs,
    ) -> list:
        """
        Generates image embeddings based on the provided source.

        This method is a wrapper around the 'predict()' method, focusing on generating embeddings from an image source.
        It allows customization of the embedding process through various keyword arguments.

        Args:
            source (str | int | PIL.Image | np.ndarray): The source of the image for generating embeddings.
                The source can be a file path, URL, PIL image, numpy array, etc. Defaults to None.
            stream (bool): If True, predictions are streamed. Defaults to False.
            **kwargs (any): Additional keyword arguments for configuring the embedding process.

        Returns:
            (List[torch.Tensor]): A list containing the image embeddings.

        Raises:
            AssertionError: If the model is not a PyTorch model.
        """
        if not kwargs.get("embed"):
            kwargs["embed"] = [len(self.model.model) - 2]  # embed second-to-last layer if no indices passed
        return self.predict(source, stream, **kwargs)

    def predict(
        self,
        source: Union[str, Path, int, list, tuple, np.ndarray, torch.Tensor] = None,
        stream: bool = False,
        predictor=None,
        **kwargs,
    ) -> List[Results]:
        """
        Performs predictions on the given image source using the YOLO model.

        This method facilitates the prediction process, allowing various configurations through keyword arguments.
        It supports predictions with custom predictors or the default predictor method. The method handles different
        types of image sources and can operate in a streaming mode. It also provides support for SAM-type models
        through 'prompts'.

        The method sets up a new predictor if not already present and updates its arguments with each call.
        It also issues a warning and uses default assets if the 'source' is not provided. The method determines if it
        is being called from the command line interface and adjusts its behavior accordingly, including setting defaults
        for confidence threshold and saving behavior.

        Args:
            source (str | int | PIL.Image | np.ndarray, optional): The source of the image for making predictions.
                Accepts various types, including file paths, URLs, PIL images, and numpy arrays. Defaults to ASSETS.
            stream (bool, optional): Treats the input source as a continuous stream for predictions. Defaults to False.
            predictor (BasePredictor, optional): An instance of a custom predictor class for making predictions.
                If None, the method uses a default predictor. Defaults to None.
            **kwargs (any): Additional keyword arguments for configuring the prediction process. These arguments allow
                for further customization of the prediction behavior.

        Returns:
            (List[ultralytics.engine.results.Results]): A list of prediction results, encapsulated in the Results class.

        Raises:
            AttributeError: If the predictor is not properly set up.
        """
        if source is None:
            source = ASSETS
            LOGGER.warning(f"WARNING ÔÜá´ŞĆ 'source' is missing. Using 'source={source}'.")

        is_cli = (ARGV[0].endswith("yolo") or ARGV[0].endswith("ultralytics")) and any(
            x in ARGV for x in ("predict", "track", "mode=predict", "mode=track")
        )

        custom = {"conf": 0.25, "batch": 1, "save": is_cli, "mode": "predict"}  # method defaults
        args = {**self.overrides, **custom, **kwargs}  # highest priority args on the right
        prompts = args.pop("prompts", None)  # for SAM-type models

        if not self.predictor:
            self.predictor = predictor or self._smart_load("predictor")(overrides=args, _callbacks=self.callbacks)
            self.predictor.setup_model(model=self.model, verbose=is_cli)
        else:  # only update args if predictor is already setup
            self.predictor.args = get_cfg(self.predictor.args, args)
            if "project" in args or "name" in args:
                self.predictor.save_dir = get_save_dir(self.predictor.args)
        if prompts and hasattr(self.predictor, "set_prompts"):  # for SAM-type models
            self.predictor.set_prompts(prompts)
        return self.predictor.predict_cli(source=source) if is_cli else self.predictor(source=source, stream=stream)

    def track(
        self,
        source: Union[str, Path, int, list, tuple, np.ndarray, torch.Tensor] = None,
        stream: bool = False,
        persist: bool = False,
        **kwargs,
    ) -> List[Results]:
        """
        Conducts object tracking on the specified input source using the registered trackers.

        This method performs object tracking using the model's predictors and optionally registered trackers. It is
        capable of handling different types of input sources such as file paths or video streams. The method supports
        customization of the tracking process through various keyword arguments. It registers trackers if they are not
        already present and optionally persists them based on the 'persist' flag.

        The method sets a default confidence threshold specifically for ByteTrack-based tracking, which requires low
        confidence predictions as input. The tracking mode is explicitly set in the keyword arguments.

        Args:
            source (str, optional): The input source for object tracking. It can be a file path, URL, or video stream.
            stream (bool, optional): Treats the input source as a continuous video stream. Defaults to False.
            persist (bool, optional): Persists the trackers between different calls to this method. Defaults to False.
            **kwargs (any): Additional keyword arguments for configuring the tracking process. These arguments allow
                for further customization of the tracking behavior.

        Returns:
            (List[ultralytics.engine.results.Results]): A list of tracking results, encapsulated in the Results class.

        Raises:
            AttributeError: If the predictor does not have registered trackers.
        """
        if not hasattr(self.predictor, "trackers"):
            from ultralytics.trackers import register_tracker

            register_tracker(self, persist)
        kwargs["conf"] = kwargs.get("conf") or 0.1  # ByteTrack-based method needs low confidence predictions as input
        kwargs["batch"] = kwargs.get("batch") or 1  # batch-size 1 for tracking in videos
        kwargs["mode"] = "track"
        return self.predict(source=source, stream=stream, **kwargs)

    def val(
        self,
        validator=None,
        **kwargs,
    ):
        """
        Validates the model using a specified dataset and validation configuration.

        This method facilitates the model validation process, allowing for a range of customization through various
        settings and configurations. It supports validation with a custom validator or the default validation approach.
        The method combines default configurations, method-specific defaults, and user-provided arguments to configure
        the validation process. After validation, it updates the model's metrics with the results obtained from the
        validator.

        The method supports various arguments that allow customization of the validation process. For a comprehensive
        list of all configurable options, users should refer to the 'configuration' section in the documentation.

        Args:
            validator (BaseValidator, optional): An instance of a custom validator class for validating the model. If
                None, the method uses a default validator. Defaults to None.
            **kwargs (any): Arbitrary keyword arguments representing the validation configuration. These arguments are
                used to customize various aspects of the validation process.

        Returns:
            (dict): Validation metrics obtained from the validation process.

        Raises:
            AssertionError: If the model is not a PyTorch model.
        """
        custom = {"rect": True}  # method defaults
        args = {**self.overrides, **custom, **kwargs, "mode": "val"}  # highest priority args on the right

        validator = (validator or self._smart_load("validator"))(args=args, _callbacks=self.callbacks)
        validator(model=self.model)
        self.metrics = validator.metrics
        return validator.metrics

    def benchmark(
        self,
        **kwargs,
    ):
        """
        Benchmarks the model across various export formats to evaluate performance.

        This method assesses the model's performance in different export formats, such as ONNX, TorchScript, etc.
        It uses the 'benchmark' function from the ultralytics.utils.benchmarks module. The benchmarking is configured
        using a combination of default configuration values, model-specific arguments, method-specific defaults, and
        any additional user-provided keyword arguments.

        The method supports various arguments that allow customization of the benchmarking process, such as dataset
        choice, image size, precision modes, device selection, and verbosity. For a comprehensive list of all
        configurable options, users should refer to the 'configuration' section in the documentation.

        Args:
            **kwargs (any): Arbitrary keyword arguments to customize the benchmarking process. These are combined with
                default configurations, model-specific arguments, and method defaults.

        Returns:
            (dict): A dictionary containing the results of the benchmarking process.

        Raises:
            AssertionError: If the model is not a PyTorch model.
        """
        self._check_is_pytorch_model()
        from ultralytics.utils.benchmarks import benchmark

        custom = {"verbose": False}  # method defaults
        args = {**DEFAULT_CFG_DICT, **self.model.args, **custom, **kwargs, "mode": "benchmark"}
        return benchmark(
            model=self,
            data=kwargs.get("data"),  # if no 'data' argument passed set data=None for default datasets
            imgsz=args["imgsz"],
            half=args["half"],
            int8=args["int8"],
            device=args["device"],
            verbose=kwargs.get("verbose"),
        )

    def export(
        self,
        **kwargs,
    ) -> str:
        """
        Exports the model to a different format suitable for deployment.

        This method facilitates the export of the model to various formats (e.g., ONNX, TorchScript) for deployment
        purposes. It uses the 'Exporter' class for the export process, combining model-specific overrides, method
        defaults, and any additional arguments provided. The combined arguments are used to configure export settings.

        The method supports a wide range of arguments to customize the export process. For a comprehensive list of all
        possible arguments, refer to the 'configuration' section in the documentation.

        Args:
            **kwargs (any): Arbitrary keyword arguments to customize the export process. These are combined with the
                model's overrides and method defaults.

        Returns:
            (str): The exported model filename in the specified format, or an object related to the export process.

        Raises:
            AssertionError: If the model is not a PyTorch model.
        """
        self._check_is_pytorch_model()
        from .exporter import Exporter

        custom = {"imgsz": self.model.args["imgsz"], "batch": 1, "data": None, "verbose": False}  # method defaults
        args = {**self.overrides, **custom, **kwargs, "mode": "export"}  # highest priority args on the right
        return Exporter(overrides=args, _callbacks=self.callbacks)(model=self.model)

    def train(
        self,
        trainer=None,
        **kwargs,
    ):
        """
        Trains the model using the specified dataset and training configuration.

        This method facilitates model training with a range of customizable settings and configurations. It supports
        training with a custom trainer or the default training approach defined in the method. The method handles
        different scenarios, such as resuming training from a checkpoint, integrating with Ultralytics HUB, and
        updating model and configuration after training.

        When using Ultralytics HUB, if the session already has a loaded model, the method prioritizes HUB training
        arguments and issues a warning if local arguments are provided. It checks for pip updates and combines default
        configurations, method-specific defaults, and user-provided arguments to configure the training process. After
        training, it updates the model and its configurations, and optionally attaches metrics.

        Args:
            trainer (BaseTrainer, optional): An instance of a custom trainer class for training the model. If None, the
                method uses a default trainer. Defaults to None.
            **kwargs (any): Arbitrary keyword arguments representing the training configuration. These arguments are
                used to customize various aspects of the training process.

        Returns:
            (dict | None): Training metrics if available and training is successful; otherwise, None.

        Raises:
            AssertionError: If the model is not a PyTorch model.
            PermissionError: If there is a permission issue with the HUB session.
            ModuleNotFoundError: If the HUB SDK is not installed.
        """
        self._check_is_pytorch_model()
        if hasattr(self.session, "model") and self.session.model.id:  # Ultralytics HUB session with loaded model
            if any(kwargs):
                LOGGER.warning("WARNING ÔÜá´ŞĆ using HUB training arguments, ignoring local training arguments.")
            kwargs = self.session.train_args  # overwrite kwargs

        checks.check_pip_update_available()

        overrides = yaml_load(checks.check_yaml(kwargs["cfg"])) if kwargs.get("cfg") else self.overrides
        custom = {
            # NOTE: handle the case when 'cfg' includes 'data'.
            "data": overrides.get("data") or DEFAULT_CFG_DICT["data"] or TASK2DATA[self.task],
            "model": self.overrides["model"],
            "task": self.task,
        }  # method defaults
        args = {**overrides, **custom, **kwargs, "mode": "train"}  # highest priority args on the right
        if args.get("resume"):
            args["resume"] = self.ckpt_path

        self.trainer = (trainer or self._smart_load("trainer"))(overrides=args, _callbacks=self.callbacks)
        if not args.get("resume"):  # manually set model only if not resuming
            self.trainer.model = self.trainer.get_model(weights=self.model if self.ckpt else None, cfg=self.model.yaml)
            self.model = self.trainer.model

            if SETTINGS["hub"] is True and not self.session:
                # Create a model in HUB
                try:
                    self.session = self._get_hub_session(self.model_name)
                    if self.session:
                        self.session.create_model(args)
                        # Check model was created
                        if not getattr(self.session.model, "id", None):
                            self.session = None
                except (PermissionError, ModuleNotFoundError):
                    # Ignore PermissionError and ModuleNotFoundError which indicates hub-sdk not installed
                    pass

        self.trainer.hub_session = self.session  # attach optional HUB session
        self.trainer.train()
        # Update model and cfg after training
        if RANK in {-1, 0}:
            ckpt = self.trainer.best if self.trainer.best.exists() else self.trainer.last
            self.model, _ = attempt_load_one_weight(ckpt)
            self.overrides = self.model.args
            self.metrics = getattr(self.trainer.validator, "metrics", None)  # TODO: no metrics returned by DDP
        return self.metrics

    def tune(
        self,
        use_ray=False,
        iterations=10,
        *args,
        **kwargs,
    ):
        """
        Conducts hyperparameter tuning for the model, with an option to use Ray Tune.

        This method supports two modes of hyperparameter tuning: using Ray Tune or a custom tuning method.
        When Ray Tune is enabled, it leverages the 'run_ray_tune' function from the ultralytics.utils.tuner module.
        Otherwise, it uses the internal 'Tuner' class for tuning. The method combines default, overridden, and
        custom arguments to configure the tuning process.

        Args:
            use_ray (bool): If True, uses Ray Tune for hyperparameter tuning. Defaults to False.
            iterations (int): The number of tuning iterations to perform. Defaults to 10.
            *args (list): Variable length argument list for additional arguments.
            **kwargs (any): Arbitrary keyword arguments. These are combined with the model's overrides and defaults.

        Returns:
            (dict): A dictionary containing the results of the hyperparameter search.

        Raises:
            AssertionError: If the model is not a PyTorch model.
        """
        self._check_is_pytorch_model()
        if use_ray:
            from ultralytics.utils.tuner import run_ray_tune

            return run_ray_tune(self, max_samples=iterations, *args, **kwargs)
        else:
            from .tuner import Tuner

            custom = {}  # method defaults
            args = {**self.overrides, **custom, **kwargs, "mode": "train"}  # highest priority args on the right
            return Tuner(args=args, _callbacks=self.callbacks)(model=self, iterations=iterations)

    def _apply(self, fn) -> "Model":
        """Apply to(), cpu(), cuda(), half(), float() to model tensors that are not parameters or registered buffers."""
        self._check_is_pytorch_model()
        self = super()._apply(fn)  # noqa
        self.predictor = None  # reset predictor as device may have changed
        self.overrides["device"] = self.device  # was str(self.device) i.e. device(type='cuda', index=0) -> 'cuda:0'
        return self

    @property
    def names(self) -> list:
        """
        Retrieves the class names associated with the loaded model.

        This property returns the class names if they are defined in the model. It checks the class names for validity
        using the 'check_class_names' function from the ultralytics.nn.autobackend module.

        Returns:
            (list | None): The class names of the model if available, otherwise None.
        """
        from ultralytics.nn.autobackend import check_class_names

        if hasattr(self.model, "names"):
            return check_class_names(self.model.names)
        if not self.predictor:  # export formats will not have predictor defined until predict() is called
            self.predictor = self._smart_load("predictor")(overrides=self.overrides, _callbacks=self.callbacks)
            self.predictor.setup_model(model=self.model, verbose=False)
        return self.predictor.model.names

    @property
    def device(self) -> torch.device:
        """
        Retrieves the device on which the model's parameters are allocated.

        This property is used to determine whether the model's parameters are on CPU or GPU. It only applies to models
        that are instances of nn.Module.

        Returns:
            (torch.device | None): The device (CPU/GPU) of the model if it is a PyTorch model, otherwise None.
        """
        return next(self.model.parameters()).device if isinstance(self.model, nn.Module) else None

    @property
    def transforms(self):
        """
        Retrieves the transformations applied to the input data of the loaded model.

        This property returns the transformations if they are defined in the model.

        Returns:
            (object | None): The transform object of the model if available, otherwise None.
        """
        return self.model.transforms if hasattr(self.model, "transforms") else None

    def add_callback(self, event: str, func) -> None:
        """
        Adds a callback function for a specified event.

        This method allows the user to register a custom callback function that is triggered on a specific event during
        model training or inference.

        Args:
            event (str): The name of the event to attach the callback to.
            func (callable): The callback function to be registered.

        Raises:
            ValueError: If the event name is not recognized.
        """
        self.callbacks[event].append(func)

    def clear_callback(self, event: str) -> None:
        """
        Clears all callback functions registered for a specified event.

        This method removes all custom and default callback functions associated with the given event.

        Args:
            event (str): The name of the event for which to clear the callbacks.

        Raises:
            ValueError: If the event name is not recognized.
        """
        self.callbacks[event] = []

    def reset_callbacks(self) -> None:
        """
        Resets all callbacks to their default functions.

        This method reinstates the default callback functions for all events, removing any custom callbacks that were
        added previously.
        """
        for event in callbacks.default_callbacks.keys():
            self.callbacks[event] = [callbacks.default_callbacks[event][0]]

    @staticmethod
    def _reset_ckpt_args(args: dict) -> dict:
        """Reset arguments when loading a PyTorch model."""
        include = {"imgsz", "data", "task", "single_cls"}  # only remember these arguments when loading a PyTorch model
        return {k: v for k, v in args.items() if k in include}

    # def __getattr__(self, attr):
    #    """Raises error if object has no requested attribute."""
    #    name = self.__class__.__name__
    #    raise AttributeError(f"'{name}' object has no attribute '{attr}'. See valid attributes below.\n{self.__doc__}")

    def _smart_load(self, key: str):
        """Load model/trainer/validator/predictor."""
        try:
            return self.task_map[self.task][key]
        except Exception as e:
            name = self.__class__.__name__
            mode = inspect.stack()[1][3]  # get the function name.
            raise NotImplementedError(
                emojis(f"WARNING ÔÜá´ŞĆ '{name}' model does not support '{mode}' mode for '{self.task}' task yet.")
            ) from e

    @property
    def task_map(self) -> dict:
        """
        Map head to model, trainer, validator, and predictor classes.

        Returns:
            task_map (dict): The map of model task to mode classes.
        """
        raise NotImplementedError("Please provide task map for your model!")

device: torch.device property

Modelin parametrelerinin tahsis edildi─či cihaz─▒ al─▒r.

Bu ├Âzellik, modelin parametrelerinin CPU'da m─▒ yoksa GPU'da m─▒ oldu─čunu belirlemek i├žin kullan─▒l─▒r. Yaln─▒zca modeller i├žin ge├žerlidir nn.Module'├╝n ├Ârnekleri olan.

─░ade:

Tip A├ž─▒klama
device | None

Bir PyTorch modeli ise modelin cihaz─▒ (CPU/GPU), aksi takdirde Yok.

names: list property

Y├╝klenen modelle ili┼čkili s─▒n─▒f adlar─▒n─▒ al─▒r.

Bu ├Âzellik, modelde tan─▒mlanm─▒┼člarsa s─▒n─▒f adlar─▒n─▒ d├Ând├╝r├╝r. S─▒n─▒f adlar─▒n─▒n ge├žerlili─čini kontrol eder ultralytics.nn.autobackend mod├╝l├╝ndeki 'check_class_names' i┼člevini kullanarak.

─░ade:

Tip A├ž─▒klama
list | None

Varsa modelin s─▒n─▒f adlar─▒, aksi takdirde Yok.

task_map: dict property

Ba┼čl─▒─č─▒ model, e─čitmen, do─črulay─▒c─▒ ve tahmin edici s─▒n─▒flar─▒yla e┼čleyin.

─░ade:

─░sim Tip A├ž─▒klama
task_map dict

Model g├Ârevinin mod s─▒n─▒flar─▒na haritas─▒.

transforms property

Y├╝klenen modelin giri┼č verilerine uygulanan d├Ân├╝┼č├╝mleri al─▒r.

Bu ├Âzellik, modelde tan─▒mlanm─▒┼člarsa d├Ân├╝┼č├╝mleri d├Ând├╝r├╝r.

─░ade:

Tip A├ž─▒klama
object | None

Varsa modelin d├Ân├╝┼č├╝m nesnesi, aksi takdirde Yok.

__call__(source=None, stream=False, **kwargs)

Model ├Ârne─činin ├ža─čr─▒labilir olmas─▒n─▒ sa─člayan tahmin y├Ântemi i├žin bir takma ad.

Bu y├Ântem, model ├Ârne─činin do─črudan ├ža─čr─▒lmas─▒na izin vererek tahmin yapma s├╝recini basitle┼čtirir tahmin i├žin gerekli arg├╝manlarla birlikte.

Parametreler:

─░sim Tip A├ž─▒klama Varsay─▒lan
source str | Path | int | Image | ndarray

Yap─▒lacak g├Âr├╝nt├╝n├╝n kayna─č─▒ Tahminler. Dosya yollar─▒, URL'ler, PIL g├Âr├╝nt├╝leri ve numpy dizileri dahil olmak ├╝zere ├že┼čitli t├╝rleri kabul eder. Varsay─▒lan de─čer Yok'tur.

None
stream bool

True ise, girdi kayna─č─▒n─▒ tahminler i├žin s├╝rekli bir ak─▒┼č olarak ele al─▒r. Varsay─▒lan de─čer False'dir.

False
**kwargs any

Tahmin s├╝recini yap─▒land─▒rmak i├žin ek anahtar s├Âzc├╝k ba─č─▒ms─▒z de─či┼čkenleri.

{}

─░ade:

Tip A├ž─▒klama
List[Results]

Results s─▒n─▒f─▒nda kaps├╝llenmi┼č bir tahmin sonu├žlar─▒ listesi.

Kaynak kodu ultralytics/engine/model.py
def __call__(
    self,
    source: Union[str, Path, int, list, tuple, np.ndarray, torch.Tensor] = None,
    stream: bool = False,
    **kwargs,
) -> list:
    """
    An alias for the predict method, enabling the model instance to be callable.

    This method simplifies the process of making predictions by allowing the model instance to be called directly
    with the required arguments for prediction.

    Args:
        source (str | Path | int | PIL.Image | np.ndarray, optional): The source of the image for making
            predictions. Accepts various types, including file paths, URLs, PIL images, and numpy arrays.
            Defaults to None.
        stream (bool, optional): If True, treats the input source as a continuous stream for predictions.
            Defaults to False.
        **kwargs (any): Additional keyword arguments for configuring the prediction process.

    Returns:
        (List[ultralytics.engine.results.Results]): A list of prediction results, encapsulated in the Results class.
    """
    return self.predict(source, stream, **kwargs)

__init__(model='yolov8n.pt', task=None, verbose=False)

YOLO model s─▒n─▒f─▒n─▒n yeni bir ├Ârne─čini ba┼člat─▒r.

Bu kurucu, modeli sa─članan model yoluna veya ad─▒na g├Âre kurar. ├çe┼čitli model t├╝rlerini i┼čler yerel dosyalar, Ultralytics HUB modelleri ve Triton Sunucu modelleri dahil olmak ├╝zere kaynaklar. Y├Ântem birka├ž kayna─č─▒ ba┼člat─▒r Modelin ├Ânemli nitelikleri ve e─čitim, tahmin veya d─▒┼ča aktarma gibi i┼člemler i├žin haz─▒rlar.

Parametreler:

─░sim Tip A├ž─▒klama Varsay─▒lan
model Union[str, Path]

Y├╝klenecek veya olu┼čturulacak yol veya model dosyas─▒. Bu yerel bir dosya olabilir dosya yolu, Ultralytics HUB'dan bir model ad─▒ veya bir Triton Sunucu modeli. Varsay─▒lan de─čer 'yolov8n.pt' ┼čeklindedir.

'yolov8n.pt'
task Any

Uygulama etki alan─▒n─▒ belirten YOLO modeliyle ili┼čkili g├Ârev t├╝r├╝. Varsay─▒lan de─čer Yok'tur.

None
verbose bool

True ise, modelin ba┼člat─▒lmas─▒ s─▒ras─▒nda ve daha sonra ayr─▒nt─▒l─▒ ├ž─▒kt─▒y─▒ etkinle┼čtirir i┼člemler. Varsay─▒lan de─čer False'dir.

False

Zamlar:

Tip A├ž─▒klama
FileNotFoundError

Belirtilen model dosyas─▒ mevcut de─čilse veya eri┼čilemiyorsa.

ValueError

Model dosyas─▒ veya yap─▒land─▒rma ge├žersizse veya desteklenmiyorsa.

ImportError

Belirli model t├╝rleri i├žin gerekli ba─č─▒ml─▒l─▒klar (HUB SDK gibi) y├╝klenmemi┼čse.

Kaynak kodu ultralytics/engine/model.py
def __init__(
    self,
    model: Union[str, Path] = "yolov8n.pt",
    task: str = None,
    verbose: bool = False,
) -> None:
    """
    Initializes a new instance of the YOLO model class.

    This constructor sets up the model based on the provided model path or name. It handles various types of model
    sources, including local files, Ultralytics HUB models, and Triton Server models. The method initializes several
    important attributes of the model and prepares it for operations like training, prediction, or export.

    Args:
        model (Union[str, Path], optional): The path or model file to load or create. This can be a local
            file path, a model name from Ultralytics HUB, or a Triton Server model. Defaults to 'yolov8n.pt'.
        task (Any, optional): The task type associated with the YOLO model, specifying its application domain.
            Defaults to None.
        verbose (bool, optional): If True, enables verbose output during the model's initialization and subsequent
            operations. Defaults to False.

    Raises:
        FileNotFoundError: If the specified model file does not exist or is inaccessible.
        ValueError: If the model file or configuration is invalid or unsupported.
        ImportError: If required dependencies for specific model types (like HUB SDK) are not installed.
    """
    super().__init__()
    self.callbacks = callbacks.get_default_callbacks()
    self.predictor = None  # reuse predictor
    self.model = None  # model object
    self.trainer = None  # trainer object
    self.ckpt = None  # if loaded from *.pt
    self.cfg = None  # if loaded from *.yaml
    self.ckpt_path = None
    self.overrides = {}  # overrides for trainer object
    self.metrics = None  # validation/training metrics
    self.session = None  # HUB session
    self.task = task  # task type
    model = str(model).strip()

    # Check if Ultralytics HUB model from https://hub.ultralytics.com
    if self.is_hub_model(model):
        # Fetch model from HUB
        checks.check_requirements("hub-sdk>=0.0.6")
        self.session = self._get_hub_session(model)
        model = self.session.model_file

    # Check if Triton Server model
    elif self.is_triton_model(model):
        self.model_name = self.model = model
        self.task = task
        return

    # Load or create new YOLO model
    if Path(model).suffix in {".yaml", ".yml"}:
        self._new(model, task=task, verbose=verbose)
    else:
        self._load(model, task=task)

add_callback(event, func)

Belirtilen olay i├žin bir geri arama i┼člevi ekler.

Bu y├Ântem, kullan─▒c─▒n─▒n belirli bir olay s─▒ras─▒nda tetiklenen ├Âzel bir geri arama i┼člevi kaydetmesine olanak tan─▒r model e─čitimi veya ├ž─▒kar─▒m─▒.

Parametreler:

─░sim Tip A├ž─▒klama Varsay─▒lan
event str

Geri araman─▒n eklenece─či olay─▒n ad─▒.

gerekli
func callable

Kaydedilecek geri arama i┼člevi.

gerekli

Zamlar:

Tip A├ž─▒klama
ValueError

Olay ad─▒ tan─▒nm─▒yorsa.

Kaynak kodu ultralytics/engine/model.py
def add_callback(self, event: str, func) -> None:
    """
    Adds a callback function for a specified event.

    This method allows the user to register a custom callback function that is triggered on a specific event during
    model training or inference.

    Args:
        event (str): The name of the event to attach the callback to.
        func (callable): The callback function to be registered.

    Raises:
        ValueError: If the event name is not recognized.
    """
    self.callbacks[event].append(func)

benchmark(**kwargs)

Performans─▒ de─čerlendirmek i├žin modeli ├že┼čitli d─▒┼ča aktarma bi├žimlerinde k─▒yaslar.

Bu y├Ântem, modelin performans─▒n─▒ ONNX, TorchScript, vb. gibi farkl─▒ d─▒┼ča aktarma formatlar─▒nda de─čerlendirir. ultralytics.utils.benchmarks mod├╝l├╝ndeki 'benchmark' fonksiyonunu kullan─▒r. K─▒yaslama yap─▒land─▒r─▒lm─▒┼čt─▒r varsay─▒lan yap─▒land─▒rma de─čerleri, modele ├Âzg├╝ arg├╝manlar, y├Ânteme ├Âzg├╝ varsay─▒lanlar ve kullan─▒c─▒ taraf─▒ndan sa─članan herhangi bir ek anahtar kelime arg├╝man─▒.

Y├Ântem, veri k├╝mesi gibi k─▒yaslama s├╝recinin ├Âzelle┼čtirilmesine olanak tan─▒yan ├že┼čitli arg├╝manlar─▒ destekler se├žimi, g├Âr├╝nt├╝ boyutu, hassasiyet modlar─▒, cihaz se├žimi ve ayr─▒nt─▒ d├╝zeyi. Kapsaml─▒ bir liste i├žin yap─▒land─▒r─▒labilir se├ženekler i├žin, kullan─▒c─▒lar belgelerdeki 'yap─▒land─▒rma' b├Âl├╝m├╝ne ba┼čvurmal─▒d─▒r.

Parametreler:

─░sim Tip A├ž─▒klama Varsay─▒lan
**kwargs any

K─▒yaslama s├╝recini ├Âzelle┼čtirmek i├žin keyfi anahtar kelime arg├╝manlar─▒. Bunlar ile birle┼čtirilir varsay─▒lan yap─▒land─▒rmalar, modele ├Âzg├╝ arg├╝manlar ve y├Ântem varsay─▒lanlar─▒.

{}

─░ade:

Tip A├ž─▒klama
dict

K─▒yaslama s├╝recinin sonu├žlar─▒n─▒ i├žeren bir s├Âzl├╝k.

Zamlar:

Tip A├ž─▒klama
AssertionError

E─čer model bir PyTorch modeli de─čilse.

Kaynak kodu ultralytics/engine/model.py
def benchmark(
    self,
    **kwargs,
):
    """
    Benchmarks the model across various export formats to evaluate performance.

    This method assesses the model's performance in different export formats, such as ONNX, TorchScript, etc.
    It uses the 'benchmark' function from the ultralytics.utils.benchmarks module. The benchmarking is configured
    using a combination of default configuration values, model-specific arguments, method-specific defaults, and
    any additional user-provided keyword arguments.

    The method supports various arguments that allow customization of the benchmarking process, such as dataset
    choice, image size, precision modes, device selection, and verbosity. For a comprehensive list of all
    configurable options, users should refer to the 'configuration' section in the documentation.

    Args:
        **kwargs (any): Arbitrary keyword arguments to customize the benchmarking process. These are combined with
            default configurations, model-specific arguments, and method defaults.

    Returns:
        (dict): A dictionary containing the results of the benchmarking process.

    Raises:
        AssertionError: If the model is not a PyTorch model.
    """
    self._check_is_pytorch_model()
    from ultralytics.utils.benchmarks import benchmark

    custom = {"verbose": False}  # method defaults
    args = {**DEFAULT_CFG_DICT, **self.model.args, **custom, **kwargs, "mode": "benchmark"}
    return benchmark(
        model=self,
        data=kwargs.get("data"),  # if no 'data' argument passed set data=None for default datasets
        imgsz=args["imgsz"],
        half=args["half"],
        int8=args["int8"],
        device=args["device"],
        verbose=kwargs.get("verbose"),
    )

clear_callback(event)

Belirtilen bir olay i├žin kay─▒tl─▒ t├╝m geri ├ža─č─▒rma i┼člevlerini temizler.

Bu y├Ântem, verilen olayla ili┼čkili t├╝m ├Âzel ve varsay─▒lan geri arama i┼člevlerini kald─▒r─▒r.

Parametreler:

─░sim Tip A├ž─▒klama Varsay─▒lan
event str

Geri aramalar─▒n temizlenece─či olay─▒n ad─▒.

gerekli

Zamlar:

Tip A├ž─▒klama
ValueError

Olay ad─▒ tan─▒nm─▒yorsa.

Kaynak kodu ultralytics/engine/model.py
def clear_callback(self, event: str) -> None:
    """
    Clears all callback functions registered for a specified event.

    This method removes all custom and default callback functions associated with the given event.

    Args:
        event (str): The name of the event for which to clear the callbacks.

    Raises:
        ValueError: If the event name is not recognized.
    """
    self.callbacks[event] = []

embed(source=None, stream=False, **kwargs)

Sa─članan kayna─ča dayal─▒ olarak g├Âr├╝nt├╝ kat─▒┼čt─▒rmalar─▒ olu┼čturur.

Bu y├Ântem 'predict()' y├Ântemi etraf─▒nda bir sarmalay─▒c─▒d─▒r ve bir g├Âr├╝nt├╝ kayna─č─▒ndan g├Âmme olu┼čturmaya odaklan─▒r. ├çe┼čitli anahtar kelime arg├╝manlar─▒ arac─▒l─▒─č─▒yla g├Âmme i┼čleminin ├Âzelle┼čtirilmesine olanak tan─▒r.

Parametreler:

─░sim Tip A├ž─▒klama Varsay─▒lan
source str | int | Image | ndarray

G├Âmme olu┼čturmak i├žin g├Âr├╝nt├╝n├╝n kayna─č─▒. Kaynak bir dosya yolu, URL, PIL g├Âr├╝nt├╝s├╝, numpy dizisi vb. olabilir. Varsay─▒lan de─čer Yok'tur.

None
stream bool

True ise, tahminler yay─▒nlan─▒r. Varsay─▒lan de─čer False'dir.

False
**kwargs any

Yerle┼čtirme i┼člemini yap─▒land─▒rmak i├žin ek anahtar s├Âzc├╝k arg├╝manlar─▒.

{}

─░ade:

Tip A├ž─▒klama
List[Tensor]

G├Âr├╝nt├╝ kat─▒┼čt─▒rmalar─▒n─▒ i├žeren bir liste.

Zamlar:

Tip A├ž─▒klama
AssertionError

E─čer model bir PyTorch modeli de─čilse.

Kaynak kodu ultralytics/engine/model.py
def embed(
    self,
    source: Union[str, Path, int, list, tuple, np.ndarray, torch.Tensor] = None,
    stream: bool = False,
    **kwargs,
) -> list:
    """
    Generates image embeddings based on the provided source.

    This method is a wrapper around the 'predict()' method, focusing on generating embeddings from an image source.
    It allows customization of the embedding process through various keyword arguments.

    Args:
        source (str | int | PIL.Image | np.ndarray): The source of the image for generating embeddings.
            The source can be a file path, URL, PIL image, numpy array, etc. Defaults to None.
        stream (bool): If True, predictions are streamed. Defaults to False.
        **kwargs (any): Additional keyword arguments for configuring the embedding process.

    Returns:
        (List[torch.Tensor]): A list containing the image embeddings.

    Raises:
        AssertionError: If the model is not a PyTorch model.
    """
    if not kwargs.get("embed"):
        kwargs["embed"] = [len(self.model.model) - 2]  # embed second-to-last layer if no indices passed
    return self.predict(source, stream, **kwargs)

export(**kwargs)

Modeli da─č─▒t─▒m i├žin uygun farkl─▒ bir formata aktar─▒r.

Bu y├Ântem, modelin da─č─▒t─▒m i├žin ├že┼čitli formatlara (├Ârn. ONNX, TorchScript) aktar─▒lmas─▒n─▒ kolayla┼čt─▒r─▒r ama├žlar. D─▒┼ča aktarma i┼člemi i├žin 'Exporter' s─▒n─▒f─▒n─▒ kullan─▒r, modele ├Âzg├╝ ge├žersiz k─▒lmalar─▒, y├Ântem varsay─▒lanlar ve sa─članan ek ba─č─▒ms─▒z de─či┼čkenler. Birle┼čik ba─č─▒ms─▒z de─či┼čkenler d─▒┼ča aktarma ayarlar─▒n─▒ yap─▒land─▒rmak i├žin kullan─▒l─▒r.

Y├Ântem, d─▒┼ča aktarma i┼člemini ├Âzelle┼čtirmek i├žin ├žok ├že┼čitli arg├╝manlar─▒ destekler. T├╝m arg├╝manlar─▒n kapsaml─▒ bir listesi i├žin olas─▒ arg├╝manlar i├žin belgelerdeki 'yap─▒land─▒rma' b├Âl├╝m├╝ne bak─▒n.

Parametreler:

─░sim Tip A├ž─▒klama Varsay─▒lan
**kwargs any

D─▒┼ča aktarma i┼člemini ├Âzelle┼čtirmek i├žin keyfi anahtar kelime arg├╝manlar─▒. Bunlar ile birle┼čtirilir modelin ge├žersiz k─▒lmalar─▒ ve y├Ântem varsay─▒lanlar─▒.

{}

─░ade:

Tip A├ž─▒klama
str

Belirtilen formatta d─▒┼ča aktar─▒lan model dosya ad─▒ veya d─▒┼ča aktarma i┼člemiyle ilgili bir nesne.

Zamlar:

Tip A├ž─▒klama
AssertionError

E─čer model bir PyTorch modeli de─čilse.

Kaynak kodu ultralytics/engine/model.py
def export(
    self,
    **kwargs,
) -> str:
    """
    Exports the model to a different format suitable for deployment.

    This method facilitates the export of the model to various formats (e.g., ONNX, TorchScript) for deployment
    purposes. It uses the 'Exporter' class for the export process, combining model-specific overrides, method
    defaults, and any additional arguments provided. The combined arguments are used to configure export settings.

    The method supports a wide range of arguments to customize the export process. For a comprehensive list of all
    possible arguments, refer to the 'configuration' section in the documentation.

    Args:
        **kwargs (any): Arbitrary keyword arguments to customize the export process. These are combined with the
            model's overrides and method defaults.

    Returns:
        (str): The exported model filename in the specified format, or an object related to the export process.

    Raises:
        AssertionError: If the model is not a PyTorch model.
    """
    self._check_is_pytorch_model()
    from .exporter import Exporter

    custom = {"imgsz": self.model.args["imgsz"], "batch": 1, "data": None, "verbose": False}  # method defaults
    args = {**self.overrides, **custom, **kwargs, "mode": "export"}  # highest priority args on the right
    return Exporter(overrides=args, _callbacks=self.callbacks)(model=self.model)

fuse()

Conv2d ve BatchNorm2d katmanlar─▒n─▒ modelde birle┼čtirir.

Bu y├Ântem, Conv2d ve BatchNorm2d katmanlar─▒n─▒ birle┼čtirerek modeli optimize eder ve bu da ├ž─▒kar─▒m h─▒z─▒n─▒ art─▒rabilir.

Zamlar:

Tip A├ž─▒klama
AssertionError

E─čer model bir PyTorch modeli de─čilse.

Kaynak kodu ultralytics/engine/model.py
def fuse(self):
    """
    Fuses Conv2d and BatchNorm2d layers in the model.

    This method optimizes the model by fusing Conv2d and BatchNorm2d layers, which can improve inference speed.

    Raises:
        AssertionError: If the model is not a PyTorch model.
    """
    self._check_is_pytorch_model()
    self.model.fuse()

info(detailed=False, verbose=True)

Model bilgilerini g├╝nl├╝─če kaydeder veya d├Ând├╝r├╝r.

Bu y├Ântem, aktar─▒lan arg├╝manlara ba─čl─▒ olarak model hakk─▒nda genel bir bak─▒┼č veya ayr─▒nt─▒l─▒ bilgi sa─člar. ├ç─▒kt─▒n─▒n ayr─▒nt─▒ d├╝zeyini kontrol edebilir.

Parametreler:

─░sim Tip A├ž─▒klama Varsay─▒lan
detailed bool

True ise, model hakk─▒nda ayr─▒nt─▒l─▒ bilgi g├Âsterir. Varsay─▒lan de─čer False'dir.

False
verbose bool

True ise, bilgileri yazd─▒r─▒r. False ise bilgileri d├Ând├╝r├╝r. Varsay─▒lan de─čer True'dur.

True

─░ade:

Tip A├ž─▒klama
list

'Ayr─▒nt─▒l─▒' ve 'ayr─▒nt─▒l─▒' parametrelerine ba─čl─▒ olarak model hakk─▒nda ├že┼čitli bilgi t├╝rleri.

Zamlar:

Tip A├ž─▒klama
AssertionError

E─čer model bir PyTorch modeli de─čilse.

Kaynak kodu ultralytics/engine/model.py
def info(self, detailed: bool = False, verbose: bool = True):
    """
    Logs or returns model information.

    This method provides an overview or detailed information about the model, depending on the arguments passed.
    It can control the verbosity of the output.

    Args:
        detailed (bool): If True, shows detailed information about the model. Defaults to False.
        verbose (bool): If True, prints the information. If False, returns the information. Defaults to True.

    Returns:
        (list): Various types of information about the model, depending on the 'detailed' and 'verbose' parameters.

    Raises:
        AssertionError: If the model is not a PyTorch model.
    """
    self._check_is_pytorch_model()
    return self.model.info(detailed=detailed, verbose=verbose)

is_hub_model(model) staticmethod

Sa─članan modelin bir HUB modeli olup olmad─▒─č─▒n─▒ kontrol edin.

Kaynak kodu ultralytics/engine/model.py
@staticmethod
def is_hub_model(model: str) -> bool:
    """Check if the provided model is a HUB model."""
    return any(
        (
            model.startswith(f"{HUB_WEB_ROOT}/models/"),  # i.e. https://hub.ultralytics.com/models/MODEL_ID
            [len(x) for x in model.split("_")] == [42, 20],  # APIKEY_MODEL
            len(model) == 20 and not Path(model).exists() and all(x not in model for x in "./\\"),  # MODEL
        )
    )

is_triton_model(model) staticmethod

Model bir Triton Sunucu URL dizesidir, yani :////

Kaynak kodu ultralytics/engine/model.py
@staticmethod
def is_triton_model(model: str) -> bool:
    """Is model a Triton Server URL string, i.e. <scheme>://<netloc>/<endpoint>/<task_name>"""
    from urllib.parse import urlsplit

    url = urlsplit(model)
    return url.netloc and url.path and url.scheme in {"http", "grpc"}

load(weights='yolov8n.pt')

Belirtilen a─č─▒rl─▒klar dosyas─▒ndaki parametreleri modele y├╝kler.

Bu y├Ântem, a─č─▒rl─▒klar─▒n bir dosyadan veya do─črudan bir weights nesnesinden y├╝klenmesini destekler. Parametreleri ┼ču ┼čekilde e┼čle┼čtirir isim ve ┼čekil verir ve bunlar─▒ modele aktar─▒r.

Parametreler:

─░sim Tip A├ž─▒klama Varsay─▒lan
weights str | Path

A─č─▒rl─▒k dosyas─▒n─▒n veya bir a─č─▒rl─▒k nesnesinin yolu. Varsay─▒lan de─čer 'yolov8n.pt' ┼čeklindedir.

'yolov8n.pt'

─░ade:

─░sim Tip A├ž─▒klama
self Model

Y├╝kl├╝ a─č─▒rl─▒klara sahip s─▒n─▒f─▒n ├Ârne─či.

Zamlar:

Tip A├ž─▒klama
AssertionError

E─čer model bir PyTorch modeli de─čilse.

Kaynak kodu ultralytics/engine/model.py
def load(self, weights: Union[str, Path] = "yolov8n.pt") -> "Model":
    """
    Loads parameters from the specified weights file into the model.

    This method supports loading weights from a file or directly from a weights object. It matches parameters by
    name and shape and transfers them to the model.

    Args:
        weights (str | Path): Path to the weights file or a weights object. Defaults to 'yolov8n.pt'.

    Returns:
        self (ultralytics.engine.model.Model): The instance of the class with loaded weights.

    Raises:
        AssertionError: If the model is not a PyTorch model.
    """
    self._check_is_pytorch_model()
    if isinstance(weights, (str, Path)):
        weights, self.ckpt = attempt_load_one_weight(weights)
    self.model.load(weights)
    return self

predict(source=None, stream=False, predictor=None, **kwargs)

YOLO modelini kullanarak verilen g├Âr├╝nt├╝ kayna─č─▒ ├╝zerinde tahminler ger├žekle┼čtirir.

Bu y├Ântem, anahtar kelime arg├╝manlar─▒ arac─▒l─▒─č─▒yla ├že┼čitli yap─▒land─▒rmalara izin vererek tahmin s├╝recini kolayla┼čt─▒r─▒r. ├ľzel tahmin edicilerle veya varsay─▒lan tahmin edici y├Ântemiyle tahminleri destekler. Y├Ântem farkl─▒ tahmin y├Ântemlerini g├Âr├╝nt├╝ kayna─č─▒ t├╝rleri ve ak─▒┼č modunda ├žal─▒┼čabilir. Ayr─▒ca SAM tipi modeller i├žin de destek sa─člar 'y├Ânlendirmeler' arac─▒l─▒─č─▒yla.

Y├Ântem, halihaz─▒rda mevcut de─čilse yeni bir tahminci kurar ve her ├ža─čr─▒da arg├╝manlar─▒n─▒ g├╝nceller. Ayr─▒ca bir uyar─▒ verir ve 'kaynak' sa─članmam─▒┼čsa varsay─▒lan varl─▒klar─▒ kullan─▒r. Y├Ântem a┼ča─č─▒dakilerin olup olmad─▒─č─▒n─▒ belirler komut sat─▒r─▒ aray├╝z├╝nden ├ža─čr─▒l─▒yor ve varsay─▒lanlar─▒ ayarlamak da dahil olmak ├╝zere davran─▒┼č─▒n─▒ buna g├Âre ayarl─▒yor g├╝ven e┼či─či ve tasarruf davran─▒┼č─▒ i├žin.

Parametreler:

─░sim Tip A├ž─▒klama Varsay─▒lan
source str | int | Image | ndarray

Tahmin yapmak i├žin g├Âr├╝nt├╝n├╝n kayna─č─▒. Dosya yollar─▒, URL'ler, PIL g├Âr├╝nt├╝leri ve numpy dizileri dahil olmak ├╝zere ├že┼čitli t├╝rleri kabul eder. Varsay─▒lan de─čer ASSETS'tir.

None
stream bool

Tahminler i├žin girdi kayna─č─▒n─▒ s├╝rekli bir ak─▒┼č olarak ele al─▒r. Varsay─▒lan de─čer False'dir.

False
predictor BasePredictor

Tahmin yapmak i├žin ├Âzel bir tahminci s─▒n─▒f─▒n─▒n bir ├Ârne─či. Yok ise, y├Ântem varsay─▒lan bir tahmin ediciyi kullan─▒r. Varsay─▒lan de─čer Yok'tur.

None
**kwargs any

Tahmin s├╝recini yap─▒land─▒rmak i├žin ek anahtar s├Âzc├╝k ba─č─▒ms─▒z de─či┼čkenleri. Bu arg├╝manlar ┼čunlara izin verir Tahmin davran─▒┼č─▒n─▒n daha fazla ├Âzelle┼čtirilmesi i├žin.

{}

─░ade:

Tip A├ž─▒klama
List[Results]

Results s─▒n─▒f─▒nda kaps├╝llenmi┼č bir tahmin sonu├žlar─▒ listesi.

Zamlar:

Tip A├ž─▒klama
AttributeError

Tahmin edici d├╝zg├╝n ┼čekilde ayarlanmam─▒┼čsa.

Kaynak kodu ultralytics/engine/model.py
def predict(
    self,
    source: Union[str, Path, int, list, tuple, np.ndarray, torch.Tensor] = None,
    stream: bool = False,
    predictor=None,
    **kwargs,
) -> List[Results]:
    """
    Performs predictions on the given image source using the YOLO model.

    This method facilitates the prediction process, allowing various configurations through keyword arguments.
    It supports predictions with custom predictors or the default predictor method. The method handles different
    types of image sources and can operate in a streaming mode. It also provides support for SAM-type models
    through 'prompts'.

    The method sets up a new predictor if not already present and updates its arguments with each call.
    It also issues a warning and uses default assets if the 'source' is not provided. The method determines if it
    is being called from the command line interface and adjusts its behavior accordingly, including setting defaults
    for confidence threshold and saving behavior.

    Args:
        source (str | int | PIL.Image | np.ndarray, optional): The source of the image for making predictions.
            Accepts various types, including file paths, URLs, PIL images, and numpy arrays. Defaults to ASSETS.
        stream (bool, optional): Treats the input source as a continuous stream for predictions. Defaults to False.
        predictor (BasePredictor, optional): An instance of a custom predictor class for making predictions.
            If None, the method uses a default predictor. Defaults to None.
        **kwargs (any): Additional keyword arguments for configuring the prediction process. These arguments allow
            for further customization of the prediction behavior.

    Returns:
        (List[ultralytics.engine.results.Results]): A list of prediction results, encapsulated in the Results class.

    Raises:
        AttributeError: If the predictor is not properly set up.
    """
    if source is None:
        source = ASSETS
        LOGGER.warning(f"WARNING ÔÜá´ŞĆ 'source' is missing. Using 'source={source}'.")

    is_cli = (ARGV[0].endswith("yolo") or ARGV[0].endswith("ultralytics")) and any(
        x in ARGV for x in ("predict", "track", "mode=predict", "mode=track")
    )

    custom = {"conf": 0.25, "batch": 1, "save": is_cli, "mode": "predict"}  # method defaults
    args = {**self.overrides, **custom, **kwargs}  # highest priority args on the right
    prompts = args.pop("prompts", None)  # for SAM-type models

    if not self.predictor:
        self.predictor = predictor or self._smart_load("predictor")(overrides=args, _callbacks=self.callbacks)
        self.predictor.setup_model(model=self.model, verbose=is_cli)
    else:  # only update args if predictor is already setup
        self.predictor.args = get_cfg(self.predictor.args, args)
        if "project" in args or "name" in args:
            self.predictor.save_dir = get_save_dir(self.predictor.args)
    if prompts and hasattr(self.predictor, "set_prompts"):  # for SAM-type models
        self.predictor.set_prompts(prompts)
    return self.predictor.predict_cli(source=source) if is_cli else self.predictor(source=source, stream=stream)

reset_callbacks()

T├╝m geri ├ža─č─▒rmalar─▒ varsay─▒lan i┼člevlerine s─▒f─▒rlar.

Bu y├Ântem, t├╝m olaylar i├žin varsay─▒lan geri arama i┼člevlerini eski haline getirir ve daha ├Ânce kullan─▒lan ├Âzel geri aramalar─▒ kald─▒r─▒r. daha ├Ânce eklendi.

Kaynak kodu ultralytics/engine/model.py
def reset_callbacks(self) -> None:
    """
    Resets all callbacks to their default functions.

    This method reinstates the default callback functions for all events, removing any custom callbacks that were
    added previously.
    """
    for event in callbacks.default_callbacks.keys():
        self.callbacks[event] = [callbacks.default_callbacks[event][0]]

reset_weights()

Model parametrelerini rastgele ba┼člat─▒lan de─čerlere s─▒f─▒rlar ve t├╝m e─čitim bilgilerini etkili bir ┼čekilde atar.

Bu y├Ântem modeldeki t├╝m mod├╝lleri yineler ve parametrelerini s─▒f─▒rlar, e─čer bir 'reset_parameters' y├Ântemi. Ayr─▒ca t├╝m parametrelerin 'requires_grad' de─čerinin True olarak ayarlanmas─▒n─▒ sa─člayarak e─čitim s─▒ras─▒nda g├╝ncellenecektir.

─░ade:

─░sim Tip A├ž─▒klama
self Model

A─č─▒rl─▒klar─▒ s─▒f─▒rlanm─▒┼č s─▒n─▒f ├Ârne─či.

Zamlar:

Tip A├ž─▒klama
AssertionError

E─čer model bir PyTorch modeli de─čilse.

Kaynak kodu ultralytics/engine/model.py
def reset_weights(self) -> "Model":
    """
    Resets the model parameters to randomly initialized values, effectively discarding all training information.

    This method iterates through all modules in the model and resets their parameters if they have a
    'reset_parameters' method. It also ensures that all parameters have 'requires_grad' set to True, enabling them
    to be updated during training.

    Returns:
        self (ultralytics.engine.model.Model): The instance of the class with reset weights.

    Raises:
        AssertionError: If the model is not a PyTorch model.
    """
    self._check_is_pytorch_model()
    for m in self.model.modules():
        if hasattr(m, "reset_parameters"):
            m.reset_parameters()
    for p in self.model.parameters():
        p.requires_grad = True
    return self

save(filename='saved_model.pt', use_dill=True)

Ge├žerli model durumunu bir dosyaya kaydeder.

Bu y├Ântem, modelin kontrol noktas─▒n─▒ (ckpt) belirtilen dosya ad─▒na aktar─▒r.

Parametreler:

─░sim Tip A├ž─▒klama Varsay─▒lan
filename str | Path

Modelin kaydedilece─či dosyan─▒n ad─▒. Varsay─▒lan olarak 'saved_model.pt'.

'saved_model.pt'
use_dill bool

Varsa serile┼čtirme i├žin dill kullanmay─▒ deneyip denemeyece─činiz. Varsay─▒lan de─čer True'dur.

True

Zamlar:

Tip A├ž─▒klama
AssertionError

E─čer model bir PyTorch modeli de─čilse.

Kaynak kodu ultralytics/engine/model.py
def save(self, filename: Union[str, Path] = "saved_model.pt", use_dill=True) -> None:
    """
    Saves the current model state to a file.

    This method exports the model's checkpoint (ckpt) to the specified filename.

    Args:
        filename (str | Path): The name of the file to save the model to. Defaults to 'saved_model.pt'.
        use_dill (bool): Whether to try using dill for serialization if available. Defaults to True.

    Raises:
        AssertionError: If the model is not a PyTorch model.
    """
    self._check_is_pytorch_model()
    from datetime import datetime

    from ultralytics import __version__

    updates = {
        "date": datetime.now().isoformat(),
        "version": __version__,
        "license": "AGPL-3.0 License (https://ultralytics.com/license)",
        "docs": "https://docs.ultralytics.com",
    }
    torch.save({**self.ckpt, **updates}, filename, use_dill=use_dill)

track(source=None, stream=False, persist=False, **kwargs)

Kay─▒tl─▒ izleyicileri kullanarak belirtilen giri┼č kayna─č─▒ ├╝zerinde nesne izleme ger├žekle┼čtirir.

Bu y├Ântem, modelin tahmin edicilerini ve iste─če ba─čl─▒ olarak kay─▒tl─▒ izleyicileri kullanarak nesne izleme ger├žekle┼čtirir. Bu dosya yollar─▒ veya video ak─▒┼člar─▒ gibi farkl─▒ t├╝rdeki giri┼č kaynaklar─▒n─▒ i┼čleyebilmektedir. Y├Ântem ┼čunlar─▒ destekler ├že┼čitli anahtar kelime arg├╝manlar─▒ arac─▒l─▒─č─▒yla izleme s├╝recinin ├Âzelle┼čtirilmesi. ─░zleyicileri e─čer de─čillerse kaydeder zaten mevcut ve iste─če ba─čl─▒ olarak 'persist' bayra─č─▒na g├Âre bunlar─▒ kal─▒c─▒ hale getirir.

Y├Ântem, ├Âzellikle d├╝┼č├╝k g├╝ven gerektiren ByteTrack tabanl─▒ izleme i├žin varsay─▒lan bir g├╝ven e┼či─či belirler girdi olarak g├╝ven tahminleri. ─░zleme modu, anahtar kelime arg├╝manlar─▒nda a├ž─▒k├ža ayarlan─▒r.

Parametreler:

─░sim Tip A├ž─▒klama Varsay─▒lan
source str

Nesne izleme i├žin giri┼č kayna─č─▒. Bir dosya yolu, URL veya video ak─▒┼č─▒ olabilir.

None
stream bool

Giri┼č kayna─č─▒n─▒ s├╝rekli bir video ak─▒┼č─▒ olarak ele al─▒r. Varsay─▒lan de─čer False'dir.

False
persist bool

Bu y├Ânteme yap─▒lan farkl─▒ ├ža─čr─▒lar aras─▒nda izleyicileri kal─▒c─▒ k─▒lar. Varsay─▒lan de─čer False'dir.

False
**kwargs any

─░zleme s├╝recini yap─▒land─▒rmak i├žin ek anahtar s├Âzc├╝k ba─č─▒ms─▒z de─či┼čkenleri. Bu arg├╝manlar ┼čunlara izin verir izleme davran─▒┼č─▒n─▒n daha fazla ├Âzelle┼čtirilmesi i├žin.

{}

─░ade:

Tip A├ž─▒klama
List[Results]

Results s─▒n─▒f─▒nda kaps├╝llenmi┼č bir izleme sonu├žlar─▒ listesi.

Zamlar:

Tip A├ž─▒klama
AttributeError

Tahmin edicinin kay─▒tl─▒ izleyicileri yoksa.

Kaynak kodu ultralytics/engine/model.py
def track(
    self,
    source: Union[str, Path, int, list, tuple, np.ndarray, torch.Tensor] = None,
    stream: bool = False,
    persist: bool = False,
    **kwargs,
) -> List[Results]:
    """
    Conducts object tracking on the specified input source using the registered trackers.

    This method performs object tracking using the model's predictors and optionally registered trackers. It is
    capable of handling different types of input sources such as file paths or video streams. The method supports
    customization of the tracking process through various keyword arguments. It registers trackers if they are not
    already present and optionally persists them based on the 'persist' flag.

    The method sets a default confidence threshold specifically for ByteTrack-based tracking, which requires low
    confidence predictions as input. The tracking mode is explicitly set in the keyword arguments.

    Args:
        source (str, optional): The input source for object tracking. It can be a file path, URL, or video stream.
        stream (bool, optional): Treats the input source as a continuous video stream. Defaults to False.
        persist (bool, optional): Persists the trackers between different calls to this method. Defaults to False.
        **kwargs (any): Additional keyword arguments for configuring the tracking process. These arguments allow
            for further customization of the tracking behavior.

    Returns:
        (List[ultralytics.engine.results.Results]): A list of tracking results, encapsulated in the Results class.

    Raises:
        AttributeError: If the predictor does not have registered trackers.
    """
    if not hasattr(self.predictor, "trackers"):
        from ultralytics.trackers import register_tracker

        register_tracker(self, persist)
    kwargs["conf"] = kwargs.get("conf") or 0.1  # ByteTrack-based method needs low confidence predictions as input
    kwargs["batch"] = kwargs.get("batch") or 1  # batch-size 1 for tracking in videos
    kwargs["mode"] = "track"
    return self.predict(source=source, stream=stream, **kwargs)

train(trainer=None, **kwargs)

Belirtilen veri k├╝mesini ve e─čitim yap─▒land─▒rmas─▒n─▒ kullanarak modeli e─čitir.

Bu y├Ântem, bir dizi ├Âzelle┼čtirilebilir ayar ve konfig├╝rasyonla model e─čitimini kolayla┼čt─▒r─▒r. Destekler ├Âzel bir e─čitmenle veya y├Ântemde tan─▒mlanan varsay─▒lan e─čitim yakla┼č─▒m─▒yla e─čitim. Y├Ântem ┼čunlar─▒ i┼čler Bir kontrol noktas─▒ndan e─čitime devam etme, Ultralytics HUB ile entegrasyon gibi farkl─▒ senaryolar ve E─čitimden sonra model ve konfig├╝rasyonun g├╝ncellenmesi.

Ultralytics HUB kullan─▒l─▒rken, oturumun zaten y├╝kl├╝ bir modeli varsa, y├Ântem HUB e─čitimine ├Âncelik verir arg├╝manlar─▒n─▒ kontrol eder ve yerel arg├╝manlar sa─članm─▒┼čsa bir uyar─▒ verir. Pip g├╝ncellemelerini kontrol eder ve varsay─▒lan konfig├╝rasyonlar─▒, y├Ânteme ├Âzg├╝ varsay─▒lanlar ve e─čitim s├╝recini yap─▒land─▒rmak i├žin kullan─▒c─▒ taraf─▒ndan sa─članan arg├╝manlar. Sonra E─čitim, modeli ve konfig├╝rasyonlar─▒n─▒ g├╝nceller ve iste─če ba─čl─▒ olarak metrikleri ekler.

Parametreler:

─░sim Tip A├ž─▒klama Varsay─▒lan
trainer BaseTrainer

Modeli e─čitmek i├žin ├Âzel bir e─čitmen s─▒n─▒f─▒n─▒n bir ├Ârne─či. Yok ise y├Ântemi varsay─▒lan bir e─čitmen kullan─▒r. Varsay─▒lan de─čer Yok'tur.

None
**kwargs any

E─čitim yap─▒land─▒rmas─▒n─▒ temsil eden keyfi anahtar kelime arg├╝manlar─▒. Bu arg├╝manlar ┼čunlard─▒r e─čitim s├╝recinin ├že┼čitli y├Ânlerini ├Âzelle┼čtirmek i├žin kullan─▒l─▒r.

{}

─░ade:

Tip A├ž─▒klama
dict | None

Mevcutsa ve e─čitim ba┼čar─▒l─▒ysa e─čitim metrikleri; aksi takdirde, Yok.

Zamlar:

Tip A├ž─▒klama
AssertionError

E─čer model bir PyTorch modeli de─čilse.

PermissionError

HUB oturumuyla ilgili bir izin sorunu varsa.

ModuleNotFoundError

HUB SDK y├╝kl├╝ de─čilse.

Kaynak kodu ultralytics/engine/model.py
def train(
    self,
    trainer=None,
    **kwargs,
):
    """
    Trains the model using the specified dataset and training configuration.

    This method facilitates model training with a range of customizable settings and configurations. It supports
    training with a custom trainer or the default training approach defined in the method. The method handles
    different scenarios, such as resuming training from a checkpoint, integrating with Ultralytics HUB, and
    updating model and configuration after training.

    When using Ultralytics HUB, if the session already has a loaded model, the method prioritizes HUB training
    arguments and issues a warning if local arguments are provided. It checks for pip updates and combines default
    configurations, method-specific defaults, and user-provided arguments to configure the training process. After
    training, it updates the model and its configurations, and optionally attaches metrics.

    Args:
        trainer (BaseTrainer, optional): An instance of a custom trainer class for training the model. If None, the
            method uses a default trainer. Defaults to None.
        **kwargs (any): Arbitrary keyword arguments representing the training configuration. These arguments are
            used to customize various aspects of the training process.

    Returns:
        (dict | None): Training metrics if available and training is successful; otherwise, None.

    Raises:
        AssertionError: If the model is not a PyTorch model.
        PermissionError: If there is a permission issue with the HUB session.
        ModuleNotFoundError: If the HUB SDK is not installed.
    """
    self._check_is_pytorch_model()
    if hasattr(self.session, "model") and self.session.model.id:  # Ultralytics HUB session with loaded model
        if any(kwargs):
            LOGGER.warning("WARNING ÔÜá´ŞĆ using HUB training arguments, ignoring local training arguments.")
        kwargs = self.session.train_args  # overwrite kwargs

    checks.check_pip_update_available()

    overrides = yaml_load(checks.check_yaml(kwargs["cfg"])) if kwargs.get("cfg") else self.overrides
    custom = {
        # NOTE: handle the case when 'cfg' includes 'data'.
        "data": overrides.get("data") or DEFAULT_CFG_DICT["data"] or TASK2DATA[self.task],
        "model": self.overrides["model"],
        "task": self.task,
    }  # method defaults
    args = {**overrides, **custom, **kwargs, "mode": "train"}  # highest priority args on the right
    if args.get("resume"):
        args["resume"] = self.ckpt_path

    self.trainer = (trainer or self._smart_load("trainer"))(overrides=args, _callbacks=self.callbacks)
    if not args.get("resume"):  # manually set model only if not resuming
        self.trainer.model = self.trainer.get_model(weights=self.model if self.ckpt else None, cfg=self.model.yaml)
        self.model = self.trainer.model

        if SETTINGS["hub"] is True and not self.session:
            # Create a model in HUB
            try:
                self.session = self._get_hub_session(self.model_name)
                if self.session:
                    self.session.create_model(args)
                    # Check model was created
                    if not getattr(self.session.model, "id", None):
                        self.session = None
            except (PermissionError, ModuleNotFoundError):
                # Ignore PermissionError and ModuleNotFoundError which indicates hub-sdk not installed
                pass

    self.trainer.hub_session = self.session  # attach optional HUB session
    self.trainer.train()
    # Update model and cfg after training
    if RANK in {-1, 0}:
        ckpt = self.trainer.best if self.trainer.best.exists() else self.trainer.last
        self.model, _ = attempt_load_one_weight(ckpt)
        self.overrides = self.model.args
        self.metrics = getattr(self.trainer.validator, "metrics", None)  # TODO: no metrics returned by DDP
    return self.metrics

tune(use_ray=False, iterations=10, *args, **kwargs)

Ray Tune kullanma se├žene─či ile model i├žin hiperparametre ayarlamas─▒ yapar.

Bu y├Ântem iki hiperparametre ayarlama modunu destekler: Ray Tune veya ├Âzel bir ayarlama y├Ântemi kullanma. Ray Tune etkinle┼čtirildi─činde, ultralytics.utils.tuner mod├╝l├╝ndeki 'run_ray_tune' i┼člevinden yararlan─▒r. Aksi takdirde, ayarlama i├žin dahili 'Tuner' s─▒n─▒f─▒n─▒ kullan─▒r. Y├Ântem varsay─▒lan, ge├žersiz k─▒l─▒nm─▒┼č ve ayarlama s├╝recini yap─▒land─▒rmak i├žin ├Âzel arg├╝manlar.

Parametreler:

─░sim Tip A├ž─▒klama Varsay─▒lan
use_ray bool

True ise, hiperparametre ayar─▒ i├žin Ray Tune kullan─▒r. Varsay─▒lan de─čer False'dir.

False
iterations int

Ger├žekle┼čtirilecek ayarlama yinelemelerinin say─▒s─▒. Varsay─▒lan de─čer 10'dur.

10
*args list

Ek arg├╝manlar i├žin de─či┼čken uzunlukta arg├╝man listesi.

()
**kwargs any

Keyfi anahtar kelime arg├╝manlar─▒. Bunlar modelin ge├žersiz k─▒lmalar─▒ ve varsay─▒lanlar─▒ ile birle┼čtirilir.

{}

─░ade:

Tip A├ž─▒klama
dict

Hiperparametre aramas─▒n─▒n sonu├žlar─▒n─▒ i├žeren bir s├Âzl├╝k.

Zamlar:

Tip A├ž─▒klama
AssertionError

E─čer model bir PyTorch modeli de─čilse.

Kaynak kodu ultralytics/engine/model.py
def tune(
    self,
    use_ray=False,
    iterations=10,
    *args,
    **kwargs,
):
    """
    Conducts hyperparameter tuning for the model, with an option to use Ray Tune.

    This method supports two modes of hyperparameter tuning: using Ray Tune or a custom tuning method.
    When Ray Tune is enabled, it leverages the 'run_ray_tune' function from the ultralytics.utils.tuner module.
    Otherwise, it uses the internal 'Tuner' class for tuning. The method combines default, overridden, and
    custom arguments to configure the tuning process.

    Args:
        use_ray (bool): If True, uses Ray Tune for hyperparameter tuning. Defaults to False.
        iterations (int): The number of tuning iterations to perform. Defaults to 10.
        *args (list): Variable length argument list for additional arguments.
        **kwargs (any): Arbitrary keyword arguments. These are combined with the model's overrides and defaults.

    Returns:
        (dict): A dictionary containing the results of the hyperparameter search.

    Raises:
        AssertionError: If the model is not a PyTorch model.
    """
    self._check_is_pytorch_model()
    if use_ray:
        from ultralytics.utils.tuner import run_ray_tune

        return run_ray_tune(self, max_samples=iterations, *args, **kwargs)
    else:
        from .tuner import Tuner

        custom = {}  # method defaults
        args = {**self.overrides, **custom, **kwargs, "mode": "train"}  # highest priority args on the right
        return Tuner(args=args, _callbacks=self.callbacks)(model=self, iterations=iterations)

val(validator=None, **kwargs)

Belirtilen bir veri k├╝mesini ve do─črulama yap─▒land─▒rmas─▒n─▒ kullanarak modeli do─črular.

Bu y├Ântem, model do─črulama s├╝recini kolayla┼čt─▒rarak ├že┼čitli ├Âzelle┼čtirmelere olanak tan─▒r ayarlar ve yap─▒land─▒rmalar. ├ľzel bir do─črulay─▒c─▒ veya varsay─▒lan do─črulama yakla┼č─▒m─▒ ile do─črulamay─▒ destekler. Y├Ântem, yap─▒land─▒rmak i├žin varsay─▒lan yap─▒land─▒rmalar─▒, y├Ânteme ├Âzg├╝ varsay─▒lanlar─▒ ve kullan─▒c─▒ taraf─▒ndan sa─članan arg├╝manlar─▒ birle┼čtirir do─črulama s├╝reci. Do─črulama i┼čleminden sonra modelin metriklerini, do─črulama i┼čleminden elde edilen sonu├žlarla g├╝nceller. do─črulay─▒c─▒.

Y├Ântem, do─črulama s├╝recinin ├Âzelle┼čtirilmesine olanak tan─▒yan ├že┼čitli arg├╝manlar─▒ destekler. Kapsaml─▒ bir do─črulama i├žin Yap─▒land─▒r─▒labilir t├╝m se├ženeklerin listesi i├žin, kullan─▒c─▒lar belgelerdeki 'yap─▒land─▒rma' b├Âl├╝m├╝ne ba┼čvurmal─▒d─▒r.

Parametreler:

─░sim Tip A├ž─▒klama Varsay─▒lan
validator BaseValidator

Modeli do─črulamak i├žin ├Âzel bir do─črulay─▒c─▒ s─▒n─▒f─▒n─▒n bir ├Ârne─či. E─čer Yok, y├Ântem varsay─▒lan bir do─črulay─▒c─▒ kullan─▒r. Varsay─▒lan de─čer Yok'tur.

None
**kwargs any

Do─črulama yap─▒land─▒rmas─▒n─▒ temsil eden keyfi anahtar s├Âzc├╝k ba─č─▒ms─▒z de─či┼čkenleri. Bu arg├╝manlar ┼čunlard─▒r do─črulama s├╝recinin ├že┼čitli y├Ânlerini ├Âzelle┼čtirmek i├žin kullan─▒l─▒r.

{}

─░ade:

Tip A├ž─▒klama
dict

Do─črulama s├╝recinden elde edilen do─črulama metrikleri.

Zamlar:

Tip A├ž─▒klama
AssertionError

E─čer model bir PyTorch modeli de─čilse.

Kaynak kodu ultralytics/engine/model.py
def val(
    self,
    validator=None,
    **kwargs,
):
    """
    Validates the model using a specified dataset and validation configuration.

    This method facilitates the model validation process, allowing for a range of customization through various
    settings and configurations. It supports validation with a custom validator or the default validation approach.
    The method combines default configurations, method-specific defaults, and user-provided arguments to configure
    the validation process. After validation, it updates the model's metrics with the results obtained from the
    validator.

    The method supports various arguments that allow customization of the validation process. For a comprehensive
    list of all configurable options, users should refer to the 'configuration' section in the documentation.

    Args:
        validator (BaseValidator, optional): An instance of a custom validator class for validating the model. If
            None, the method uses a default validator. Defaults to None.
        **kwargs (any): Arbitrary keyword arguments representing the validation configuration. These arguments are
            used to customize various aspects of the validation process.

    Returns:
        (dict): Validation metrics obtained from the validation process.

    Raises:
        AssertionError: If the model is not a PyTorch model.
    """
    custom = {"rect": True}  # method defaults
    args = {**self.overrides, **custom, **kwargs, "mode": "val"}  # highest priority args on the right

    validator = (validator or self._smart_load("validator"))(args=args, _callbacks=self.callbacks)
    validator(model=self.model)
    self.metrics = validator.metrics
    return validator.metrics





Created 2023-11-12, Updated 2024-06-02
Authors: glenn-jocher (5), Burhan-Q (1)