取梯度的平均值并不是确定数据趋势的可靠方法。如果您将数据绘制成图表,则有明显的上升趋势,并且正如您所指出的,对于第二种情况,梯度的平均值将为负。使用下面的示例,我们可以绘制数据、查看趋势和梯度的可变性。
您可以看到,使用趋势线是确定数据是增加还是减少的更可靠的方法,因为趋势线实际上代表了您的数据。另一方面,梯度放大了亚趋势尺度的可变性,现在包括将抵消平均值的正数和负数。
import numpy as np
from matplotlib import peplos as plt
#Define the example data
n1=np.array([6.2, 5.0, 6.6, 5.7, 8.3, 8.5, 7.9, 6.7, 8.0, 8.3, 8.6, 8.3])
n2=np.array([13.8, 10.4, 9.4, 12.4, 12.8, 10.9, 11.0, 11.0, 11.7, 14.5, 13.8, 14.2])
#arbitrary time dimension, assume fixed delta
tim = np.arange(0,len(n1))
#get linear trend lines
m1, b1 = np.polyfit(tim, n1, 1)
m2, b2 = np.polyfit(tim, n2, 1)
fig=plt.figure(figsize=(12,6))
ax1=plt.subplot(121)
ax1.plot(tim,n1,c='C0',lw=2,label='n1')
ax1.plot(tim,n2,c='C1',lw=2,label='n2')
ax1.plot(tim,m1*tim+b1,ls='dotted',c='C0',lw=2,label='n1 slope=%1.2f'%m1)
ax1.plot(tim,m2*tim+b2,ls='dotted',c='C1',lw=2,label='n2 slope=%1.2f'%m2)
ax1.legend()
ax2=plt.subplot(122)
ax2.plot(tim,np.gradient(n1),c='C0',lw=2,label='n1 gradient mean=%1.2f'%np.mean(np.gradient(n1)))
ax2.plot(tim,np.gradient(n2),c='C1',lw=2,label='n2 gradient mean=%1.2f'%np.mean(np.gradient(n2)))
ax2.axhline(0,c='black')
ax2.legend()
plt.show()