gpt4 book ai didi

python - 任意长度的 Numpy 分段

转载 作者:行者123 更新时间:2023-12-01 05:24:06 34 4
gpt4 key购买 nike

我需要构建一个具有任意数量的间隔和函数的分段函数,能够对输入的 numpy 数组进行操作。

我可以使用 for 循环和指示符数组来做到这一点,如下面的代码片段所示,但是有没有一种更 Pythonic 的方法来做到这一点?

我尝试使用 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()

最佳答案

您可以使用np.piecewise来做到这一点如下(抱歉格式错误!):

ys = np.piecewise(
xs,
[(xs >= segments[i]) & (xs <= segments[i+1]) for i in range(len(segments)-1)],
funcs)

结果是一样的。

本质上你的循环和测试相当于你的行 indaseg = np.logical_and(xs>=segments[ii], xs<=segments[ii+1])被移动到调用代码中。

关于python - 任意长度的 Numpy 分段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21725464/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com