Zum Inhalt springen

Referenz fĂŒr hub_sdk/modules/models.py

Hinweis

Diese Datei ist verfĂŒgbar unter https://github.com/ultralytics/hub-sdk/blob/main/hub_sdk/modules/models .py. Wenn du ein Problem entdeckst, hilf bitte mit, es zu beheben, indem du einen Pull Request đŸ› ïž einreichst. Vielen Dank 🙏!



hub_sdk.modules.models.Models

Basen: CRUDClient

Eine Klasse, die einen Client fĂŒr die Interaktion mit Models durch CRUD-Operationen darstellt. Diese Klasse erweitert die CRUDClient Klasse und bietet spezielle Methoden fĂŒr die Arbeit mit Models.

Attribute:

Name Typ Beschreibung
base_endpoint str

Die Basis-Endpunkt-URL fĂŒr die API, eingestellt auf "models".

hub_client ModelUpload

Eine Instanz von ModelUpload, die fĂŒr die Interaktion mit Modell-Uploads verwendet wird.

id (str, None)

Der eindeutige Bezeichner des Modells, falls vorhanden.

data dict

Ein Wörterbuch zum Speichern von Modelldaten.

metrics

Platzhalter fĂŒr die Speicherung von Modellmetriken, falls nach dem Abruf verfĂŒgbar.

Hinweis

Das Attribut "id" wird bei der Initialisierung gesetzt und kann zur eindeutigen Identifizierung eines Modells verwendet werden. Das Attribut "data" wird verwendet, um Modelldaten zu speichern, die von der API abgerufen werden.

Quellcode in hub_sdk/modules/models.py
class Models(CRUDClient):
    """
    A class representing a client for interacting with Models through CRUD operations. This class extends the CRUDClient
    class and provides specific methods for working with Models.

    Attributes:
        base_endpoint (str): The base endpoint URL for the API, set to "models".
        hub_client (ModelUpload): An instance of ModelUpload used for interacting with model uploads.
        id (str, None): The unique identifier of the model, if available.
        data (dict): A dictionary to store model data.
        metrics: Placeholder for storing model metrics, if available after retrieval.

    Note:
        The 'id' attribute is set during initialization and can be used to uniquely identify a model.
        The 'data' attribute is used to store model data fetched from the API.
    """

    def __init__(self, model_id: Optional[str] = None, headers: Optional[Dict[str, Any]] = None):
        """
        Initialize a Models instance.

        Args:
            model_id (str, optional): The unique identifier of the model.
            headers (dict, optional): Headers to be included in API requests.
        """
        self.base_endpoint = "models"
        super().__init__(self.base_endpoint, "model", headers)
        self.hub_client = ModelUpload(headers)
        self.id = model_id
        self.data = {}
        self.metrics = None
        if model_id:
            self.get_data()

    @staticmethod
    def _reconstruct_data(data: dict) -> dict:
        """
        Reconstruct format of model data supported by ultralytics.

        Args:
            data: dict
        Returns:
            (dict): Reconstructed data format
        """
        if not data:
            return data

        data["config"] = {
            "batchSize": data.pop("batch_size", None),
            "epochs": data.pop("epochs", None),
            "imageSize": data.pop("imgsz", None),
            "patience": data.pop("patience", None),
            "device": data.pop("device", None),
            "cache": data.pop("cache", None),
        }

        return data

    def get_data(self) -> None:
        """
        Retrieves data for the current model instance.

        If a valid model ID has been set, it sends a request to fetch the model data and stores it in the instance.
        If no model ID has been set, it logs an error message.

        Returns:
            (None): The method does not return a value.
        """
        if not self.id:
            self.logger.error("No model id has been set. Update the model id or create a model.")
            return

        try:
            response = super().read(self.id)

            if response is None:
                self.logger.error(f"Received no response from the server for model ID: {self.id}")
                return

            # Check if the response has a .json() method (it should if it's a response object)
            if not hasattr(response, "json"):
                self.logger.error(f"Invalid response object received for model ID: {self.id}")
                return

            resp_data = response.json()
            if resp_data is None:
                self.logger.error(f"No data received in the response for model ID: {self.id}")
                return

            data = resp_data.get("data", {})
            self.data = self._reconstruct_data(data)
            self.logger.debug(f"Model data retrieved for ID: {self.id}")

        except Exception as e:
            self.logger.error(f"An error occurred while retrieving data for model ID: {self.id}, {str(e)}")

    def create_model(self, model_data: dict) -> None:
        """
        Creates a new model with the provided data and sets the model ID for the current instance.

        Args:
            model_data (dict): A dictionary containing the data for creating the model.

        Returns:
            (None): The method does not return a value.
        """
        try:
            response = super().create(model_data)

            if response is None:
                self.logger.error("Received no response from the server while creating the model.")
                return

            # Ensuring the response object has the .json() method
            if not hasattr(response, "json"):
                self.logger.error("Invalid response object received while creating the model.")
                return

            resp_data = response.json()
            if resp_data is None:
                self.logger.error("No data received in the response while creating the model.")
                return

            self.id = resp_data.get("data", {}).get("id")

            # Check if the ID was successfully retrieved
            if not self.id:
                self.logger.error("Model ID not found in the response data.")
                return

            self.get_data()

        except Exception as e:
            self.logger.error(f"An error occurred while creating the model: {str(e)}")

    def is_resumable(self) -> bool:
        """
        Check if the model training can be resumed.

        Returns:
            (bool): True if resumable, False otherwise.
        """
        return self.data.get("has_last_weights", False)

    def has_best_weights(self) -> bool:
        """
        Check if the model has best weights saved.

        Returns:
            (bool): True if best weights available, False otherwise.
        """
        return self.data.get("has_best_weights", False)

    def is_pretrained(self) -> bool:
        """
        Check if the model is pretrained.

        Returns:
            (bool): True if pretrained, False otherwise.
        """
        return self.data.get("is_pretrained", False)

    def is_trained(self) -> bool:
        """
        Check if the model is trained.

        Returns:
            (bool): True if trained, False otherwise.
        """
        return self.data.get("status") == "trained"

    def is_custom(self) -> bool:
        """
        Check if the model is custom.

        Returns:
            (bool): True if custom, False otherwise.
        """
        return self.data.get("is_custom", False)

    def get_architecture(self) -> Optional[str]:
        """
        Get the architecture name of the model.

        Returns:
            (Optional[str]): The architecture name followed by '.yaml' or None if not available.
        """
        return self.data.get("cfg")

    def get_dataset_url(self) -> Optional[str]:
        """
        Get the dataset URL associated with the model.

        Returns:
            (Optional[str]): The URL of the dataset or None if not available.
        """
        return self.data.get("data")

    def get_weights_url(self, weight: str = "best") -> Optional[str]:
        """
        Get the URL of the model weights.

        Args:
            weight (str, optional): Type of weights to retrieve.

        Returns:
            (Optional[str]): The URL of the specified weights or None if not available.
        """
        if weight == "last":
            return self.data.get("resume")

        return self.data.get("weights")

    def delete(self, hard: bool = False) -> Optional[Response]:
        """
        Delete the model resource represented by this instance.

        Args:
            hard (bool, optional): If True, perform a hard (permanent) delete.

        Note:
            The 'hard' parameter determines whether to perform a soft delete (default) or a hard delete.
            In a soft delete, the model might be marked as deleted but retained in the system.
            In a hard delete, the model is permanently removed from the system.

        Returns:
            (Optional[Response]): Response object from the delete request, or None if delete fails.
        """
        return super().delete(self.id, hard)

    def update(self, data: dict) -> Optional[Response]:
        """
        Update the model resource represented by this instance.

        Args:
            data (dict): The updated data for the model resource.

        Returns:
            (Optional[Response]): Response object from the update request, or None if update fails.
        """
        return super().update(self.id, data)

    def get_metrics(self) -> Optional[List[Dict[str, Any]]]:
        """
        Get metrics to of model.

        Returns:
            (list(dict), optional): The list of metrics objects, or None if it fails.
        """
        if self.metrics:
            return self.metrics

        endpoint = f"{HUB_API_ROOT}/v1/{self.base_endpoint}/{self.id}/metrics"
        try:
            results = self.get(endpoint)
            self.metrics = results.json().get("data")
            return self.metrics
        except Exception as e:
            self.logger.error(f"Model Metrics not found: {e}")

    def upload_model(
        self,
        epoch: int,
        weights: str,
        is_best: bool = False,
        map: float = 0.0,
        final: bool = False,
    ) -> Optional[Response]:
        """
        Upload a model checkpoint to Ultralytics HUB.

        Args:
            epoch (int): The current training epoch.
            weights (str): Path to the model weights file.
            is_best (bool): Indicates if the current model is the best one so far.
            map (float): Mean average precision of the model.
            final (bool): Indicates if the model is the final model after training.

        Returns:
            (Optional[Response]): Response object from the upload request, or None if upload fails.
        """
        return self.hub_client.upload_model(self.id, epoch, weights, is_best=is_best, map=map, final=final)

    def upload_metrics(self, metrics: dict) -> Optional[Response]:
        """
        Upload model metrics to Ultralytics HUB.

        Args:
            metrics (dict):

        Returns:
            (Optional[Response]): Response object from the upload metrics request, or None if it fails.
        """
        return self.hub_client.upload_metrics(self.id, metrics)  # response

    def start_heartbeat(self, interval: int = 60):
        """
        Starts sending heartbeat signals to a remote hub server.

        This method initiates the sending of heartbeat signals to a hub server
        in order to indicate the continued availability and health of the client.

        Args:
            interval (int): The time interval, in seconds, between consecutive heartbeats.

        Returns:
            (None): The method does not return a value.

        Note:
            Heartbeats are essential for maintaining a connection with the hub server
            and ensuring that the client remains active and responsive.
        """
        self.hub_client._register_signal_handlers()
        self.hub_client._start_heartbeats(self.id, interval)

    def stop_heartbeat(self) -> None:
        """
        Stops sending heartbeat signals to a remote hub server.

        This method terminates the sending of heartbeat signals to the hub server,
        effectively signaling that the client is no longer available or active.

        Returns:
            (None): The method does not return a value.

        Note:
            Stopping heartbeats should be done carefully, as it may result in the hub server
            considering the client as disconnected or unavailable.
        """
        self.hub_client._stop_heartbeats()

    def export(self, format: str) -> Optional[Response]:
        """
        Export to Ultralytics HUB.

        Args: format (str): Export format here. Here are supported export [formats](
        https://docs.ultralytics.com/modes/export/#export-formats)

        Returns:
            (Optional[Response]): Response object from the export request, or None if export fails.
        """
        return self.hub_client.export(self.id, format)  # response

    def predict(self, image: str, config: Dict[str, Any]) -> Optional[Response]:
        """
        Predict to Ultralytics HUB.

        Args:
            image (str): The path to the image file.
            config (dict): A configuration for the prediction (JSON).

        Returns:
            (Optional[Response]): Response object from the predict request, or None if upload fails.
        """
        return self.hub_client.predict(self.id, image, config)  # response

__init__(model_id=None, headers=None)

Initialisiere eine Models-Instanz.

Parameter:

Name Typ Beschreibung Standard
model_id str

Der eindeutige Bezeichner des Modells.

None
headers dict

Kopfzeilen, die in API-Anfragen enthalten sein mĂŒssen.

None
Quellcode in hub_sdk/modules/models.py
def __init__(self, model_id: Optional[str] = None, headers: Optional[Dict[str, Any]] = None):
    """
    Initialize a Models instance.

    Args:
        model_id (str, optional): The unique identifier of the model.
        headers (dict, optional): Headers to be included in API requests.
    """
    self.base_endpoint = "models"
    super().__init__(self.base_endpoint, "model", headers)
    self.hub_client = ModelUpload(headers)
    self.id = model_id
    self.data = {}
    self.metrics = None
    if model_id:
        self.get_data()

create_model(model_data)

Erzeugt ein neues Modell mit den angegebenen Daten und setzt die Modell-ID fĂŒr die aktuelle Instanz.

Parameter:

Name Typ Beschreibung Standard
model_data dict

Ein Wörterbuch, das die Daten fĂŒr die Erstellung des Modells enthĂ€lt.

erforderlich

Retouren:

Typ Beschreibung
None

Die Methode gibt keinen Wert zurĂŒck.

Quellcode in hub_sdk/modules/models.py
def create_model(self, model_data: dict) -> None:
    """
    Creates a new model with the provided data and sets the model ID for the current instance.

    Args:
        model_data (dict): A dictionary containing the data for creating the model.

    Returns:
        (None): The method does not return a value.
    """
    try:
        response = super().create(model_data)

        if response is None:
            self.logger.error("Received no response from the server while creating the model.")
            return

        # Ensuring the response object has the .json() method
        if not hasattr(response, "json"):
            self.logger.error("Invalid response object received while creating the model.")
            return

        resp_data = response.json()
        if resp_data is None:
            self.logger.error("No data received in the response while creating the model.")
            return

        self.id = resp_data.get("data", {}).get("id")

        # Check if the ID was successfully retrieved
        if not self.id:
            self.logger.error("Model ID not found in the response data.")
            return

        self.get_data()

    except Exception as e:
        self.logger.error(f"An error occurred while creating the model: {str(e)}")

delete(hard=False)

Lösche die Modellressource, die durch diese Instanz reprÀsentiert wird.

Parameter:

Name Typ Beschreibung Standard
hard bool

Wenn True, fĂŒhre eine harte (permanente) Löschung durch.

False
Hinweis

Der Parameter "hart" legt fest, ob ein weiches Löschen (Standard) oder ein hartes Löschen durchgefĂŒhrt werden soll. Bei einer weichen Löschung kann das Modell als gelöscht markiert werden, bleibt aber im System erhalten. Bei einer harten Löschung wird das Modell dauerhaft aus dem System entfernt.

Retouren:

Typ Beschreibung
Optional[Response]

Antwortobjekt der Löschanfrage oder Keine, wenn das Löschen fehlschlÀgt.

Quellcode in hub_sdk/modules/models.py
def delete(self, hard: bool = False) -> Optional[Response]:
    """
    Delete the model resource represented by this instance.

    Args:
        hard (bool, optional): If True, perform a hard (permanent) delete.

    Note:
        The 'hard' parameter determines whether to perform a soft delete (default) or a hard delete.
        In a soft delete, the model might be marked as deleted but retained in the system.
        In a hard delete, the model is permanently removed from the system.

    Returns:
        (Optional[Response]): Response object from the delete request, or None if delete fails.
    """
    return super().delete(self.id, hard)

export(format)

Exportiere zu Ultralytics HUB.

Args: format (str): Exportiere hier das Format. Hier sind die unterstĂŒtzten Exportformate

Retouren:

Typ Beschreibung
Optional[Response]

Antwortobjekt der Exportanfrage oder Keine, wenn der Export fehlschlÀgt.

Quellcode in hub_sdk/modules/models.py
def export(self, format: str) -> Optional[Response]:
    """
    Export to Ultralytics HUB.

    Args: format (str): Export format here. Here are supported export [formats](
    https://docs.ultralytics.com/modes/export/#export-formats)

    Returns:
        (Optional[Response]): Response object from the export request, or None if export fails.
    """
    return self.hub_client.export(self.id, format)  # response

get_architecture()

Ermittelt den Namen der Architektur des Modells.

Retouren:

Typ Beschreibung
Optional[str]

Der Name der Architektur, gefolgt von '.yaml' oder None, falls nicht vorhanden.

Quellcode in hub_sdk/modules/models.py
def get_architecture(self) -> Optional[str]:
    """
    Get the architecture name of the model.

    Returns:
        (Optional[str]): The architecture name followed by '.yaml' or None if not available.
    """
    return self.data.get("cfg")

get_data()

Ruft die Daten fĂŒr die aktuelle Modellinstanz ab.

Wenn eine gĂŒltige Modell-ID festgelegt wurde, sendet es eine Anfrage, um die Modelldaten zu holen und speichert sie in der Instanz. Wenn keine Modell-ID festgelegt wurde, wird eine Fehlermeldung ausgegeben.

Retouren:

Typ Beschreibung
None

Die Methode gibt keinen Wert zurĂŒck.

Quellcode in hub_sdk/modules/models.py
def get_data(self) -> None:
    """
    Retrieves data for the current model instance.

    If a valid model ID has been set, it sends a request to fetch the model data and stores it in the instance.
    If no model ID has been set, it logs an error message.

    Returns:
        (None): The method does not return a value.
    """
    if not self.id:
        self.logger.error("No model id has been set. Update the model id or create a model.")
        return

    try:
        response = super().read(self.id)

        if response is None:
            self.logger.error(f"Received no response from the server for model ID: {self.id}")
            return

        # Check if the response has a .json() method (it should if it's a response object)
        if not hasattr(response, "json"):
            self.logger.error(f"Invalid response object received for model ID: {self.id}")
            return

        resp_data = response.json()
        if resp_data is None:
            self.logger.error(f"No data received in the response for model ID: {self.id}")
            return

        data = resp_data.get("data", {})
        self.data = self._reconstruct_data(data)
        self.logger.debug(f"Model data retrieved for ID: {self.id}")

    except Exception as e:
        self.logger.error(f"An error occurred while retrieving data for model ID: {self.id}, {str(e)}")

get_dataset_url()

Ermittelt die URL des Datensatzes, der mit dem Modell verknĂŒpft ist.

Retouren:

Typ Beschreibung
Optional[str]

Die URL des Datensatzes oder Keine, wenn nicht verfĂŒgbar.

Quellcode in hub_sdk/modules/models.py
def get_dataset_url(self) -> Optional[str]:
    """
    Get the dataset URL associated with the model.

    Returns:
        (Optional[str]): The URL of the dataset or None if not available.
    """
    return self.data.get("data")

get_metrics()

Erhalte Metriken fĂŒr das Modell.

Retouren:

Typ Beschreibung
(list(dict), optional)

Die Liste der Metrik-Objekte oder Keine, wenn sie fehlschlÀgt.

Quellcode in hub_sdk/modules/models.py
def get_metrics(self) -> Optional[List[Dict[str, Any]]]:
    """
    Get metrics to of model.

    Returns:
        (list(dict), optional): The list of metrics objects, or None if it fails.
    """
    if self.metrics:
        return self.metrics

    endpoint = f"{HUB_API_ROOT}/v1/{self.base_endpoint}/{self.id}/metrics"
    try:
        results = self.get(endpoint)
        self.metrics = results.json().get("data")
        return self.metrics
    except Exception as e:
        self.logger.error(f"Model Metrics not found: {e}")

get_weights_url(weight='best')

Erhalte die URL der Modellgewichte.

Parameter:

Name Typ Beschreibung Standard
weight str

Art der abzurufenden Gewichte.

'best'

Retouren:

Typ Beschreibung
Optional[str]

Die URL der angegebenen Gewichte oder Keine, wenn nicht verfĂŒgbar.

Quellcode in hub_sdk/modules/models.py
def get_weights_url(self, weight: str = "best") -> Optional[str]:
    """
    Get the URL of the model weights.

    Args:
        weight (str, optional): Type of weights to retrieve.

    Returns:
        (Optional[str]): The URL of the specified weights or None if not available.
    """
    if weight == "last":
        return self.data.get("resume")

    return self.data.get("weights")

has_best_weights()

PrĂŒfe, ob das Modell die besten Gewichte gespeichert hat.

Retouren:

Typ Beschreibung
bool

True, wenn die besten Gewichte verfĂŒgbar sind, sonst False.

Quellcode in hub_sdk/modules/models.py
def has_best_weights(self) -> bool:
    """
    Check if the model has best weights saved.

    Returns:
        (bool): True if best weights available, False otherwise.
    """
    return self.data.get("has_best_weights", False)

is_custom()

PrĂŒfe, ob das Modell benutzerdefiniert ist.

Retouren:

Typ Beschreibung
bool

True, wenn benutzerdefiniert, sonst False.

Quellcode in hub_sdk/modules/models.py
def is_custom(self) -> bool:
    """
    Check if the model is custom.

    Returns:
        (bool): True if custom, False otherwise.
    """
    return self.data.get("is_custom", False)

is_pretrained()

PrĂŒfe, ob das Modell vortrainiert ist.

Retouren:

Typ Beschreibung
bool

True, wenn vortrainiert, sonst False.

Quellcode in hub_sdk/modules/models.py
def is_pretrained(self) -> bool:
    """
    Check if the model is pretrained.

    Returns:
        (bool): True if pretrained, False otherwise.
    """
    return self.data.get("is_pretrained", False)

is_resumable()

PrĂŒfe, ob das Modelltraining wieder aufgenommen werden kann.

Retouren:

Typ Beschreibung
bool

True, wenn es wieder aufgenommen werden kann, sonst False.

Quellcode in hub_sdk/modules/models.py
def is_resumable(self) -> bool:
    """
    Check if the model training can be resumed.

    Returns:
        (bool): True if resumable, False otherwise.
    """
    return self.data.get("has_last_weights", False)

is_trained()

PrĂŒfe, ob das Modell trainiert ist.

Retouren:

Typ Beschreibung
bool

True, wenn trainiert, sonst False.

Quellcode in hub_sdk/modules/models.py
def is_trained(self) -> bool:
    """
    Check if the model is trained.

    Returns:
        (bool): True if trained, False otherwise.
    """
    return self.data.get("status") == "trained"

predict(image, config)

Voraussage an Ultralytics HUB.

Parameter:

Name Typ Beschreibung Standard
image str

Der Pfad zur Bilddatei.

erforderlich
config dict

Eine Konfiguration fĂŒr die Vorhersage (JSON).

erforderlich

Retouren:

Typ Beschreibung
Optional[Response]

Antwortobjekt aus der PrÀdiktionsanfrage oder Keine, wenn der Upload fehlschlÀgt.

Quellcode in hub_sdk/modules/models.py
def predict(self, image: str, config: Dict[str, Any]) -> Optional[Response]:
    """
    Predict to Ultralytics HUB.

    Args:
        image (str): The path to the image file.
        config (dict): A configuration for the prediction (JSON).

    Returns:
        (Optional[Response]): Response object from the predict request, or None if upload fails.
    """
    return self.hub_client.predict(self.id, image, config)  # response

start_heartbeat(interval=60)

Beginnt mit dem Senden von Heartbeat-Signalen an einen entfernten Hub-Server.

Diese Methode initiiert das Senden von Heartbeat-Signalen an einen Hub-Server um die kontinuierliche VerfĂŒgbarkeit und den Zustand des Clients anzuzeigen.

Parameter:

Name Typ Beschreibung Standard
interval int

Das Zeitintervall in Sekunden zwischen aufeinanderfolgenden HerzschlÀgen.

60

Retouren:

Typ Beschreibung
None

Die Methode gibt keinen Wert zurĂŒck.

Hinweis

Heartbeats sind wichtig fĂŒr die Aufrechterhaltung der Verbindung mit dem Hubserver und stellen sicher, dass der Client aktiv und ansprechbar bleibt.

Quellcode in hub_sdk/modules/models.py
def start_heartbeat(self, interval: int = 60):
    """
    Starts sending heartbeat signals to a remote hub server.

    This method initiates the sending of heartbeat signals to a hub server
    in order to indicate the continued availability and health of the client.

    Args:
        interval (int): The time interval, in seconds, between consecutive heartbeats.

    Returns:
        (None): The method does not return a value.

    Note:
        Heartbeats are essential for maintaining a connection with the hub server
        and ensuring that the client remains active and responsive.
    """
    self.hub_client._register_signal_handlers()
    self.hub_client._start_heartbeats(self.id, interval)

stop_heartbeat()

Beendet das Senden von Heartbeat-Signalen an einen entfernten Hub-Server.

Mit dieser Methode wird das Senden von Heartbeat-Signalen an den Hub-Server beendet, und signalisiert damit, dass der Client nicht mehr verfĂŒgbar oder aktiv ist.

Retouren:

Typ Beschreibung
None

Die Methode gibt keinen Wert zurĂŒck.

Hinweis

Das Anhalten von Heartbeats sollte vorsichtig erfolgen, da es dazu fĂŒhren kann, dass der Hubserver dass der Hub-Server den Client als nicht mehr verbunden oder nicht mehr verfĂŒgbar betrachtet.

Quellcode in hub_sdk/modules/models.py
def stop_heartbeat(self) -> None:
    """
    Stops sending heartbeat signals to a remote hub server.

    This method terminates the sending of heartbeat signals to the hub server,
    effectively signaling that the client is no longer available or active.

    Returns:
        (None): The method does not return a value.

    Note:
        Stopping heartbeats should be done carefully, as it may result in the hub server
        considering the client as disconnected or unavailable.
    """
    self.hub_client._stop_heartbeats()

update(data)

Aktualisiere die durch diese Instanz reprÀsentierte Modellressource.

Parameter:

Name Typ Beschreibung Standard
data dict

Die aktualisierten Daten fĂŒr die Modellressource.

erforderlich

Retouren:

Typ Beschreibung
Optional[Response]

Antwortobjekt der Aktualisierungsanfrage oder Keine, wenn die Aktualisierung fehlschlÀgt.

Quellcode in hub_sdk/modules/models.py
def update(self, data: dict) -> Optional[Response]:
    """
    Update the model resource represented by this instance.

    Args:
        data (dict): The updated data for the model resource.

    Returns:
        (Optional[Response]): Response object from the update request, or None if update fails.
    """
    return super().update(self.id, data)

upload_metrics(metrics)

Lade die Modellmetriken auf Ultralytics HUB hoch.

Parameter:

Name Typ Beschreibung Standard
metrics dict
erforderlich

Retouren:

Typ Beschreibung
Optional[Response]

Antwortobjekt der Upload-Metrics-Anfrage oder Keine, wenn sie fehlschlÀgt.

Quellcode in hub_sdk/modules/models.py
def upload_metrics(self, metrics: dict) -> Optional[Response]:
    """
    Upload model metrics to Ultralytics HUB.

    Args:
        metrics (dict):

    Returns:
        (Optional[Response]): Response object from the upload metrics request, or None if it fails.
    """
    return self.hub_client.upload_metrics(self.id, metrics)  # response

upload_model(epoch, weights, is_best=False, map=0.0, final=False)

Lade einen ModellprĂŒfpunkt auf Ultralytics HUB hoch.

Parameter:

Name Typ Beschreibung Standard
epoch int

Die aktuelle Trainingsepoche.

erforderlich
weights str

Pfad zur Datei mit den Modellgewichten.

erforderlich
is_best bool

Zeigt an, ob das aktuelle Modell das bisher beste ist.

False
map float

Mittlere durchschnittliche Genauigkeit des Modells.

0.0
final bool

Gibt an, ob das Modell das endgĂŒltige Modell nach dem Training ist.

False

Retouren:

Typ Beschreibung
Optional[Response]

Antwortobjekt der Upload-Anforderung oder Keine, wenn der Upload fehlschlÀgt.

Quellcode in hub_sdk/modules/models.py
def upload_model(
    self,
    epoch: int,
    weights: str,
    is_best: bool = False,
    map: float = 0.0,
    final: bool = False,
) -> Optional[Response]:
    """
    Upload a model checkpoint to Ultralytics HUB.

    Args:
        epoch (int): The current training epoch.
        weights (str): Path to the model weights file.
        is_best (bool): Indicates if the current model is the best one so far.
        map (float): Mean average precision of the model.
        final (bool): Indicates if the model is the final model after training.

    Returns:
        (Optional[Response]): Response object from the upload request, or None if upload fails.
    """
    return self.hub_client.upload_model(self.id, epoch, weights, is_best=is_best, map=map, final=final)



hub_sdk.modules.models.ModelList

Basen: PaginatedList

Quellcode in hub_sdk/modules/models.py
class ModelList(PaginatedList):
    def __init__(self, page_size=None, public=None, headers=None):
        """
        Initialize a ModelList instance.

        Args:
            page_size (int, optional): The number of items to request per page.
            public (bool, optional): Whether the items should be publicly accessible.
            headers (dict, optional): Headers to be included in API requests.
        """
        base_endpoint = "models"
        super().__init__(base_endpoint, "model", page_size, public, headers)

__init__(page_size=None, public=None, headers=None)

Initialisiere eine ModelList-Instanz.

Parameter:

Name Typ Beschreibung Standard
page_size int

Die Anzahl der anzufordernden Artikel pro Seite.

None
public bool

Ob die GegenstÀnde öffentlich zugÀnglich sein sollen.

None
headers dict

Kopfzeilen, die in API-Anfragen enthalten sein mĂŒssen.

None
Quellcode in hub_sdk/modules/models.py
def __init__(self, page_size=None, public=None, headers=None):
    """
    Initialize a ModelList instance.

    Args:
        page_size (int, optional): The number of items to request per page.
        public (bool, optional): Whether the items should be publicly accessible.
        headers (dict, optional): Headers to be included in API requests.
    """
    base_endpoint = "models"
    super().__init__(base_endpoint, "model", page_size, public, headers)