我刚开始使用Pydantic和ruaml.yaml,实际上我正在使用这两个工具做一个项目。
当我尝试加载一个模型配置并用mkdocs表示它时,我遇到了一个错误,它似乎ruaml.yaml无法转储到我的Pydantic模式的np.array对象上。
File "/usr/local/lib/python3.10/site-packages/ruamel/yaml/representer.py", line 337, in represent_undefined
raise RepresenterError(f'cannot represent an object: {data!s}')
ruamel.yaml.representer.RepresenterError: cannot represent an object: [0 0 0 0]
当我试图表达这一点时,它就会发生:
std: Optional[np.ndarray] = np.array([1.0, 1.0, 1.0, 1.0])
mean: Optional[np.ndarray] = np.array([0, 0, 0, 0])
有没有一个解决方案或我可以改变的东西?先谢谢你了!
测试:我尝试用以下代码替换它:
std: Optional[np.ndarray] = [1.0, 1.0, 1.0, 1.0]
mean: Optional[np.ndarray] = [0, 0, 0, 0]
但需要这些是np。数组对象为我的代码的其余部分。
1条答案
按热度按时间50few1ms1#
YAML在Language Independent types for YAML 1.1中定义了几种类型。
numpy.array
不在这个列表中,主要是因为它不是独立于语言的,所以没有像这样的非标准表示。所以你必须自己提供一个表示器,如果你用一个标记来表示它,如果你为那个标记提供了一个构造函数,你就可以加载回结果表示。
但是,为
numpy.array
创建一个表示器是不够的,因为std
和mean
都不是该类型,因为您已经通过提供的类型信息表明了自己。您必须为numpy.ndarray
和numpy.float64
(用于std
的元素和numpy.int
(用于mean的元素))提供表示器一旦你这样做,你可以转储
std
和mean
。其给出:
ruamel.yaml
的默认往返加载器,可以加载结果文件:其给出:
正如你所看到的,这并没有将文件加载为
numpy.ndarray
。为此,你需要为标记提供一个构造函数(因为我们不转储标记的floats/int,所以你不需要为它们提供构造函数):其给出:
请注意,上述方法不适用于(间接)递归转储,因为
construct_numpy_array
没有yield
语句。最好做一些类似的事情:但这并没有给予相同的结果(因为我对numpy不熟悉)。