我有一组基于NumPy的数值例程,并且能够轻松处理符号元素是一件好事(但不是主要用例)。在代码中有一些实例对于了解NumPy数组是否包含符号元素非常有用。
问题:测试NumPy数组是否包含符号元素的最快方法是什么。
一种看似快速的方法依赖于以下事实:如果存在任何符号元素,则dtype
会变为object
而不是数字类型。但是,可以想象它可以是其他类型对象的数组,而不是符号对象。我认为数组在包含的对象中可以是异构的(只是引用指针),因此除了迭代所有元素之外,没有简便的方法来测试数组包含的对象类型。
答案 0 :(得分:0)
在isympy
会话中(以前用于sympy
SO问题):
In [317]: type(y)
Out[317]: sympy.core.symbol.Symbol
In [318]: np.array([1,2,y])
Out[318]: array([1, 2, y], dtype=object)
In [319]: np.sum(_)
Out[319]: y + 3
In [320]: type(_)
Out[320]: sympy.core.add.Add
因此symbol
的存在会产生一个sympy
对象。
使用其他sympy
对象:
In [321]: type(x)
Out[321]: sympy.core.function.UndefinedFunction
In [322]: np.sum(np.array([1,2,x]))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-322-1782e9d730ec> in <module>
----> 1 np.sum(np.array([1,2,x]))
<__array_function__ internals> in sum(*args, **kwargs)
/usr/local/lib/python3.6/dist-packages/numpy/core/fromnumeric.py in sum(a, axis, dtype, out, keepdims, initial, where)
2240
2241 return _wrapreduction(a, np.add, 'sum', axis, dtype, out, keepdims=keepdims,
-> 2242 initial=initial, where=where)
2243
2244
/usr/local/lib/python3.6/dist-packages/numpy/core/fromnumeric.py in _wrapreduction(obj, ufunc, method, axis, dtype, out, **kwargs)
85 return reduction(axis=axis, out=out, **passkwargs)
86
---> 87 return ufunc.reduce(obj, axis, dtype, out, **passkwargs)
88
89
TypeError: unsupported operand type(s) for +: 'int' and 'UndefinedFunction'
一个例子,说明如何将符号弄乱先验,这是没人能实现的方法。
In [323]: np.exp([1,2,3])
Out[323]: array([ 2.71828183, 7.3890561 , 20.08553692])
In [324]: np.exp([1,2,y])
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
AttributeError: 'int' object has no attribute 'exp'
The above exception was the direct cause of the following exception:
TypeError Traceback (most recent call last)
<ipython-input-324-b2dfa5af3395> in <module>
----> 1 np.exp([1,2,y])
TypeError: loop of ufunc does not support argument 0 of type int which has no callable exp method
None
是公共对象dtype元素;那会弄乱这些。 list
元素通常会因数学而失败-除了少数情况下,+
或*
的定义和使用是正确的。
找到sympy
会搞乱numpy
操作的方法可能比确定一组清晰的工作要容易得多。