一系列的分段线性函数

2024-03-28 23:42:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一系列的“成本斜率”,代表一个线性函数f,以痛苦的形式给出。下面是一个小得多的例子:

slopes = Series({'-inf': 10, -200: 60, 0: 0, 200: 1, 'inf': 10})

-inf    10
-200    60
0        0
200      1
inf     10

(0,0)始终在序列中,斜率表示从零向任意方向移动时的分段“边际成本”

f(-200) = 12000  # abs(-200) * 60
f(-100) = 6000  # abs(-100) * 60
f(0) = 0
f(100) = 100  # 100 * 1
f(200) = 200  # 200 * 1
f(300) = 1200  # 200 * 1 + (300-200) * 10

由于这个系列很大,而且被多次调用,我希望能将其转换为一种形式,在这种形式下,我可以使用Numpy的interppiecewise或Pandasinterpolate来提高速度,而不是构建for循环

我认为^{}可能是解决方案,但我不确定如何转换和处理inf?也许有更干净的方法


Tags: 函数代表序列线性abs方向形式例子
2条回答
import math
slopes = pd.Series({ -math.inf: 10, -200: 60, 0: 0, 200: 1, 300: 10, math.inf: 10})

根据需要定义成本函数

def cost_func(x):
    if x[0] < 200:
        return abs(x[0]) * x[1]
    else: 
        return 200 + abs(x[0]-200) * x[1]

slope_df = pd.DataFrame({'value':slopes.index, 'amount':slopes.values}, index = range(slopes.size))

slope_df['cost'] = slope_df[ ['value', 'amount'] ].apply(lambda row: cost_func(row), axis=1)
print(slope_df)

slope_df output

通过选择使用np.piecewise,您只需将成本斜率间隔指定为condlist,并将相应的线性函数表达式指定为funclist,如:

import numpy as np
import matplotlib.pyplot as plt

x = np.array([-200,-100,0,100,200,300])

condlist = [x<-200,\
            np.logical_and(x>=-200, x<0),\
            x==0,\
            np.logical_and(x>0,x<=200),\
            x>200]
funclist = [lambda x: 200*60+abs(x+200)*10,\
            lambda x: abs(x)*60,\
            lambda x:0,\
            lambda x: abs(x)*1,\
            lambda x: 200*1+abs(x-200)*10]

f = np.piecewise(x,condlist,funclist)

使用给定点验证实现的正确性,如下所示:

np.allclose([12000,6000,0,100,200,1200],f)
>>> True

它在更大范围内绘制,比如说x = np.linspace(-500,500,2000),最后给出:

plt.plot(x, f,'r')
plt.scatter([-200,-100,0,100,200,300],[12000,6000,0,100,200,1200],s=20,zorder=5)

piecewise_output

希望这有帮助

相关问题 更多 >