i have code with timeseries model using GluonTS for preparing data and timeseriestransformers for model
Установка необходимых зависимостей
import pandas as pd
import numpy as np
from evaluate import load
from gluonts.transform import InstanceSplitter
from sklearn.metrics import mean_absolute_error, mean_squared_error
from transformers import TimeSeriesTransformerConfig, TimeSeriesTransformerForPrediction
from datasets import Dataset, DatasetDict
from torch.optim import AdamW
from typing import Iterable
from gluonts.itertools import Cyclic, Cached
from gluonts.dataset.loader import as_stacked_batches
from gluonts.transform.sampler import InstanceSampler
from typing import Optional
from accelerate import Accelerator
from tqdm.auto import tqdm
from evaluate import load
from gluonts.time_feature import get_seasonality
import torch
import psutil
import tensorflow as tf
import os
import mlflow
import matplotlib.pyplot as plt
from functools import lru_cache
from functools import partial
from itertools import islice
from transformers import PretrainedConfig
import matplotlib.pyplot as plt
from scipy.signal import savgol_filter
from matplotlib.backends.backend_pdf import PdfPages
from gluonts.time_feature import get_lags_for_frequency
from gluonts.time_feature import time_features_from_frequency_str
from gluonts.torch.distributions import GammaOutput
Проверка ресурсов
torch.cuda.is_available()
!nvidia-smi
#Сколько памяти в системе всего сейчас доступно
total_memory_bytes = psutil.virtual_memory().free
total_memory_gb = total_memory_bytes / (1024 * 1024 * 1024)
print(f"Free memory: {total_memory_gb:.2f} GB")
Загрузка датасетов
#Тренировочная выборка
path_uni = '//teconpc.local/ta/ТеконАвтоматизация/!ПРОЕКТЫ/СМД/Предиктивная диагностика/Файлы для сотрудников/!Отчеты Пронин И.С/1_Исследование методов улучшения качества прогноза (трансформеры)/Сигналы/07MAA10CT001/Train_Uni.xlsx'
path_uni = './signals/07MAA10CT001/Train_Multi (+Lables).xlsx'
path1_uni = os.path.normpath(path_uni)
df = pd.read_excel(path1_uni).iloc[:,:]
#Тестовая выборка (!!!Только один сигнал 07MAA10CT001)
path_test = '//teconpc.local/ta/ТеконАвтоматизация/!ПРОЕКТЫ/СМД/Предиктивная диагностика/Файлы для сотрудников/!Отчеты Пронин И.С/1_Исследование методов улучшения качества прогноза (трансформеры)/Сигналы/07MAA10CT001/Test_Anomaly.xlsx'
path_test = './signals/07MAA10CT001/Test_Anomaly.xlsx'
path1_test = os.path.normpath(path_test)
df_test = pd.read_excel(path1_test).iloc[:,:]
Рабочая папка для моделей и графиков
work_model_path = '//teconpc.local/ta/ТеконАвтоматизация/!ПРОЕКТЫ/СМД/Предиктивная диагностика/Файлы для сотрудников/!Отчеты Пронин И.С/1_Исследование методов улучшения качества прогноза (трансформеры)/models'
work_plots_path = '//teconpc.local/ta/ТеконАвтоматизация/!ПРОЕКТЫ/СМД/Предиктивная диагностика/Файлы для сотрудников/!Отчеты Пронин И.С/1_Исследование методов улучшения качества прогноза (трансформеры)/plots'
# в случае мультивариативности добавляем настройки на количество фичей:
num_target_features=n,
target_indices=[0],
include_target_feature=True,
)
model = TimeSeriesTransformerForPrediction(config)
дефолтное распределение которое строит модель и на основании которого считается ошибка
model.config.distribution_output
#зависимости для трансформации данных
from gluonts.time_feature import (
time_features_from_frequency_str,
TimeFeature,
get_lags_for_frequency,
)
from gluonts.dataset.field_names import FieldName
from gluonts.transform import (
AddAgeFeature,
AddObservedValuesIndicator,
AddTimeFeatures,
AsNumpyArray,
Chain,
ExpectedNumInstanceSampler,
InstanceSplitter,
RemoveFields,
SelectFields,
SetField,
TestSplitSampler,
Transformation,
ValidationSplitSampler,
VstackFeatures,
RenameFields,
)
Трансформация данных под конфиг модели
def create_transformation(freq: str, config: PretrainedConfig) -> Transformation:
remove_field_names = []
if config.num_static_real_features == 0:
remove_field_names.append(FieldName.FEAT_STATIC_REAL)
if config.num_dynamic_real_features == 0:
remove_field_names.append(FieldName.FEAT_DYNAMIC_REAL)
if config.num_static_categorical_features == 0:
remove_field_names.append(FieldName.FEAT_STATIC_CAT)
test_dataloader = create_test_dataloader(
config=config,
freq=time_freq,
data=test_dataset,
batch_size=batch_size,
)
Инициализация акселератора, перенос модели на GPU
#Инициализация cuda, перенос модели на GPU
model.train()
for epoch in tqdm(range(num_epoch)):
for idx, batch in enumerate(train_dataloader):
optimizer.zero_grad()
outputs = model(
static_categorical_features=batch["static_categorical_features"].to(device)
if config.num_static_categorical_features > 0
else None,
static_real_features=batch["static_real_features"].to(device)
if config.num_static_real_features > 0
else None,
past_time_features=batch["past_time_features"].to(device),
past_values=batch["past_values"].to(device),
future_time_features=batch["future_time_features"].to(device),
future_values=batch["future_values"].to(device),
past_observed_mask=batch["past_observed_mask"].to(device),
future_observed_mask=batch["future_observed_mask"].to(device),
)
loss = outputs.loss
accelerator.backward(loss)
optimizer.step()
if idx % 100 == 0:
print(f"Epoch {epoch + 1}, Step {idx + 1}, Loss: {loss.item()}")
val_loss_rmse = evaluate(model, val_dataloader, accelerator, num_val_batches)
if val_loss_rmse < best_val_loss - early_stopping.min_delta:
best_val_loss = val_loss_rmse
best_model_path = os.path.join(os.getcwd(), model_path)
torch.save(model.state_dict(), best_model_path)
print(f"Epoch {epoch + 1}, Validation RMSE Loss: {val_loss_rmse}")
mlflow.log_metric("Loss -LNN", loss, step=epoch)
mlflow.log_metric("Val_loss RMSE", val_loss_rmse, step=epoch)
scheduler.step(val_loss_rmse)
early_stopping.step(val_loss_rmse)
if early_stopping.early_stop:
print("Сработали условия ранней остановы")
break
if best_model_path:
model.load_state_dict(torch.load(best_model_path))
print(f"Веса лучшей модели восстановлены: {best_model_path}")
else:
print("Нет лучшей сохраненной модели")
mlflow.log_artifact(model_path)
mlflow.end_run()
model
model_path = f'{work_model_path}/probability_model_rev_3_2'
model.load_state_dict(torch.load(model_path))
Оценка модели, формирование стака прогнозов, визуализация
EVALUATION = True
#Оценка модели с количеством батчей с начала датасета
if EVALUATION:
model.eval()
forecasts = []
count = 0
for batch in tqdm(test_dataloader):
outputs = model.generate(
static_categorical_features=batch["static_categorical_features"].to(device)
if config.num_static_categorical_features > 0
else None,
static_real_features=batch["static_real_features"].to(device)
if config.num_static_real_features > 0
else None,
past_time_features=batch["past_time_features"].to(device),
past_values=batch["past_values"].to(device),
future_time_features=batch["future_time_features"].to(device),
past_observed_mask=batch["past_observed_mask"].to(device),
)
forecasts.append(outputs.sequences.cpu().numpy())
count += 1
if count >= 40:
break
forecasts = np.vstack(forecasts)
forecast_mean = np.mean(forecasts, axis=1)
print(f'Размерность матрицы с прогнозами: {forecasts.shape}')
#Расчет MASE
def compute_mase(y_true, y_pred, y_train, seasonality=1):
n = len(y_train)
d = np.abs(np.diff(y_train, n=seasonality)).sum() / (n - seasonality)
errors = np.abs(y_true - y_pred)
return errors.mean() / d
forecast_mean = np.mean(forecasts, 1)
Расчет через самописную функцию
seasonality = 1
mase_metrics_1 = []
for item_id, ts in tqdm(enumerate(test_dataset)):
training_data = np.array(ts['target'][:-prediction_length*2])
ground_truth = np.array(ts['target'][-prediction_length:])
mase_metric = compute_mase(ground_truth, forecast_mean[item_id], training_data, seasonality=seasonality)
mase_metrics_1.append(mase_metric)
print(f'Метрика MASE (самописная) на тестовой выборке: {np.mean(mase_metrics_1)}')
plt.legend()
fig.autofmt_xdate()
start_time = index[-2 * prediction_length]
end_time = index[-1]
plt.title(f"График отображает вывод за период с {start_time} до {end_time}")
plt.show()
return fig
#Загружаем альбом результатов тестов в MLflow
try:
mlflow.set_tracking_uri("http://od-eto:5002/")
runs = mlflow.search_runs(experiment_ids = experiment_id, order_by=["start_time desc"], max_results=1)
mlflow.start_run(run_id = runs['run_id'][0])
except Exception as e:
print(f'Run уже запущен {e}')
plot_path = f'{work_plots_path}/График для {run_name} на тестовой выборке.pdf'
plot_path = os.path.join(os.getcwd(), plot_path)
with PdfPages(plot_path) as pdf:
for i in range(0, forecasts.shape[0]):
fig = plot(i)
pdf.savefig(fig, bbox_inches='tight')
plt.close(fig)
mlflow.log_artifact(plot_path)
mlflow.end_run()
for i in range(0, forecasts.shape[0]):
plot(i)
Expand class from transformers import TimeSeriesTransformerConfig, TimeSeriesTransformerForPrediction to Custom class which will be able to use Gamma distribution as output, after check train, eval and test proccess and apapt it to new model
To enable your TimeSeriesTransformerForPrediction model to use a Gamma distribution as its output, you need to extend the existing functionality within the transformers library. Here's a step-by-step guide on how to do this:
1. Implementing a Custom Gamma Distribution Class
Firstly, you need to define a Gamma distribution output. GluonTS already has a Gamma distribution class, so one approach is to wrap this existing distribution in your transformers models.
You need to extend the TimeSeriesTransformerConfig class to support the Gamma distribution output.
from transformers import PretrainedConfig
class CustomTimeSeriesTransformerConfig(TimeSeriesTransformerConfig):
def __init__(self, distribution_output='gamma', **kwargs):
super().__init__(**kwargs)
self.distribution_output = distribution_output
3. Extend the TimeSeriesTransformerForPrediction Class
You need to extend the TimeSeriesTransformerForPrediction class to use the new Gamma distribution. In this custom model, modify the forward method to incorporate your custom distribution.
from transformers import TimeSeriesTransformerForPrediction
class CustomTimeSeriesTransformerForPrediction(TimeSeriesTransformerForPrediction):
def __init__(self, config: CustomTimeSeriesTransformerConfig):
super().__init__(config)
if config.distribution_output == 'gamma':
self.distribution_output = GammaOutput()
def forward(self, **batch):
out = super().forward(**batch)
if self.config.distribution_output == 'gamma':
distr_args = self.distribution_output.domain_map(
out.distr_args[:, :, 0], out.distr_args[:, :, 1]
)
out.distr = self.distribution_output.distribution(distr_args)
return out
4. Update Training, Evaluation, and Testing Process
You need to adapt your training, evaluation, and testing pipelines to use the custom model and configuration.
Update Model Initialization
config = CustomTimeSeriesTransformerConfig(
prediction_length=prediction_length,
context_length=context_length,
lags_sequence=lags_sequence,
num_time_features=len(time_features) + 1,
num_static_categorical_features=1,
cardinality=[2],
embedding_dimension=[2],
distribution_output='gamma', # Updated to use Gamma distribution
encoder_layers=4,
decoder_layers=4,
d_model=32,
)
model = CustomTimeSeriesTransformerForPrediction(config)
Update Training Step
No changes are necessary in the training step as your custom model already incorporates the required changes.
Evaluate and Test Process
Again, no changes are necessary in the evaluation and test process unless you have custom evaluation metrics specifically tailored for the Gamma distribution.
Final Code
Here is the complete updated model initialization and training loop utilizing the CustomTimeSeriesTransformerForPrediction with the Gamma distribution:
# Custom Configuration
config = CustomTimeSeriesTransformerConfig(
prediction_length=prediction_length,
context_length=context_length,
lags_sequence=lags_sequence,
num_time_features=len(time_features) + 1,
num_static_categorical_features=1,
cardinality=[2],
embedding_dimension=[2],
distribution_output='gamma', # Updated with Gamma distribution
encoder_layers=4,
decoder_layers=4,
d_model=32,
)
# Custom Model
model = CustomTimeSeriesTransformerForPrediction(config)
model.to(device)
# Optimizer
optimizer = AdamW(model.parameters(), lr=1e-4, betas=(0.9, 0.98), weight_decay=1e-2)
accelerator = Accelerator()
model, optimizer, train_dataloader = accelerator.prepare(
model,
optimizer,
train_dataloader,
)
early_stopping = CustomEarlyStoppingCallback(patience=10, min_delta=1e-4, verbose=True)
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, 'min', patience=5, factor=0.5)
# Training Loop
num_epoch = 50
with mlflow.start_run(experiment_id=experiment_id, run_name=run_name):
mlflow.log_param("num_epoch", num_epoch)
mlflow.log_param("batch_size", batch_size)
mlflow.log_param("model_architecture", str(model))
model.train()
for epoch in tqdm(range(num_epoch)):
for idx, batch in enumerate(train_dataloader):
optimizer.zero_grad()
outputs = model(
static_categorical_features=batch["static_categorical_features"].to(device)
if config.num_static_categorical_features > 0
else None,
static_real_features=batch["static_real_features"].to(device)
if config.num_static_real_features > 0
else None,
past_time_features=batch["past_time_features"].to(device),
past_values=batch["past_values"].to(device),
future_time_features=batch["future_time_features"].to(device),
future_values=batch["future_values"].to(device),
past_observed_mask=batch["past_observed_mask"].to(device),
future_observed_mask=batch["future_observed_mask"].to(device),
)
loss = outputs.loss
accelerator.backward(loss)
optimizer.step()
if idx % 100 == 0:
print(f"Epoch {epoch + 1}, Step {idx + 1}, Loss: {loss.item()}")
val_loss_rmse = evaluate(model, val_dataloader, accelerator, num_val_batches)
if val_loss_rmse < best_val_loss - early_stopping.min_delta:
best_val_loss = val_loss_rmse
best_model_path = os.path.join(os.getcwd(), model_path)
torch.save(model.state_dict(), best_model_path)
print(f"Epoch {epoch + 1}, Validation RMSE Loss: {val_loss_rmse}")
mlflow.log_metric("Loss -LNN", loss, step=epoch)
mlflow.log_metric("Val_loss RMSE", val_loss_rmse, step=epoch)
scheduler.step(val_loss_rmse)
early_stopping.step(val_loss_rmse)
if early_stopping.early_stop:
print("Early stopping triggered")
break
if best_model_path:
model.load_state_dict(torch.load(best_model_path))
print(f"Best model weights restored: {best_model_path}")
else:
print("No best model saved")
mlflow.end_run()
This revised training process ensures your model is based on the Gamma distribution. Both training and evaluation processes are updated to use the custom model with Gamma distribution output.
after adding all to my code
from gluonts.torch import distributions
import torch.distributions as D
class GammaOutput:
args_dim = 2
distr_cls = D.Gamma
The error is raised because the base TimeSeriesTransformerForPrediction class does not recognize "gamma" as a valid distribution output. To handle custom distribution output properly, you need to extend both the configuration and the main transformer model class. In this case, you missed extending the __init__ method properly so that it recognizes the "gamma" distribution output.
Here's how to implement the correct custom class to handle "gamma" distribution:
Step-by-Step Implementation
Custom Gamma Distribution Class
This class seems correct. Ensure it is correctly implemented as follows:
from transformers import TimeSeriesTransformerConfig
class CustomTimeSeriesTransformerConfig(TimeSeriesTransformerConfig):
def __init__(self, distribution_output='gamma', **kwargs):
super().__init__(**kwargs)
self.distribution_output = distribution_output
Custom Transformer Class
Extend the base transformer model to recognize the custom distribution configuration:
from transformers import TimeSeriesTransformerForPrediction
class CustomTimeSeriesTransformerForPrediction(TimeSeriesTransformerForPrediction):
def __init__(self, config: CustomTimeSeriesTransformerConfig):
super().__init__(config)
if config.distribution_output == 'gamma':
self.distribution_output = GammaOutput()
self.parameter_projection = self.distribution_output.get_parameter_projection(self.model.config.d_model)
self.target_shape = self.distribution_output.event_shape
elif config.distribution_output == 'negative_binomial':
self.distribution_output = NegativeBinomialOutput(dim=config.input_size)
self.parameter_projection = self.distribution_output.get_parameter_projection(self.model.config.d_model)
self.target_shape = self.distribution_output.event_shape
else:
raise ValueError(f"Unknown distribution output {config.distribution_output}")
def forward(self, **batch):
out = super().forward(**batch)
if self.config.distribution_output == 'gamma':
distr_args = self.distribution_output.domain_map(
out.distr_args[:, :, 0], out.distr_args[:, :, 1]
)
out.distr = self.distribution_output.distribution(distr_args)
return out
Update Model Initialization
Ensure model initialization and testing:
config = CustomTimeSeriesTransformerConfig(
prediction_length=prediction_length,
context_length=context_length,
lags_sequence=lags_sequence,
num_time_features=len(time_features) + 1,
num_static_categorical_features=1,
cardinality=[2],
embedding_dimension=[2],
distribution_output='gamma', # Updated to use Gamma distribution
encoder_layers=4,
decoder_layers=4,
d_model=32,
)
model = CustomTimeSeriesTransformerForPrediction(config)
model.to(device)
Now, your custom configuration and model classes are correctly set up to recognize and handle the Gamma distribution. This implementation should solve the ValueError you're experiencing. Additionally, remember to include the default distribution in the custom class's __init__ to avoid conflicts with other distribution outputs.
Troubleshooting Checklist
Ensure the GammaOutput class is correctly implemented and imported.
The custom configuration class should have the distribution_output attribute defined and handled in the custom model class.
The custom model class should correctly initialize the custom distribution output as shown above.
Properly pass the custom configuration when initializing your custom model.
By following these steps, you create a complete structure to integrate the Gamma distribution properly.
It looks like the base TimeSeriesTransformerForPrediction class throws an error for unsupported distributions because it doesn't know about your custom gamma distribution. To fix this, we need to ensure that our custom class properly integrates and handles the custom gamma distribution.
Here's the complete implementation to make sure everything is handled correctly:
from transformers import TimeSeriesTransformerConfig
class CustomTimeSeriesTransformerConfig(TimeSeriesTransformerConfig):
def __init__(self, distribution_output='gamma', **kwargs):
super().__init__(**kwargs)
self.distribution_output = distribution_output
Extend the TimeSeriesTransformerForPrediction Class
from transformers import TimeSeriesTransformerForPrediction
class CustomTimeSeriesTransformerForPrediction(TimeSeriesTransformerForPrediction):
def __init__(self, config: CustomTimeSeriesTransformerConfig):
super().__init__(config)
if config.distribution_output == 'gamma':
self.distribution_output = GammaOutput()
self.parameter_projection = self.distribution_output.args_dim * config.d_model
self.target_shape = self.distribution_output.event_shape
elif config.distribution_output == 'negative_binomial':
self.distribution_output = NegativeBinomialOutput(dim=config.input_size)
self.parameter_projection = self.distribution_output.get_parameter_projection(config.d_model)
self.target_shape = self.distribution_output.event_shape
else:
raise ValueError(f"Unknown distribution output {config.distribution_output}")
def forward(self, **batch):
out = super().forward(**batch)
if self.config.distribution_output == 'gamma':
distr_args = self.distribution_output.domain_map(
out.distr_args[:, :, 0].squeeze(-1),
out.distr_args[:, :, 1].squeeze(-1)
)
out.distr = self.distribution_output.distribution(distr_args)
return out
Model Initialization
config = CustomTimeSeriesTransformerConfig(
prediction_length=prediction_length,
context_length=context_length,
lags_sequence=lags_sequence,
num_time_features=len(time_features) + 1,
num_static_categorical_features=1,
cardinality=[2],
embedding_dimension=[2],
distribution_output='gamma', # Use Gamma distribution
encoder_layers=4,
decoder_layers=4,
d_model=32,
)
model = CustomTimeSeriesTransformerForPrediction(config)
model.to(device)
Complete Flow
Now, the complete flow should look like this:
Define Gamma Distribution Output Class
No changes needed as above.
Extend Configuration Class
No changes needed as above.
Extend TimeSeriesTransformerForPrediction Class
Ensure your class checks for the gamma distribution and initializes the correct attributes.
Initialize the model
Make sure the model is initialized with CustomTimeSeriesTransformerConfig.
Here’s a complete version wrapped for execution:
from gluonts.torch.model.predictor import PyTorchPredictor
import torch.nn.functional as F
from transformers import TimeSeriesTransformerConfig, TimeSeriesTransformerForPrediction
# Define GammaOutput Distribution
class GammaOutput:
args_dim = 2
distr_cls = torch.distributions.Gamma
@staticmethod
def domain_map(concentration: torch.Tensor, rate: torch.Tensor):
concentration = F.softplus(concentration) + 1e-8
rate = F.softplus(rate) + 1e-8
return concentration, rate
def distribution(self, args, scale=None, **kwargs):
concentration, rate = args
return self.distr_cls(concentration, rate)
@property
def event_shape(self):
return ()
# Extend Custom Configuration
class CustomTimeSeriesTransformerConfig(TimeSeriesTransformerConfig):
def __init__(self, distribution_output='gamma', **kwargs):
super().__init__(**kwargs)
self.distribution_output = distribution_output
# Extend Custom TimeSeries Transformer
class CustomTimeSeriesTransformerForPrediction(TimeSeriesTransformerForPrediction):
def __init__(self, config: CustomTimeSeriesTransformerConfig):
super().__init__(config)
if config.distribution_output == 'gamma':
self.distribution_output = GammaOutput()
self.parameter_projection = torch.nn.Linear(self.model.config.d_model, self.distribution_output.args_dim)
self.target_shape = self.distribution_output.event_shape
elif config.distribution_output == 'negative_binomial':
self.distribution_output = NegativeBinomialOutput(dim=config.input_size)
self.parameter_projection = self.distribution_output.get_parameter_projection(config.d_model)
self.target_shape = self.distribution_output.event_shape
else:
raise ValueError(f"Unknown distribution output {config.distribution_output}")
def forward(self, **batch):
out = super().forward(**batch)
if self.config.distribution_output == 'gamma':
distr_args = self.distribution_output.domain_map(
out.distr_args[:, :, 0], out.distr_args[:, :, 1]
)
out.distr = self.distribution_output.distribution(distr_args)
return out
# Initialize Custom Config and Model
config = CustomTimeSeriesTransformerConfig(
prediction_length=prediction_length,
context_length=context_length,
lags_sequence=lags_sequence,
num_time_features=len(time_features) + 1,
num_static_categorical_features=1,
cardinality=[2],
embedding_dimension=[2],
distribution_output='gamma', # Use Gamma distribution
encoder_layers=4,
decoder_layers=4,
d_model=32,
)
model = CustomTimeSeriesTransformerForPrediction(config)
model.to(device)
Testing the Implementation
Now, run the code above and ensure it properly initializes the model, preventing the ValueError.
If you follow these steps closely, it will extend the transformer model to handle gamma distribution output correctly. This ensures your custom configuration and model integration work seamlessly with your existing training and evaluation pipeline.
Yes, if you have a binary categorical feature for your static categorical features (i.e., the feature can take only two possible values: 0 and 1), you should set cardinality=[2].
The cardinality parameter represents the number of unique values (or categories) that each categorical feature can take. For a binary categorical feature, this corresponds to two possible values, hence cardinality=[2].
Here's what each parameter signifies in this context:
cardinality: This is a list where each entry corresponds to the number of unique values that each categorical feature can take. Since you only have one binary categorical feature, this list should contain a single value, which is 2.
embedding_dimension: This list defines the dimensionality of the embedding space for each categorical feature. This allows the model to learn dense representations for these categorical values. Even though the feature is binary, you can choose an appropriate dimensionality based on your model complexity and dataset size.
config = CustomTimeSeriesTransformerConfig(
prediction_length=prediction_length,
context_length=context_length,
lags_sequence=lags_sequence,
num_time_features=len(time_features) + 1, # includes the hour and day_of_week features
num_static_categorical_features=1, # since you have one binary categorical feature
cardinality=[2], # since it's a binary feature (can take 2 unique values: 0 or 1)
embedding_dimension=[2], # number of dimensions for the embedding of the binary feature
distribution_output='gamma', # specifying the output distribution
encoder_layers=4,
decoder_layers=4,
d_model=32,
)
Full Pipeline Initialization Example
With the context provided, here's how you initialize the configuration and the model including the binary categorical feature:
# Custom Configuration
config = CustomTimeSeriesTransformerConfig(
prediction_length=prediction_length,
context_length=context_length,
lags_sequence=lags_sequence,
num_time_features=len(time_features) + 1, # includes the hour and day_of_week features
num_static_categorical_features=1, # since you have one binary categorical feature
cardinality=[2], # since it's a binary feature (can take 2 unique values: 0 or 1)
embedding_dimension=[2], # number of dimensions for the embedding of the binary feature
distribution_output='gamma', # specifying the output distribution
encoder_layers=4,
decoder_layers=4,
d_model=32,
)
# Custom Model
model = CustomTimeSeriesTransformerForPrediction(config)
model.to(device)
This setup ensures that your single binary categorical feature is properly handled in the model configuration and during training.
Selecting the dimension of embeddings (embedding dimension) for categorical features is an essential part of configuring your model, and it often depends on several factors like the size of the dataset, the number of unique categories, and the complexity of the problem. Here are a few guidelines to help you choose:
Guidelines for Embedding Dimensions
Binary Features (Two Categories - 0 and 1):
For binary categorical features, an embedding dimension of 2 is common. This allows representation in a 2-dimensional space, which is usually sufficient for such a simple categorical input.
Heuristic Approaches:
A common rule of thumb is to use the embedding dimension around the fourth root of the cardinality or dimensions incrementally up to the cardinality itself but typically not beyond.
**Embedding Dimension = min(50, (Number of categories)0.25):
For example, if cardinality = 100, the embedding dimension would be min(50, 100**0.25) ≈ 3.
Empirical Tuning:
Ultimately, the best embedding dimension is often determined through empirical tuning based on the performance on your validation set.
For Your Case
Given you have a binary categorical feature, the number of unique values (cardinality) is 2. Therefore, a dimension of 2 is usually adequate but you can experiment with lower dimensions like 1 and 3 depending on your dataset size and model complexity.
Application
For your case with cardinality = [2]:
An embedding dimension of 2 is reasonable.
Here's how you should configure it in code:
config = CustomTimeSeriesTransformerConfig(
prediction_length=prediction_length,
context_length=context_length,
lags_sequence=lags_sequence,
num_time_features=len(time_features) + 1, # includes the hour and day_of_week features
num_static_categorical_features=1, # since you have one binary categorical feature
cardinality=[2], # since it's a binary feature (can take 2 unique values: 0 or 1)
embedding_dimension=[2], # number of dimensions for the embedding of the binary feature
distribution_output='gamma', # specifying the output distribution
encoder_layers=4,
decoder_layers=4,
d_model=32,
)
This setup is expected to work well, and you can always experiment with embedding dimensions like 1 or 3 to see if it provides better performance for your specific problem. Here’s the complete initialization for clarity:
Full Initialization Example
# Define GammaOutput Distribution
class GammaOutput:
args_dim = 2
distr_cls = torch.distributions.Gamma
@staticmethod
def domain_map(concentration: torch.Tensor, rate: torch.Tensor):
concentration = torch.nn.functional.softplus(concentration) + 1e-8
rate = torch.nn.functional.softplus(rate) + 1e-8
return concentration, rate
def distribution(self, args, scale=None, **kwargs):
concentration, rate = args
return self.distr_cls(concentration, rate)
@property
def event_shape(self):
return ()
# Extend Custom Configuration
class CustomTimeSeriesTransformerConfig(TimeSeriesTransformerConfig):
def __init__(self, distribution_output='gamma', **kwargs):
super().__init__(**kwargs)
self.distribution_output = distribution_output
# Extend Custom TimeSeries Transformer
class CustomTimeSeriesTransformerForPrediction(TimeSeriesTransformerForPrediction):
def __init__(self, config: CustomTimeSeriesTransformerConfig):
super().__init__(config)
if config.distribution_output == 'gamma':
self.distribution_output = GammaOutput()
self.parameter_projection = torch.nn.Linear(self.model.config.d_model, self.distribution_output.args_dim)
self.target_shape = self.distribution_output.event_shape
elif config.distribution_output == 'negative_binomial':
self.distribution_output = NegativeBinomialOutput(dim=config.input_size)
self.parameter_projection = self.distribution_output.get_parameter_projection(config.d_model)
self.target_shape = self.distribution_output.event_shape
else:
raise ValueError(f"Unknown distribution output {config.distribution_output}")
def forward(self, **batch):
out = super().forward(**batch)
if self.config.distribution_output == 'gamma':
distr_args = self.distribution_output.domain_map(
out.distr_args[:, :, 0], out.distr_args[:, :, 1]
)
out.distr = self.distribution_output.distribution(distr_args)
return out
# Initialize Custom Config and Model
config = CustomTimeSeriesTransformerConfig(
prediction_length=prediction_length,
context_length=context_length,
lags_sequence=lags_sequence,
num_time_features=len(time_features) + 1, # includes the hour and day_of_week features
num_static_categorical_features=1, # since you have one binary categorical feature
cardinality=[2], # since it's a binary feature (can take 2 unique values: 0 or 1)
embedding_dimension=[2], # number of dimensions for the embedding of the binary feature
distribution_output='gamma', # Use Gamma distribution
encoder_layers=4,
decoder_layers=4,
d_model=32,
)
model = CustomTimeSeriesTransformerForPrediction(config)
model.to(device)
By following this setup, you should have the correct configuration for handling your binary categorical feature effectively.