代码:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
def Pettitt_change_point_detection(inputdata):
inputdata = np.array(inputdata)
n = inputdata.shape[0]
k = range(n)
inputdataT = pd.Series(inputdata)
r = inputdataT.rank()
Uk = [2*np.sum(r[0:x])-x*(n + 1) for x in k]
Uka = list(np.abs(Uk))
U = np.max(Uka)
K = Uka.index(U)
pvalue = 2 * np.exp((-6 * (U**2))/(n**3 + n**2))
if pvalue <= 0.05:
change_point_desc = '显著'
else:
change_point_desc = '不显著'
#Pettitt_result = {'突变点位置':K,'突变程度':change_point_desc}
return K #,Pettitt_result
dt = [2413.291, 2201.967, 2363.555, 2086.259, 2070.092, 2242.442, 3091.346, 1326.768, 1595.619, 1631.493, 1797.879, 2044.798, 1904.171, 1746.416, 1875.368 ,1826.619, 1853.982, 1887.834, 1802.647 ,1783.050,1925.268, 1777.375, 1970.239 ,1782.715]
plt.plot(dt)
plt.plot([0,5],[np.mean(dt[0:6]),np.mean(dt[0:6])],'m--',color='r')
plt.plot([7,23],[np.mean(dt[7:]),np.mean(dt[7:])],'m--',color='r')
print("Pettitt:",Pettitt_change_point_detection(dt))
结果: