递归地把 numpy / torch 等类型转成纯 Python,可 JSON 序列化。
(obj)
| 15 | |
| 16 | |
| 17 | def to_python(obj): |
| 18 | """递归地把 numpy / torch 等类型转成纯 Python,可 JSON 序列化。""" |
| 19 | try: |
| 20 | import numpy as np # noqa |
| 21 | import torch # noqa |
| 22 | except Exception: |
| 23 | np = None |
| 24 | torch = None |
| 25 | |
| 26 | if np is not None and isinstance(obj, np.generic): |
| 27 | return obj.item() |
| 28 | if np is not None and isinstance(obj, np.ndarray): |
| 29 | return obj.tolist() |
| 30 | if torch is not None and isinstance(obj, torch.Tensor): |
| 31 | return obj.cpu().tolist() |
| 32 | |
| 33 | if isinstance(obj, dict): |
| 34 | return {k: to_python(v) for k, v in obj.items()} |
| 35 | if isinstance(obj, (list, tuple)): |
| 36 | return [to_python(v) for v in obj] |
| 37 | |
| 38 | return obj |
| 39 | |
| 40 | |
| 41 | parser = argparse.ArgumentParser() |
no outgoing calls
no test coverage detected
searching dependent graphs…