栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

numpy.piecewise中的多个部分

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

numpy.piecewise中的多个部分

通常,当您仅将代码编写为数字时,numpy数组非常擅长做明智的事情。链接比较是罕见的例外之一。您看到的错误本质上是这样的(

piecewise
内部和ipython错误格式对此进行了混淆):

>>> a = np.array([1, 2, 3])>>> 1.5 < aarray([False,  True,  True], dtype=bool)>>> >>> 1.5 < a < 2.5Traceback (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
需要为
ndarray
,而不是
array_like
):

>>> piecew(2.1)Traceback (most recent call last):  File "<stdin>", line 1, in <module>  File "<stdin>", line 4, in piecew  File "/home/br/.local/lib/python2.7/site-packages/numpy/lib/function_base.py", line 690, in piecewise    "function list and condition list must be the same")ValueError: function list and condition list must be the same>>> >>> piecew(np.asarray([2.1]))array([ 0.01])


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/659874.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号