PyTorch-Forecasting一個(gè)新的時(shí)間序列預(yù)測庫
時(shí)間序列預(yù)測在金融、天氣預(yù)報(bào)、銷售預(yù)測和需求預(yù)測等各個(gè)領(lǐng)域發(fā)揮著至關(guān)重要的作用。PyTorch- forecasting是一個(gè)建立在PyTorch之上的開源Python包,專門用于簡化和增強(qiáng)時(shí)間序列的工作。在本文中我們介紹PyTorch-Forecasting的特性和功能,并進(jìn)行示例代碼演示。
PyTorch-Forecasting的安裝非常簡單:
pip install pytorch-forecasting
但是需要注意的是,他目前現(xiàn)在只支持Pytorch 1.7以上,但是2.0是否支持我沒有測試。
PyTorch-Forecasting提供了幾個(gè)方面的功能:
1、提供了一個(gè)高級(jí)接口,抽象了時(shí)間序列建模的復(fù)雜性,可以使用幾行代碼來定義預(yù)測任務(wù),使得使用不同的模型和技術(shù)進(jìn)行實(shí)驗(yàn)變得容易。
2、支持多個(gè)預(yù)測模型,包括自回歸模型(AR, ARIMA),狀態(tài)空間模型(SARIMAX),神經(jīng)網(wǎng)絡(luò)(LSTM, GRU)和集成方法(Prophet, N-Beats)。這種多樣化的模型集確保了為您的時(shí)間序列數(shù)據(jù)選擇最合適方法的靈活性。
3、提供各種數(shù)據(jù)預(yù)處理工具來處理常見的時(shí)間序列任務(wù),包括:缺失值輸入、縮放、特征提取和滾動(dòng)窗口轉(zhuǎn)換等。除了一些數(shù)據(jù)的預(yù)處理的工具外,還提供了一個(gè)名為 TimeSeriesDataSet 的Pytorch的DS,這樣可以方便的處理時(shí)間序列數(shù)據(jù)。
4、通過統(tǒng)一的接口方便模評(píng)估:實(shí)現(xiàn)了QuantileLoss,SMAPE 等時(shí)間序列的損失函數(shù)和驗(yàn)證指標(biāo),支持Pytorch Lighting 這樣可以直接使用早停和交叉驗(yàn)證等訓(xùn)練方法
使用方法也很簡單:
from pytorch_forecasting import TimeSeriesDataSet, TemporalFusionTransformer
# Load and preprocess the data
dataset = TimeSeriesDataSet.from_csv('data.csv', target='target', time_idx='time', group_ids=['id'])
dataset.prepare_training(split_into_train_val_test=[0.8, 0.1, 0.1])
# Initialize and train the model
model = TemporalFusionTransformer.from_dataset(dataset)
trainer = pl.Trainer()
trainer.fit(model, dataset.train_dataloader())
# Generate predictions
predictions = model.predict(dataset.test_dataloader())
# Evaluate the model
metric = dataset.target_normalizer.metrics['mse']
print(f'Test MSE: {metric(predictions, dataset.test_dataloader())}')
如果需要分類編碼,可以這樣用:
from pytorch_forecasting.data import GroupNormalizer
# Load and preprocess the data with categorical variables
dataset = TimeSeriesDataSet.from_pandas(data, target='target', time_idx='time', group_ids=['id'],
categorical_encoders={'cat_variable': GroupNormalizer()})
dataset.prepare_training(...)
# Initialize and train the model
model = TemporalFusionTransformer.from_dataset(dataset)
trainer.fit(model, dataset.train_dataloader())
# Generate predictions
predictions = model.predict(dataset.test_dataloader())
# Evaluate the model
print(f'Test MSE: {metric(predictions, dataset.test_dataloader())}')
PyTorch-Forecasting是一個(gè)非常好用的工具包,就算你不使用它所有的功能,也可以將他提供的一些功能當(dāng)作鞏工具來整合到自己的項(xiàng)目中,如果你對(duì)使用PyTorch處理時(shí)序數(shù)據(jù)感興趣,也可以看看他的代碼當(dāng)作學(xué)習(xí)的參考,他的文檔還是比較全面的,并且也提供了很多的示例。
有興趣的看看官方的文檔和代碼示例:
https://pytorch-forecasting.readthedocs.io/en/stable/index.html