fis*_*000 6 python validation numpy introspection typechecking
我想针对给定NumPy dtype所暗示的约束来测试未知值- 例如,如果我有一个整数值,它是否足够小以适应uint8?
我可以确定,NumPy的dtype架构并没有提供这样的方法:
### FICTIONAL NUMPY CODE: I made this up ###
try:
numpy.uint8.validate(rupees)
except numpy.dtype.ValidationError:
print "Users can't hold more than 255 rupees."
Run Code Online (Sandbox Code Playgroud)
我的小幻想API基于Django的模型字段验证器,但这仅仅是一个例子 - 我设法设计的最佳机制就是这样:
>>> nd = numpy.array([0,0,0,0,0,0], dtype=numpy.dtype('uint8'))
>>> nd[0]
0
>>> nd[0] = 1
>>> nd[0] = -1
>>> nd
array([255, 0, 0, 0, 0, 0], dtype=uint8)
>>> nd[0] = 257
>>> nd
array([1, 0, 0, 0, 0, 0], dtype=uint8)
Run Code Online (Sandbox Code Playgroud)
通过numpy.ndarray类型化显式numpy.uint8回滚可疑值会使我返回已经包装到具有适当大小的内容的整数 - 不会抛出异常,或者引发任何其他类型的可操作错误状态.
当然,我宁愿不穿建筑宇航员飞行服,但这更可取的选择,看起来像是不可维护的意大利面 - 怪物混乱的if dtype(this) ... elif dtype(that)陈述.除了开始编写我自己的API的宏伟和放纵行为之外,我还能做些什么吗?
如果a是您的原始可迭代,您可以执行以下操作:
np.all(np.array(a, dtype=np.int8) == a)
Run Code Online (Sandbox Code Playgroud)
很简单,这会将结果ndarray与原始值进行比较,并告诉您转换是否为ndarray无损.
这也将捕获诸如使用太窄而不能完全表示某些值的浮点类型之类的事情:
>>> a = [0, 0, 0, 0, 0, 0.123456789]
>>> np.all(np.array(a, dtype=np.float32) == a)
False
>>> np.all(np.array(a, dtype=np.float64) == a)
True
Run Code Online (Sandbox Code Playgroud)
编辑:使用带浮点数的上述代码时,一个警告是NaN总是比较不相等.如果需要,扩展代码以处理该情况也是微不足道的.