Pytorch Forecasting은 최첨단 딥 러닝 아키텍처를 사용하여 Pytorch 기반 패키지입니다. 고급 API를 제공하고 Pytorch Lightning을 사용하여 자동 로깅과 함께 GPU 또는 CPU에 대한 교육을 확장합니다.
| 문서 · 튜토리얼 · 릴리스 노트 | |
|---|---|
| 오픈 소스 | |
| 지역 사회 | |
| CI/CD | |
| 암호 |
Data Science에 대한 우리의 기사는 패키지를 소개하고 배경 정보를 제공합니다.
Pytorch 예측은 실제 사례 및 연구를 위해 신경망으로 최첨단 시대의 예측을 완화하는 것을 목표로합니다. 목표는 전문가에게 최대한의 유연성과 초보자에게 합리적인 기본값을 제공하는 고급 API를 제공하는 것입니다. 구체적으로 패키지는 제공합니다
이 패키지는 Pytorch-Lightning을 기반으로 CPU, 단일 및 다중 GPU에 대한 교육을 제공 할 수 있습니다.
Windows에서 작업하는 경우 먼저 Pytorch를 설치해야합니다.
pip install torch -f https://download.pytorch.org/whl/torch_stable.html .
그렇지 않으면 진행할 수 있습니다
pip install pytorch-forecasting
또는 Conda를 통해 패키지를 설치할 수 있습니다
conda install pytorch-forecasting pytorch -c pytorch>=1.7 -c conda-forge
Pytorch는 이제 Conda-Forge 채널에서 설치되는 동안 Pytorch는 Pytorch 채널에서 설치됩니다.
MQF2 손실 (다변량 Quantile Loss)을 사용하려면 pip install pytorch-forecasting[mqf2] 설치하십시오.
https://pytorch-forecasting.readthedocs.io를 방문하여 자세한 자습서가있는 문서를 읽으십시오.
문서는 사용 가능한 모델을 비교합니다.
새로운 모델 또는 기타 사용자 정의 구성 요소를 구현하려면 새로운 모델 구현 방법 자습서를 참조하십시오. 기본 및 고급 아키텍처를 다룹니다.
네트워크는 Pandas Dataframes에서 Pytorch Lighning 트레이너와 함께 처음 TimeseriesDataset으로 변환 될 수 있습니다.
# imports for training
import lightning . pytorch as pl
from lightning . pytorch . loggers import TensorBoardLogger
from lightning . pytorch . callbacks import EarlyStopping , LearningRateMonitor
# import dataset, network to train and metric to optimize
from pytorch_forecasting import TimeSeriesDataSet , TemporalFusionTransformer , QuantileLoss
from lightning . pytorch . tuner import Tuner
# load data: this is pandas dataframe with at least a column for
# * the target (what you want to predict)
# * the timeseries ID (which should be a unique string to identify each timeseries)
# * the time of the observation (which should be a monotonically increasing integer)
data = ...
# define the dataset, i.e. add metadata to pandas dataframe for the model to understand it
max_encoder_length = 36
max_prediction_length = 6
training_cutoff = "YYYY-MM-DD" # day for cutoff
training = TimeSeriesDataSet (
data [ lambda x : x . date <= training_cutoff ],
time_idx = ..., # column name of time of observation
target = ..., # column name of target to predict
group_ids = [ ... ], # column name(s) for timeseries IDs
max_encoder_length = max_encoder_length , # how much history to use
max_prediction_length = max_prediction_length , # how far to predict into future
# covariates static for a timeseries ID
static_categoricals = [ ... ],
static_reals = [ ... ],
# covariates known and unknown in the future to inform prediction
time_varying_known_categoricals = [ ... ],
time_varying_known_reals = [ ... ],
time_varying_unknown_categoricals = [ ... ],
time_varying_unknown_reals = [ ... ],
)
# create validation dataset using the same normalization techniques as for the training dataset
validation = TimeSeriesDataSet . from_dataset ( training , data , min_prediction_idx = training . index . time . max () + 1 , stop_randomization = True )
# convert datasets to dataloaders for training
batch_size = 128
train_dataloader = training . to_dataloader ( train = True , batch_size = batch_size , num_workers = 2 )
val_dataloader = validation . to_dataloader ( train = False , batch_size = batch_size , num_workers = 2 )
# create PyTorch Lighning Trainer with early stopping
early_stop_callback = EarlyStopping ( monitor = "val_loss" , min_delta = 1e-4 , patience = 1 , verbose = False , mode = "min" )
lr_logger = LearningRateMonitor ()
trainer = pl . Trainer (
max_epochs = 100 ,
accelerator = "auto" , # run on CPU, if on multiple GPUs, use strategy="ddp"
gradient_clip_val = 0.1 ,
limit_train_batches = 30 , # 30 batches per epoch
callbacks = [ lr_logger , early_stop_callback ],
logger = TensorBoardLogger ( "lightning_logs" )
)
# define network to train - the architecture is mostly inferred from the dataset, so that only a few hyperparameters have to be set by the user
tft = TemporalFusionTransformer . from_dataset (
# dataset
training ,
# architecture hyperparameters
hidden_size = 32 ,
attention_head_size = 1 ,
dropout = 0.1 ,
hidden_continuous_size = 16 ,
# loss metric to optimize
loss = QuantileLoss (),
# logging frequency
log_interval = 2 ,
# optimizer parameters
learning_rate = 0.03 ,
reduce_on_plateau_patience = 4
)
print ( f"Number of parameters in network: { tft . size () / 1e3 :.1f } k" )
# find the optimal learning rate
res = Tuner ( trainer ). lr_find (
tft , train_dataloaders = train_dataloader , val_dataloaders = val_dataloader , early_stop_threshold = 1000.0 , max_lr = 0.3 ,
)
# and plot the result - always visually confirm that the suggested learning rate makes sense
print ( f"suggested learning rate: { res . suggestion () } " )
fig = res . plot ( show = True , suggest = True )
fig . show ()
# fit the model on the data - redefine the model with the correct learning rate if necessary
trainer . fit (
tft , train_dataloaders = train_dataloader , val_dataloaders = val_dataloader ,
)