python - 计算数据框中的斜率
问题描述
这个问题只是关于计算数据帧中每个时间步的斜率。这里有很多额外的细节,欢迎您阅读或不阅读,但这一步就是我正在寻找的。
我有一个预测和一个观察到的数据框。我正在尝试计算预测中的“有趣”变化。
我想尝试通过以下方式实现:
- 计算观测数据的最佳拟合(即线性回归)。
- 找到它的斜率
- 求观察数据的每个时刻的斜率和斜率之间的差异
为此,我需要在时间序列中的每个时刻生成斜率。
- 计算标准差和差值的平均值
- 使用它为预测 DF 中的值生成 z 分数。
如何计算数据中每个点的斜率?
原来的
from sklearn import linear_model
original = series.copy() # the observations
f = y.copy() # the forecast
app = ' app_2'
original.reset_index(inplace=True)
original['date'] = pd.to_timedelta(original['date'] ).dt.total_seconds().astype(int)
# * calculate the best fit of the observed data (ie, linear regression).
reg = linear_model.LinearRegression()
# * find its slope
reg.fit(original['date'].values.reshape(-1, 1), original[app].values)
slope = reg.coef_
# * find the difference between the slope and the slope at each moment of the observed data
delta = original[app].apply(lambda x: abs(slope - SLOPE_OF(x)))
# * calculate the stddev and mean of that difference
odm = delta.mean()
ods = delta.std(ddof=0)
# * use that to generate z-scores for the values in the forecast DF.
# something like
f['test_delta'] = np.cumsum(f[app]).apply(lambda x: abs(slope - x))
f['z'] = f['test_delta'].apply(lambda x: x - odm / ods)
# from that I might find interesting segments of the forecast:
sig = f.index[f['z'] > 2].tolist()
解决方案
要“计算数据中每个点的斜率”,最简单的方法是使用Series.diff()
以下方法计算每个相邻行的“上升超过运行”。结果系列给出(估计)前一行和当前行之间的瞬时变化率(IROC)。
iroc = original[app].diff() / original['date'].diff()
此外,您不需要apply
. 由于 numpy 向量化,scalar - array
其行为符合预期:
delta = slope - iroc
希望这有效。正如 Wen-Ben 评论的那样,查看实际数据和您的预期输出确实会有所帮助。
推荐阅读
- javascript - 为什么 Safari 向服务人员发送两次图像请求?
- cordova - 为什么 cordova build electron --release 创建一个在应用程序屏幕的 2/3 处有调试信息的应用程序?
- arrays - 结构填充是否会影响数组的联合?
- xml - 如何使用 PowerShell 从此 XML 中提取 ErrorCode 和 ErrorDescription?
- vue.js - 自定义组件模糊
- reactjs - 用 props 反应传递的组件并装饰它
- multipart - fastify-multipart 崩溃服务
- azure-functions - 为什么建议禁用健康检查?
- c - 将伪代码转换为 C/C++ 源代码
- firebase - 如何将 Firebase 工具用于非 Google Workspace 的工作邮件