跳至内容

参考资料 hub_sdk/modules/models.py

备注

该文件位于https://github.com/ultralytics/hub-sdk/blob/main/ hub_sdk/modules/models .py。如果您发现问题,请通过提交 Pull Request🛠️ 帮助修复。谢谢🙏!



hub_sdk.modules.models.Models

垒球 CRUDClient

一个代表客户端的类,用于通过 CRUD 操作与模型交互。该类扩展了 CRUDClient 类,并提供了与模型交互的特定方法。

属性

名称 类型 说明
base_endpoint str

API 的基本端点 URL,设置为 "models"。

hub_client ModelUpload

用于与模型上传交互的 ModelUpload 实例。

id (str, None)

模型的唯一标识符(如果有)。

data dict

用于存储模型数据的字典。

metrics

用于存储模型度量的占位符(如果检索后可用)。

备注

id "属性在初始化过程中设置,可用于唯一标识模型。 data "属性用于存储从应用程序接口获取的模型数据。

源代码 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()

    def _reconstruct_data(self, 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("Received no response from the server for model id %s", 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("Invalid response object received for model id %s", self.id)
                return

            resp_data = response.json()
            if resp_data is None:
                self.logger.error("No data received in the response for model id %s", self.id)
                return

            data = resp_data.get("data", {})
            self.data = self._reconstruct_data(data)
            self.logger.debug("Model data retrieved for id %s", self.id)

        except Exception as e:
            self.logger.error("An error occurred while retrieving data for model id %s: %s", 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("An error occurred while creating the model: %s", 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("Model Metrics not found %s", 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 get_download_link(self, type: str) -> Optional[str]:
        """
        Get model download link.

        Args:
            type (Optional[str]):

        Returns:
            (Optional[str]): Return download link or None if the link is not available.
        """
        try:
            payload = {"collection": "models", "docId": self.id, "object": type}
            endpoint = f"{HUB_FUNCTIONS_ROOT}/v1/storage"
            response = self.post(endpoint, json=payload)
            json = response.json()
            return json.get("data", {}).get("url")
        except Exception as e:
            self.logger.error(f"Failed to download link for {self.name}: %s", e)
            raise e

    def start_heartbeat(self, interval: int = 60) -> None:
        """
        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)

初始化一个 Models 实例。

参数

名称 类型 说明 默认值
model_id str

模型的唯一标识符。

None
headers dict

应包含在 API 请求中的标头。

None
源代码 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)

使用提供的数据创建新模型,并为当前实例设置模型 ID。

参数

名称 类型 说明 默认值
model_data dict

包含用于创建模型的数据的字典。

所需

返回:

类型 说明
None

该方法不返回值。

源代码 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("An error occurred while creating the model: %s", str(e))

delete(hard=False)

删除该实例所代表的模型资源。

参数

名称 类型 说明 默认值
hard bool

如果为 True,则执行硬(永久)删除。

False
备注

硬 "参数决定执行软删除(默认)还是硬删除。 在软删除中,模型可能被标记为已删除,但仍保留在系统中。 在硬删除中,模型将从系统中永久删除。

返回:

类型 说明
Optional[Response]

删除请求的响应对象;如果删除失败,则为 "无"。

源代码 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)

导出到Ultralytics HUB 。

参数: format(str):此处的导出格式。以下是支持的导出格式

返回:

类型 说明
Optional[Response]

导出请求的响应对象;如果导出失败,则为 "无"。

源代码 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()

获取模型的架构名称。

返回:

类型 说明
Optional[str]

架构名称,后跟".yaml";如果没有,则为 "无"。

源代码 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()

读取当前模型实例的数据。

如果设置了有效的模型 ID,它就会发送请求获取模型数据并将其存储到实例中。 如果没有设置模型 ID,则会记录一条错误信息。

返回:

类型 说明
None

该方法不返回值。

源代码 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("Received no response from the server for model id %s", 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("Invalid response object received for model id %s", self.id)
            return

        resp_data = response.json()
        if resp_data is None:
            self.logger.error("No data received in the response for model id %s", self.id)
            return

        data = resp_data.get("data", {})
        self.data = self._reconstruct_data(data)
        self.logger.debug("Model data retrieved for id %s", self.id)

    except Exception as e:
        self.logger.error("An error occurred while retrieving data for model id %s: %s", self.id, str(e))

get_dataset_url()

获取与模型相关的数据集 URL。

返回:

类型 说明
Optional[str]

数据集的 URL,如果没有,则为 "无"。

源代码 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")

获取模型下载链接。

参数

名称 类型 说明 默认值
type Optional[str]
所需

返回:

类型 说明
Optional[str]

返回下载链接,如果链接不可用,则返回无。

源代码 hub_sdk/modules/models.py
def get_download_link(self, type: str) -> Optional[str]:
    """
    Get model download link.

    Args:
        type (Optional[str]):

    Returns:
        (Optional[str]): Return download link or None if the link is not available.
    """
    try:
        payload = {"collection": "models", "docId": self.id, "object": type}
        endpoint = f"{HUB_FUNCTIONS_ROOT}/v1/storage"
        response = self.post(endpoint, json=payload)
        json = response.json()
        return json.get("data", {}).get("url")
    except Exception as e:
        self.logger.error(f"Failed to download link for {self.name}: %s", e)
        raise e

get_metrics()

获取模型的指标。

返回:

类型 说明
(list(dict), optional)

度量对象列表,如果失败则为 "无"。

源代码 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("Model Metrics not found %s", e)

get_weights_url(weight='best')

获取模型权重的 URL。

参数

名称 类型 说明 默认值
weight str

要检索的权重类型。

'best'

返回:

类型 说明
Optional[str]

指定权重的 URL,如果没有,则为 "无"。

源代码 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()

检查模型是否保存了最佳权重。

返回:

类型 说明
bool

如果有最佳权重,则为 True,否则为 False。

源代码 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()

检查模型是否为自定义模型。

返回:

类型 说明
bool

自定义时为 True,否则为 False。

源代码 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()

检查模型是否经过预训练。

返回:

类型 说明
bool

如果经过预训练则为 True,否则为 False。

源代码 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()

检查是否可以恢复模型训练。

返回:

类型 说明
bool

如果可恢复为 True,否则为 False。

源代码 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()

检查模型是否训练有素。

返回:

类型 说明
bool

如果受过训练则为 True,否则为 False。

源代码 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)

预测至Ultralytics HUB 。

参数

名称 类型 说明 默认值
image str

图像文件的路径。

所需
config dict

预测的配置(JSON)。

所需

返回:

类型 说明
Optional[Response]

预测请求的响应对象;如果上传失败,则为 "无"。

源代码 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)

开始向远程hub 服务器发送心跳信号。

该方法会向hub 服务器发送心跳信号,以显示客户端的持续可用性和健康状况。 以显示客户端的持续可用性和健康状况。

参数

名称 类型 说明 默认值
interval int

连续心跳之间的时间间隔(秒)。

60

返回:

类型 说明
None

该方法不返回值。

备注

心跳对于维持与hub 服务器的连接和确保客户端保持活动状态至关重要。 的连接,并确保客户端保持活动和响应。

源代码 hub_sdk/modules/models.py
def start_heartbeat(self, interval: int = 60) -> None:
    """
    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()

停止向远程hub 服务器发送心跳信号。

此方法将终止向hub 服务器发送心跳信号、 该方法将终止向 服务器发送心跳信号,从而有效地表明客户端已不再可用或处于活动状态。

返回:

类型 说明
None

该方法不返回值。

备注

停止心跳应谨慎操作,因为这可能导致hub 服务器 认为客户端断开连接或不可用。

源代码 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)

更新此实例所代表的模型资源。

参数

名称 类型 说明 默认值
data dict

模型资源的更新数据。

所需

返回:

类型 说明
Optional[Response]

更新请求的响应对象;如果更新失败,则为 "无"。

源代码 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)

将模型指标上传到Ultralytics HUB 。

参数

名称 类型 说明 默认值
metrics dict
所需

返回:

类型 说明
Optional[Response]

上传度量请求的响应对象,如果失败则为 "无"。

源代码 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)

将模型检查点上传到Ultralytics HUB 。

参数

名称 类型 说明 默认值
epoch int

当前训练历元。

所需
weights str

模型权重文件的路径。

所需
is_best bool

表示当前模型是否是迄今为止最好的模型。

False
map float

模型的平均平均精度。

0.0
final bool

表示模型是否是训练后的最终模型。

False

返回:

类型 说明
Optional[Response]

上传请求的响应对象;如果上传失败,则为 "无"。

源代码 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

垒球 PaginatedList

源代码 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"
        if public:
            base_endpoint = f"public/{base_endpoint}"
        super().__init__(base_endpoint, "model", page_size, headers)

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

初始化一个 ModelList 实例。

参数

名称 类型 说明 默认值
page_size int

每页要申请的项目数。

None
public bool

项目是否应向公众开放。

None
headers dict

应包含在 API 请求中的标头。

None
源代码 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"
    if public:
        base_endpoint = f"public/{base_endpoint}"
    super().__init__(base_endpoint, "model", page_size, headers)