钳位函数为clamp(x, min, max) = min if x < min, max if x > max, else x
我需要一个行为类似于钳位函数但平滑的函数(即具有连续导数)。
最佳答案
您正在寻找的类似于Smoothstep函数,该函数具有一个免费参数N
,给出了“平滑度”,即应连续导数个数。它的定义如下:
这在几个库中使用,可以在numpy中实现为
import numpy as np
from scipy.special import comb
def smoothstep(x, x_min=0, x_max=1, N=1):
x = np.clip((x - x_min) / (x_max - x_min), 0, 1)
result = 0
for n in range(0, N + 1):
result += comb(N + n, n) * comb(2 * N + 1, N - n) * (-x) ** n
result *= x ** (N + 1)
return result
给定
N=0
(可微分0倍),它将简化为常规钳位函数,并随着N的增加而增加平滑度。您可以像这样可视化它:import matplotlib.pyplot as plt
x = np.linspace(-0.5, 1.5, 1000)
for N in range(0, 5):
y = smoothstep(x, N=N)
plt.plot(x, y, label=str(N))
plt.legend()
得到以下结果: