用最小二乘法拟合 ax+b 的a值,代表斜率,
- 如果abs(a) > 0.1763 (这是tan10度,相当于一个阈值,如果拟合的曲线仰角超过10度,就证明有倾向)
示例代码
import numpy as np
def trendline(data):
"""拟合后用斜率判断
"""
index = [i for i in range(1, len(data) + 1)]
coeffs = np.polyfit(index, list(data), 1)
slope = coeffs[-2]
if slope > 0.1763: # 0.1763是 tan10°
return "increasing"
elif slope < -0.1763:
return "decreasing"
else:
return "no trend"
if __name__ == '__main__':
data = np.array([1, 2, 3, 4, 3, 5, 5, 7, 4, 7, ])
print(trendline(data))