[英]Numpy piecewise of arbitrary length
I need to build a piecewise function with an arbitrary number of intervals and functions, able to operate on a numpy array of inputs. 我需要构建一个具有任意数量的间隔和函数的分段函数,该函数可以对输入的numpy数组进行操作。
I can do it with a for loop and indicator arrays, as exemplified in the snippet of code below, but is there is a more pythonic way to do it? 我可以使用for循环和指标数组来做到这一点,如下面的代码片段所示,但是还有更多的Python方式可以做到这一点吗?
I tried to use numpy.piecewise but, as far as I can tell, the number of segments and functions needs to be statically defined in the source code. 我尝试使用numpy.piecewise,但据我所知,段和函数的数量需要在源代码中静态定义。
import numpy as np
import matplotlib.pyplot as plt
# inputs:
# -xs: points in which to compute the piecewise function
# -segments: the extremes of the piecewise intervals (as a list)
# -funcs: the functions (as a list; len(funcs)==len(segments)-1 )
def calc_piecewise(xs, segments, funcs):
# prepare indicators and results arrays
indaseg = np.zeros(len(xs), np.bool)
ys = np.zeros_like(xs)
# loop through intervals and compute the ys
for ii in range(len(funcs)):
indaseg = np.logical_and(xs>=segments[ii], xs<=segments[ii+1])
ys[indaseg] = funcs[ii](xs[indaseg])
return ys
def test_calc_piecewise():
segments = [0.0, 1.0, 2.5, 4.0, 5.0]
def f0(xs):
return xs
def f1(xs):
return xs*xs
def f2(xs):
return 12.5-xs*xs
def f3(xs):
return 4.0*xs-19.5
funcs = [f0, f1, f2, f3]
xs = np.linspace(0.0, 5.0, 500)
ys = calc_piecewise(xs, segments, funcs)
plt.figure()
title = "calc_piecewise"
plt.title(title)
plt.plot(xs, ys, 'r-')
plt.show()
return
test_calc_piecewise()
You can do it with np.piecewise
as follows (apologies for formatting!): 您可以按如下方式使用
np.piecewise
(为格式化np.piecewise
抱歉!):
ys = np.piecewise(
xs,
[(xs >= segments[i]) & (xs <= segments[i+1]) for i in range(len(segments)-1)],
funcs)
The results are the same. 结果是一样的。
Essentially your loop and the test equivalent to your line indaseg = np.logical_and(xs>=segments[ii], xs<=segments[ii+1])
is moved into the calling code. 本质上,您的循环和等效于
indaseg = np.logical_and(xs>=segments[ii], xs<=segments[ii+1])
被移到调用代码中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.