numpy.piecewise中的多个碎片

时间:2013-10-24 22:53:51

标签: python numpy plot piecewise

我正在学习模糊系统课程,我在计算机上学习my notes。这意味着我必须不时在我的计算机上绘制图形。由于这些图表定义得很好,我觉得用numpy绘制它们是一个好主意(我用LaTeX做笔记,我在python shell上很快,所以我想我可以得到离开这个)。

fuzzy membership functions的图表非常分段,例如:

Fuzzy Membership Function

为了绘制这个,我尝试了以下代码numpy.piecewise(这给了我一个神秘的错误):

In [295]: a = np.arange(0,5,1)

In [296]: condlist = [[b<=a<b+0.25, b+0.25<=a<b+0.75, b+0.75<=a<b+1] for b in range(3)]
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-296-a951e2682357> in <module>()
----> 1 condlist = [[b<=a<b+0.25, b+0.25<=a<b+0.75, b+0.75<=a<b+1] for b in range(3)]

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

In [297]: funclist = list(itertools.chain([lambda x:-4*x+1, lambda x: 0, lambda x:4*x+1]*3))

In [298]: np.piecewise(a, condlist, funclist)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-298-41168765ae55> in <module>()
----> 1 np.piecewise(a, condlist, funclist)

/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/numpy/lib/function_base.pyc in piecewise(x, condlist, funclist, *args, **kw)
    688     if (n != n2):
    689         raise ValueError(
--> 690                 "function list and condition list must be the same")
    691     zerod = False
    692     # This is a hack to work around problems with NumPy's

ValueError: function list and condition list must be the same

此时,我对如何绘制此功能感到相当困惑。我不太了解错误信息,这进一步阻碍了我调试此操作的努力。

最终,我希望将此功能绘制并导出到EPS文件中,所以我也很感激这些方面的帮助。

1 个答案:

答案 0 :(得分:9)

一般来说,numpy数组非常善于做出明智的事情,只需编写代码就好像它们只是数字一样。链式比较是极少数例外情况之一。您所看到的错误基本上就是这种错误(piecewise内部混淆和ipython错误格式化):

>>> a = np.array([1, 2, 3])
>>> 1.5 < a
array([False,  True,  True], dtype=bool)
>>> 
>>> 1.5 < a < 2.5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> 
>>> (1.5 < a) & (a < 2.5)
array([False,  True, False], dtype=bool)
>>> 

您也可以使用np.logical_and,但按位and可以正常使用。

就绘图而言,numpy本身并没有做任何事情。这是matplotlib的一个例子:

>>> import numpy as np
>>> def piecew(x):
...   conds = [x < 0, (x > 0) & (x < 1), (x > 1) & (x < 2), x > 2]
...   funcs = [lambda x: x+1, lambda x: 1, 
...            lambda x: -x + 2., lambda x: (x-2)**2]
...   return np.piecewise(x, conds, funcs)
>>>
>>> import matplotlib.pyplot as plt
>>> xx = np.linspace(-0.5, 3.1, 100)
>>> plt.plot(xx, piecew(xx))
>>> plt.show() # or plt.savefig('foo.eps')

请注意piecewise是一只反复无常的野兽。特别是,它需要x参数作为一个数组,如果不是,则不会尝试转换它(用numpy说法:x需要是{{ 1}},而不是ndarray):

array_like