跳到内容

Numpyencoder

smac.utils.numpyencoder #

NumpyEncoder #

基类: JSONEncoder

用于 numpy 数据类型的自定义编码器

来自 stackoverflow.com/a/61903895

default #

default(obj: Any) -> Any

如果存在 numpy 数据类型,则通过转换为原生 python 类型进行处理

参数#

obj : 任意 待序列化的对象

返回值#

任意 原生 python 对象

源代码位于 smac/utils/numpyencoder.py
def default(self, obj: Any) -> Any:
    """Handle numpy datatypes if present by converting to native python

    Parameters
    ----------
    obj : Any
        Object to serialize

    Returns
    -------
    Any
        Object in native python
    """
    if isinstance(
        obj,
        (
            np.int_,
            np.intc,
            np.intp,
            np.int8,
            np.int16,
            np.int32,
            np.int64,
            np.uint8,
            np.uint16,
            np.uint32,
            np.uint64,
        ),
    ):
        return int(obj)

    elif isinstance(obj, (np.float16, np.float32, np.float64)):
        return float(obj)

    elif isinstance(obj, (np.complex64, np.complex128)):
        return {"real": obj.real, "imag": obj.imag}

    elif isinstance(obj, (np.ndarray,)):
        return obj.tolist()

    elif isinstance(obj, (np.bool_)):
        return bool(obj)

    elif isinstance(obj, (np.void)):
        return None

    return json.JSONEncoder.default(self, obj)