import matplotlib.pyplot as plt
import pandas as pd
plt.rcParams['font.sans-serif'] = 'SimHei' # 設(shè)置中文顯示
plt.rcParams['axes.unicode_minus'] = False
data = pd.read_csv('基于KNN臨近填補缺失值', index_col=0, parse_dates=['數(shù)據(jù)時間'])
print(data.shape)
data.head()

數(shù)據(jù)集為2018-01-01 00:00:00到2021-08-31 23:45:00某地區(qū)電網(wǎng)間隔15分鐘的負荷數(shù)據(jù)(數(shù)據(jù)完整不存在缺失)

plt.figure(figsize=(15,4 ), dpi =300)
plt.grid(True)
plt.plot(data['總有功功率(kw)'], label = '間隔15min數(shù)據(jù)')
plt.title('間隔15min功率圖')
plt.xlabel('時間')
plt.ylabel('總有功功率(kw)')
plt.legend()
plt.show()
# 把數(shù)據(jù)化為每天的均值數(shù)據(jù)
data_dmean = data.resample('D').mean()
data_dmean
plt.figure(figsize=(15,4 ), dpi =300)
plt.grid(True)
plt.plot(data_dmean['總有功功率(kw)'], label = '間隔15min數(shù)據(jù)')
plt.title('每天均值功率圖')
plt.xlabel('時間')
plt.ylabel('總有功功率(kw)')
plt.legend()
plt.show()
from fbprophet import Prophet
def FB(datal, column):
df = pd.DataFrame({
'ds':pd.Series(datal.iloc[:,column].index),
'y':pd.Series(datal.iloc[:,column].values)
})
df['cap'] = data.iloc[:,column].max()
df['floor'] = datal.iloc[:,column].min()

m = Prophet(
changepoint_prior_scale = 0.2,
daily_seasonality = False,
yearly_seasonality = True, #年周期性
weekly_seasonality = True, #周周期性
growth = 'linear',
interval_width = 0.8, #置信區(qū)間寬度,有多大概率落在淺藍色線里
)

m.add_country_holidays(country_name = 'CN') # 中國所有節(jié)假日

m.fit(df)

future = m.make_future_dataframe(periods = 10) # 往后預(yù)測多少
future['cap'] = datal.iloc[:,column].max()
future['floor'] = datal.iloc[:, column].min()

forecast = m.predict(future)

fig1 = m.plot(forecast)
fig2 = m.plot_components(forecast)

return future, forecast

使用Facebook Prophet庫進行時間序列預(yù)測的Python代碼。FB 函數(shù)接受一個數(shù)據(jù)框(datal)和一個列索引(column)作為輸入,對數(shù)據(jù)進行預(yù)處理,擬合Prophet模型,然后對未來時間段進行預(yù)測

參數(shù)含義
changepoint_prior_scale控制變更點的靈活性,值越大,趨勢的靈活性越高
daily_seasonality是否包含每日季節(jié)性,如果為’True’,則考慮每天的季節(jié)性波動
yearly_seasonality是否包含每年季節(jié)性,如果為’True’,則考慮每年的季節(jié)性波動
weekly_seasonality是否包含每周季節(jié)性,如果為’True’,則考慮每周的季節(jié)性波動
growth指定趨勢的增長類型,可以是’linear’或’logistic’
interval_width置信區(qū)間的寬度,用于可視化時顯示預(yù)測的不確定性
holidays指定節(jié)假日的日期??梢允菙?shù)據(jù)框或’pd.DataFrame’類型,包含節(jié)假日的日期和相關(guān)信息
add_country_holidays添加指定國家的所有公共假日
seasonality_prior_scale控制季節(jié)性的靈活性。值越大,季節(jié)性的靈活性越高

這只是其中一些參數(shù),Prophet 還有其他可調(diào)整的參數(shù),具體可以查閱 Prophet 文檔 獲取詳細信息

future, forecast = FB(data_dmean, 0)
plt.figure(figsize=(15,4 ), dpi =300)
plt.grid(True)
plt.plot(data_dmean, color = 'c', label = '日平均功率曲線')
plt.plot(forecast.ds, forecast.yhat, label='預(yù)測曲線')
plt.title('實際日平均功率與預(yù)測日平均功率對比圖')
plt.xlabel('時間')
plt.ylabel('總有功功率(kw)')
plt.legend()
plt.show()
plt.figure(figsize=(15,4 ), dpi =300)
plt.grid(True)
plt.plot(data_dmean[-100:], color = 'c', label = '日平均功率曲線')
plt.plot(forecast.ds[-100-10:], forecast.yhat[-100-10:], label='預(yù)測曲線')
plt.title('實際日平均功率與預(yù)測日平均功率對比圖')
plt.xlabel('時間')
plt.ylabel('總有功功率(kw)')
plt.legend()
plt.show()
from sklearn import metrics
mse = metrics.mean_squared_error(data_dmean.values, np.expand_dims(forecast.yhat.iloc[0:1339].values,axis=1)) # MSE 均方誤差
rmse = np.sqrt(mse) # 均方 根誤差RMSE
mae = metrics.mean_absolute_error(data_dmean.values, np.expand_dims(forecast.yhat.iloc[0:1339].values,axis=1)) # MAE 平均絕對誤差
def mape(y_true, y_pred):
return np.mean(np.abs((y_pred - y_true) / y_true)) * 100
mape = mape(data_dmean.values, np.expand_dims(forecast.yhat.iloc[0:1339].values,axis=1)) # MAPE 平均絕對百分比誤差
print(mse)
print(rmse)
print(mae)
print(mape)
from sklearn.metrics import r2_score # 擬合優(yōu)度
r2_score(data_dmean.values, np.expand_dims(forecast.yhat.iloc[0:1339].values,axis=1))

本文章轉(zhuǎn)載微信公眾號@Python機器學(xué)習(xí)AI

上一篇:

統(tǒng)計檢驗——方差檢驗(ANOVA)分析變量間的顯著性差異

下一篇:

統(tǒng)計檢驗——卡方檢驗分析分類變量間的顯著性差異

我們有何不同?

API服務(wù)商零注冊

多API并行試用

數(shù)據(jù)驅(qū)動選型,提升決策效率

查看全部API→
??

熱門場景實測,選對API

#AI文本生成大模型API

對比大模型API的內(nèi)容創(chuàng)意新穎性、情感共鳴力、商業(yè)轉(zhuǎn)化潛力

25個渠道
一鍵對比試用API 限時免費

#AI深度推理大模型API

對比大模型API的邏輯推理準確性、分析深度、可視化建議合理性

10個渠道
一鍵對比試用API 限時免費