python - 如何使用 Python 检测图形的转折点

标签 python python-3.x

我有一个类似于 x 和 y 值的指数衰减图,并在下图中标记了转折点。我的问题是,无论有没有噪音,我如何使用Python检测转折点的区域或中间点?这些值位于 link 中给出的 csv 文件中.

更新:这是更清晰的图表,显示了转折点/变化点。

enter image description here

最佳答案

解决此问题的一个简单方法是使用 np.gradient 和阈值。

import numpy as np
from matplotlib import pyplot as plt

# generate some toy data
n = 600
t = np.linspace(0, 600, n)
y = (300 * np.exp(-0.1 * t) + 1) + 20 * (np.random.random(n))

# get the gradient
dy = np.gradient(y)

# search gradient for first occurrence of thresh value:
thresh = 0.01
idx_thresh = np.argmax(dy > thresh)
# y[idx_thresh] would be the "turning point"

# visualization
plt.plot(t, y, 'b', label='y')
plt.plot(t, dy, 'g', label='dy')
plt.plot(t[idx_thresh:], y[idx_thresh:], 'r', label=f'y[dy > {thresh}]')
plt.legend()

enter image description here

但是,找到阈值的位置很大程度上取决于噪声!因此,您可能需要进行一些平滑处理,例如

from scipy.signal import savgol_filter

y_filtered = savgol_filter(y, 11, 3)
dy_f = np.gradient(y_filtered)
idx_thresh = np.argmax(dy_f > thresh)

plt.plot(t, y_filtered, 'k', label='y_filtered')
plt.plot(t, dy_f, 'g', label='dy_f')
plt.plot(t[idx_thresh:], y[idx_thresh:], 'r', label=f'y[dy > {thresh}]')
plt.legend()

enter image description here

请注意,渐变现在更加平滑。 重要提示:这取决于哪个过滤器适合的输入数据!

关于python - 如何使用 Python 检测图形的转折点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58856376/

相关文章:

python - 从 flask_ldap3_login 的 current_user.get_id() 中提取 uid 的正确方法?

python - Openpyxl:我们发现一些内容有问题

python - 使用 Tornado 进行并行异步请求时捕获异常

python - 如何将 Pandas 数据框转换为嵌套的 json

python - Pandas 原始数据框已更改

python - 使用 pip3 : ModuleNotFoundError: No module named 'pip._vendor.packaging.__about__' 时出现错误

python - 如何安装 Python 配方文件 (.py)?

python - 处理嵌套字典的最快方法

python - 将列表拆分为总和大致相等的 N 个子列表

python - 当我在 try- except block 中使用该变量时,我在分配之前引用了局部变量