neuralforecast包有很多引入好的时间序列预测算法模型,可以直接通过接口调用。
支持的算法模型有:
__all__ = ['RNN', 'GRU', 'LSTM', 'TCN', 'DeepAR', 'DilatedRNN',
'MLP', 'NHITS', 'NBEATS', 'NBEATSx', 'DLinear', 'NLinear',
'TFT', 'VanillaTransformer', 'Informer', 'Autoformer', 'PatchTST', 'FEDformer',
'StemGNN', 'HINT', 'TimesNet', 'TimeLLM', 'TSMixer', 'TSMixerx', 'MLPMultivariate',
'iTransformer', 'BiTCN', 'TiDE', 'DeepNPTS', 'SOFTS', 'TimeMixer', 'KAN'
]
预测效果:
实现代码:
#%%
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from neuralforecast import NeuralForecast
from neuralforecast.models import NBEATS, NHITS, DLinear, TFT, NLinear, TimesNet, TimeMixer, TSMixerx, iTransformer, DeepNPTS, PatchTST
from neuralforecast.utils import AirPassengersDF
from neuralprophet import NeuralProphet
%matplotlib widget
pd.set_option('display.max_columns', None) # 显示完整的列
pd.set_option('display.max_rows', None) # 显示完整的行
#%%
#处理excel数据,如果时间有缺失的话,插入一条数据,y值取前后两个点的插值
df=pd.read_csv('test1.csv')
df['ds']=pd.to_datetime(df['ds'])
'''df.set_index('ds', inplace=True) # 设置时间戳为索引
resampled_df = df['2024-5-15':'2024-6-5'].resample('1T').interpolate(method='linear').ffill()
#把date移回列
resampled_df.reset_index(drop=False, inplace=True) '''
#%%
#add N-BEATs
#freq,M月,D天,H小时,T分钟,S秒
nf = NeuralForecast(
models = [PatchTST(input_size=24, h=240, max_steps=100)],
freq = 'T',
)
nf.fit(df=df)
result_df=nf.predict()
print(result_df)
#绘图
temp_df=result_df['PatchTST']
_,ax=plt.subplots(figsize=(12,6))
ax.scatter(x=df['ds'],y=df['y'],s=1,c='b')
ax.scatter(x=result_df['ds'], y=temp_df,s=5,c='r')
#把最低和最高绘制成两条曲线,作为fillbetween的输入
ax.fill_between(result_df['ds'],temp_df.min(),temp_df.max(),alpha=0.5,linewidth=0,color='r')
#%%