prophet.py
1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
from fbprophet import Prophet
from fbprophet.plot import plot_yearly
import pandas as pd
import matplotlib.pyplot as plt
import time
def detect_anomalies(forecast, new_df):
forecasted = forecast[['trend', 'yhat', 'yhat_lower', 'yhat_upper']].copy()
forecasted['fact'] = new_df['y']
forecasted['ds'] = new_df['ds']
forecasted['anomaly'] = 0
forecasted.loc[forecasted['fact'] > forecasted['yhat_upper'], 'anomaly'] = 1
forecasted.loc[forecasted['fact'] < forecasted['yhat_lower'], 'anomaly'] = 1
forecasted['importance'] = 0
interval_range = forecasted['yhat_upper'] - forecasted['yhat_lower']
forecasted.loc[forecasted['anomaly'] == 1, 'importance'] =\
(forecasted['fact'] - forecasted['yhat_upper']) / interval_range
forecasted.loc[forecasted['anomaly'] == -1, 'importance'] =\
(forecasted['yhat_lower'] - forecasted['fact']) / interval_range
return forecasted
df = pd.read_csv("x_test_prophet.csv")
m = Prophet()
m.add_seasonality(name='50-ly', period=50, fourier_order=10)
m.fit(df)
future = m.make_future_dataframe(periods=1000)
forecast = m.predict(future)
forecast.tail()
# fig = m.plot(forecast)
forecasted = detect_anomalies(forecast, df)
forecasted.to_csv("prophet.csv")
fig = m.plot(forecast)
df_y = pd.read_csv("y_test_prophet.csv")
predict = forecasted['anomaly']
real = df_y['label']
a,b,c,d = 0,0,0,0
for i in range(len(real)):
if predict[i] == 0 and real[i] == 1:
a += 1
if predict[i] == 1 and real[i] == 0:
b += 1
if predict[i] == 0 and real[i] == 0:
c += 1
if predict[i] == 1 and real[i] == 1:
d += 1
print(a,b,c,d)
plt.show()