有没有办法平滑点之间的线,使每个点的梯度为 0?

Is there a way to smooth a line between points such that the gradient at each point is 0?

有没有办法平滑点之间的这条线,使每个点的线梯度为 0(就好像点之间有一个三次函数,每个数据点作为一个转折点)。

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

x = [1,2,3,4,5,6,7,8,9,10]
y = [8,2,1,7,5,5,8,1,9,5]

ax.plot(x,y)

'Unsmoothed'剧情:

我不确定用例是否合意,但您可以使用样条插值 scipy.interpolate.CubicSpline:

import numpy as np
from scipy.interpolate import CubicSpline

cs = CubicSpline(x, y)
xs = np.linspace(min(x), max(x), num=100)

fig, ax = plt.subplots()
ax.plot(x, y, label='data', marker='o')
ax.plot(xs, cs(xs), label='spline')
ax.legend()

输出:

选择:CubicHermiteSpline

import numpy as np
from scipy.interpolate import CubicHermiteSpline

cs = CubicHermiteSpline(x, y, np.zeros(len(x))) # force gradient to zero
xs = np.linspace(min(x), max(x), num=100)

fig, ax = plt.subplots()
ax.plot(x, y, label='data', marker='o')
ax.plot(xs, cs(xs), label='spline')
ax.legend()

有阈值(仅用于“漂亮”显示目的)
import numpy as np
from scipy.interpolate import CubicHermiteSpline

g = np.gradient(y)/np.gradient(x)
g = np.where(abs(g)>2, g, 0)

cs = CubicHermiteSpline(x, y, g)

xs = np.linspace(min(x), max(x), num=100)

fig, ax = plt.subplots()
ax.plot(x, y, label='data', marker='o')
ax.plot(xs, cs(xs), label='spline')
ax.legend()

输出: