gluonts.mx#

class gluonts.mx.DistributionOutput#

Class to construct a distribution given the output of a network.

distr_cls: type#
distribution(distr_args, loc: Optional[Union[mxnet.ndarray.ndarray.NDArray, mxnet.symbol.symbol.Symbol]] = None, scale: Optional[Union[mxnet.ndarray.ndarray.NDArray, mxnet.symbol.symbol.Symbol]] = None) gluonts.mx.distribution.Distribution#

Construct the associated distribution, given the collection of constructor arguments and, optionally, a scale tensor.

Parameters
  • distr_args – Constructor arguments for the underlying Distribution type.

  • loc – Optional tensor, of the same shape as the batch_shape+event_shape of the resulting distribution.

  • scale – Optional tensor, of the same shape as the batch_shape+event_shape of the resulting distribution.

domain_map(F, *args: Union[mxnet.ndarray.ndarray.NDArray, mxnet.symbol.symbol.Symbol])#

Converts arguments to the right shape and domain. The domain depends on the type of distribution, while the correct shape is obtained by reshaping the trailing axis in such a way that the returned tensors define a distribution of the right event_shape.

property event_dim: int#

Number of event dimensions, i.e., length of the event_shape tuple, of the distributions that this object constructs.

property event_shape: Tuple#

Shape of each individual event contemplated by the distributions that this object constructs.

property value_in_support: float#

A float that will have a valid numeric value when computing the log-loss of the corresponding distribution. By default 0.0. This value will be used when padding data series.

class gluonts.mx.GluonEstimator#

An Estimator type with utilities for creating Gluon-based models.

To extend this class, one needs to implement three methods: create_transformation, create_training_network, create_predictor, create_training_data_loader, and create_validation_data_loader.

create_predictor(transformation: Transformation, trained_network: mxnet.gluon.block.HybridBlock) gluonts.model.predictor.Predictor#

Create and return a predictor object.

Parameters
  • transformation – Transformation to be applied to data before it goes into the model.

  • module – A trained HybridBlock object.

Returns

A predictor wrapping a HybridBlock used for inference.

Return type

Predictor

create_training_data_loader(data: Dataset, **kwargs) Iterable[Dict[str, Any]]#

Create a data loader for training purposes.

Parameters

data – Dataset from which to create the data loader.

Returns

The data loader, i.e. and iterable over batches of data.

Return type

DataLoader

create_training_network() mxnet.gluon.block.HybridBlock#

Create and return the network used for training (i.e., computing the loss).

Returns

The network that computes the loss given input data.

Return type

HybridBlock

create_transformation() Transformation#

Create and return the transformation needed for training and inference.

Returns

The transformation that will be applied entry-wise to datasets, at training and inference time.

Return type

Transformation

create_validation_data_loader(data: Dataset, **kwargs) Iterable[Dict[str, Any]]#

Create a data loader for validation purposes.

Parameters

data – Dataset from which to create the data loader.

Returns

The data loader, i.e. and iterable over batches of data.

Return type

DataLoader

classmethod from_hyperparameters(**hyperparameters) GluonEstimator#
lead_time: int#
prediction_length: int#
train(training_data: Dataset, validation_data: Optional[Dataset] = None, shuffle_buffer_length: Optional[int] = None, cache_data: bool = False, **kwargs) gluonts.model.predictor.Predictor#

Train the estimator on the given data.

Parameters
  • training_data – Dataset to train the model on.

  • validation_data – Dataset to validate the model on during training.

Returns

The predictor containing the trained model.

Return type

Predictor

train_model(training_data: Dataset, validation_data: Optional[Dataset] = None, shuffle_buffer_length: Optional[int] = None, cache_data: bool = False) gluonts.mx.model.estimator.TrainOutput#
class gluonts.mx.GluonPredictor(input_names: List[str], prediction_net: mxnet.gluon.block.Block, batch_size: int, prediction_length: int, ctx: mxnet.context.Context, input_transform: Transformation, lead_time: int = 0, forecast_generator: gluonts.model.forecast_generator.ForecastGenerator = SampleForecastGenerator(), output_transform: Optional[Callable[[Dict[str, Any], numpy.ndarray], numpy.ndarray]] = None, dtype: Type = np.float32)#

Base predictor type for Gluon-based models.

Parameters
  • input_names – Input tensor names for the graph

  • prediction_net – Network that will be called for prediction

  • batch_size – Number of time series to predict in a single batch

  • prediction_length – Number of time steps to predict

  • input_transform – Input transformation pipeline

  • output_transform – Output transformation

  • ctx – MXNet context to use for computation

  • forecast_generator – Class to generate forecasts from network outputs

BlockType#

alias of mxnet.gluon.block.Block

as_symbol_block_predictor(batch: Optional[Dict[str, Any]] = None, dataset: Optional[Dataset] = None) gluonts.mx.model.predictor.SymbolBlockPredictor#

Returns a variant of the current GluonPredictor backed by a Gluon SymbolBlock. If the current predictor is already a SymbolBlockPredictor, it just returns itself.

One of batch or datset must be set.

Parameters
  • batch – A batch of data to use for the required forward pass after the hybridize() call of the underlying network.

  • dataset – Dataset from which a batch is extracted if batch is not set.

Returns

A predictor derived from the current one backed by a SymbolBlock.

Return type

SymbolBlockPredictor

hybridize(batch: Dict[str, Any]) None#

Hybridizes the underlying prediction network.

Parameters

batch – A batch of data to use for the required forward pass after the hybridize() call.

predict(dataset: Dataset, num_samples: Optional[int] = None, num_workers: Optional[int] = None, num_prefetch: Optional[int] = None, **kwargs) Iterator[gluonts.model.forecast.Forecast]#

Compute forecasts for the time series in the provided dataset. This method is not implemented in this abstract class; please use one of the subclasses. :param dataset: The dataset containing the time series to predict.

Returns

Iterator over the forecasts, in the same order as the dataset iterable was provided.

Return type

Iterator[Forecast]

serialize(path: pathlib.Path) None#
serialize_prediction_net(path: pathlib.Path) None#
class gluonts.mx.RepresentableBlockPredictor(prediction_net: mxnet.gluon.block.HybridBlock, batch_size: int, prediction_length: int, ctx: mxnet.context.Context, input_transform: Transformation, lead_time: int = 0, forecast_generator: gluonts.model.forecast_generator.ForecastGenerator = SampleForecastGenerator(), output_transform: Optional[Callable[[Dict[str, Any], numpy.ndarray], numpy.ndarray]] = None, dtype: Type = np.float32)#

A predictor which serializes the network structure using the JSON- serialization methods located in gluonts.core.serde. Use the following logic to create a RepresentableBlockPredictor from a trained prediction network.

>>> def create_representable_block_predictor(
...        prediction_network: mx.gluon.HybridBlock,
...        **kwargs
... ) -> RepresentableBlockPredictor:
...    return RepresentableBlockPredictor(
...        prediction_net=prediction_network,
...        **kwargs
...    )
BlockType#

alias of mxnet.gluon.block.HybridBlock

as_symbol_block_predictor(batch: Optional[Dict[str, Any]] = None, dataset: Optional[Dataset] = None) gluonts.mx.model.predictor.SymbolBlockPredictor#

Returns a variant of the current GluonPredictor backed by a Gluon SymbolBlock. If the current predictor is already a SymbolBlockPredictor, it just returns itself.

One of batch or datset must be set.

Parameters
  • batch – A batch of data to use for the required forward pass after the hybridize() call of the underlying network.

  • dataset – Dataset from which a batch is extracted if batch is not set.

Returns

A predictor derived from the current one backed by a SymbolBlock.

Return type

SymbolBlockPredictor

classmethod deserialize(path: pathlib.Path, ctx: Optional[mxnet.context.Context] = None) RepresentableBlockPredictor#

Load a serialized predictor from the given path.

Parameters
  • path – Path to the serialized files predictor.

  • **kwargs – Optional context/device parameter to be used with the predictor. If nothing is passed will use the GPU if available and CPU otherwise.

serialize(path: pathlib.Path) None#
serialize_prediction_net(path: pathlib.Path) None#
class gluonts.mx.Trainer(ctx: Optional[mxnet.context.Context] = None, epochs: int = 100, batch_size: Optional[int] = None, num_batches_per_epoch: int = 50, learning_rate: float = 0.001, learning_rate_decay_factor: float = 0.5, patience: int = 10, minimum_learning_rate: float = 5e-05, clip_gradient: float = 10.0, weight_decay: float = 1e-08, init: Union[str, mxnet.initializer.Initializer] = 'xavier', hybridize: bool = True, callbacks: Optional[List[gluonts.mx.trainer.callback.Callback]] = None, add_default_callbacks: bool = True)#

A trainer specifies how a network is going to be trained.

A trainer is mainly defined by two sets of parameters. The first one determines the number of examples that the network will be trained on (epochs, num_batches_per_epoch), while the second one specifies how the gradient updates are performed (learning_rate, learning_rate_decay_factor, patience, minimum_learning_rate, clip_gradient and weight_decay).

Parameters
  • ctx

  • epochs – Number of epochs that the network will train (default: 100).

  • num_batches_per_epoch – Number of batches at each epoch (default: 50).

  • learning_rate – Initial learning rate (default: \(10^{-3}\)).

  • learning_rate_decay_factor – Factor (between 0 and 1) by which to decrease the learning rate (default: 0.5).

  • patience – The patience to observe before reducing the learning rate, nonnegative integer (default: 10).

  • minimum_learning_rate – Lower bound for the learning rate (default: \(5\cdot 10^{-5}\)).

  • clip_gradient – Maximum value of gradient. The gradient is clipped if it is too large (default: 10).

  • weight_decay – The weight decay (or L2 regularization) coefficient. Modifies objective by adding a penalty for having large weights (default \(10^{-8}\)).

  • init – Initializer of the weights of the network (default: “xavier”).

  • hybridize – If set to True the network will be hybridized before training

  • callbacks – A list of gluonts.mx.trainer.callback.Callback to control the training.

  • add_default_callbacks – bool, True by default. If True, LearningRateReduction and ModelAveragingCallbacks are used in addition to the callbacks specified in the callbacks argument. Make sure that you only set this to true if you don’t specify one of the default callbacks yourself or there will be “duplicate callbacks”. default callbacks: >>> callbacks = [ … ModelAveraging(avg_strategy=SelectNBestMean(num_models=1)), … LearningRateReduction( … base_lr=1e-3, # learning_rate … decay_factor=0.5, # learning_rate_decay_factor … patience=10, # patience … min_lr=5e-5, # minimum_learning_rate … objective=”min”, … ) … ]

count_model_params(net: mxnet.gluon.block.HybridBlock) int#
gluonts.mx.as_in_context(batch: dict, ctx: Optional[mxnet.context.Context] = None) Dict[str, Any]#

Move data into new context, should only be in main process.

gluonts.mx.batchify(data: List[dict], ctx: Optional[mxnet.context.Context] = None, dtype: Optional[Type] = np.float32, variable_length: bool = False, is_right_pad: bool = True) Dict[str, Any]#