# PatchTSMixer

## 概述

PatchTSMixer 模型由 Vijay Ekambaram、Arindam Jati、Nam Nguyen、Phanwadee Sinthong 和 Jayant Kalagnanam 在 [TSMixer: Lightweight MLP-Mixer Model for Multivariate Time Series Forecasting](https://huggingface.co/papers/2306.09364) 中提出。

PatchTSMixer 是一种基于 MLP-Mixer 架构的轻量级时间序列建模方法。在此 HuggingFace 实现中，我们提供了 PatchTSMixer 的功能，以便轻松实现跨 patch、通道和隐藏特征的轻量级混合，从而有效地进行多变量时间序列建模。它还支持多种注意力机制，从简单的门控注意力到更复杂的自注意力块，均可按需自定义。该模型可以预训练，随后用于预测、分类和回归等各种下游任务。

该论文的摘要如下：

*TSMixer 是一种轻量级神经架构，完全由多层感知机（MLP）模块组成，专为基于分块时间序列的多变量预测和表示学习而设计。我们的模型借鉴了 MLP-Mixer 模型在计算机视觉领域取得的成功。我们展示了将视觉 MLP-Mixer 适配到时间序列任务中面临的挑战，并引入了经过实证验证的组件以提升精度。这包括一种新颖的设计范式，即在 MLP-Mixer 主干上附加在线协调头，以显式建模时间序列特性，例如层次结构和通道相关性。我们还提出了一种混合通道建模方法，以有效处理噪声通道交互以及在不同数据集上的泛化问题，这是现有分块通道混合方法中常见的挑战。此外，我们在主干中引入了一种简单的门控注意力机制，以优先处理重要特征。通过整合这些轻量级组件，我们显著增强了简单 MLP 结构的学习能力，在计算资源消耗极小的情况下，性能超越了复杂的 Transformer 模型。此外，TSMixer 的模块化设计使其能够兼容监督学习和掩码自监督学习方法，使其成为时间序列基础模型的一个有前景的构建模块。在预测任务中，TSMixer 以 8-60% 的显著优势超越了最先进的 MLP 和 Transformer 模型。与最新的强大基准 Patch-Transformer 模型相比，它也以 1-2% 的优势胜出，同时大幅降低了内存和运行时间（2-3 倍）。*

该模型由 [ajati](https://huggingface.co/ajati)、[vijaye12](https://huggingface.co/vijaye12)、[gsinthong](https://huggingface.co/gsinthong)、[namctin](https://huggingface.co/namctin)、[wmgifford](https://huggingface.co/wmgifford) 和 [kashif](https://huggingface.co/kashif) 贡献。

## 使用示例

以下代码片段展示了如何随机初始化 PatchTSMixer 模型。该模型兼容 [Trainer API](../trainer)。

```python

from transformers import PatchTSMixerConfig, PatchTSMixerForPrediction
from transformers import Trainer, TrainingArguments,

config = PatchTSMixerConfig(context_length = 512, prediction_length = 96)
model = PatchTSMixerForPrediction(config)
trainer = Trainer(model=model, args=training_args, 
            train_dataset=train_dataset,
            eval_dataset=valid_dataset)
trainer.train()
results = trainer.evaluate(test_dataset)
```

## 使用技巧

该模型还可用于时间序列分类和时间序列回归。请参阅相应的 [PatchTSMixerForTimeSeriesClassification](/docs/transformers/v5.23.0/zh/model_doc/patchtsmixer#transformers.PatchTSMixerForTimeSeriesClassification) 和 [PatchTSMixerForRegression](/docs/transformers/v5.23.0/zh/model_doc/patchtsmixer#transformers.PatchTSMixerForRegression) 类。

## 资源

- 一篇深入讲解 PatchTSMixer 的博客文章可以在[这里](https://huggingface.co/blog/patchtsmixer)找到。该博客也可以在 Google Colab 中打开。

## PatchTSMixerConfig[[transformers.PatchTSMixerConfig]]

#### transformers.PatchTSMixerConfig[[transformers.PatchTSMixerConfig]]

```python
transformers.PatchTSMixerConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, context_length: int = 32, patch_length: int = 8, num_input_channels: int = 1, patch_stride: int = 8, num_parallel_samples: int = 100, d_model: int = 8, expansion_factor: int = 2, num_layers: int = 3, dropout: float | int = 0.2, mode: str = 'common_channel', gated_attn: bool = True, norm_mlp: str = 'LayerNorm', self_attn: bool = False, self_attn_heads: int = 1, use_positional_encoding: bool = False, positional_encoding_type: str = 'sincos', scaling: str | bool | None = 'std', loss: str = 'mse', init_std: float = 0.02, norm_eps: float = 1e-05, mask_type: str = 'random', random_mask_ratio: float = 0.5, num_forecast_mask_patches: list[int] | tuple[int, ...] | int | None = (2,), mask_value: int = 0, masked_loss: bool = True, channel_consistent_masking: bool = True, unmasked_channel_indices: list[int] | None = None, head_dropout: float | int = 0.2, distribution_output: str = 'student_t', prediction_length: int = 16, prediction_channel_indices: list | None = None, num_targets: int = 3, output_range: list | None = None, head_aggregation: str | None = 'max_pool')
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/patchtsmixer/configuration_patchtsmixer.py#L24)

**参数：**

context_length (`int`，*可选*，默认为 32)：输入序列的上下文/历史长度。

patch_length (`int`，*可选*，默认为 8)：输入序列的 patch 长度。

num_input_channels (`int`，*可选*，默认为 `1`)：输入通道数。

patch_stride (`int`，*可选*，默认为 8)：确定两个连续 patch 之间的重叠部分。如果希望 patch 之间不重叠，请将其设置为 patch_length（或更大值）。

num_parallel_samples (`int`，*可选*，默认为 100)：用于概率预测时并行生成的样本数量。

d_model (`int`，*可选*，默认为 `8`)：编码器层和池化层的大小。

expansion_factor (`int`，*可选*，默认为 2)：MLP 内部使用的扩展因子。推荐范围为 2-5。值越大，模型越复杂。

num_layers (`int`，*可选*，默认为 `3`)：Transformer 解码器中的隐藏层数。

dropout (`Union[float, int]`，*可选*，默认为 `0.2`)：所有 dropout 层的比率。

mode (`str`, *可选*, 默认为 `"common_channel"`) : 混合器模式。确定如何处理通道。允许的值："common_channel"、"mix_channel"。在 "common_channel" 模式下，我们采用通道独立建模，不进行显式的通道混合。通道混合通过跨通道共享权重以隐式方式实现。（首选的初始方法）在 "mix_channel" 模式下，除了 patch 和特征混合器外，我们还采用显式的通道混合。（当通道相关性对建模非常重要时，首选此方法）

gated_attn (`bool`, *可选*, 默认为 `True`) : 启用门控注意力。

norm_mlp (`str`，*可选*，默认为 `"LayerNorm"`)：归一化层（BatchNorm 或 LayerNorm）。

self_attn (`bool`, *可选*，默认为 `False`)：在 patch 之间启用 Tiny self attention。当带有门控注意力的 Vanilla PatchTSMixer 输出效果不佳时，可以启用此选项。启用后，将在 patch 之间进行显式的成对注意力和建模。

self_attn_heads (`int`，*可选*，默认为 1)：自注意力头的数量。仅在 `self_attn` 设置为 `True` 时有效。

use_positional_encoding (`bool`，*可选*，默认为 `False`)：是否启用小型自注意力层的位置嵌入。仅当 `self_attn` 设置为 `True` 时有效。

positional_encoding_type (`str`，*可选*，默认为 `"sincos"`)：位置编码。支持 `"random"` 和 `"sincos"` 选项。仅在 `use_positional_encoding` 设置为 `True` 时生效

scaling (`string` 或 `bool`，*可选*，默认为 `"std"`)：是否通过 "mean" 缩放器、"std" 缩放器对输入目标进行缩放，若为 `None` 则不进行缩放。若为 `True`，则缩放器设置为 "mean"。

loss (`string`，*可选*，默认为 `"mse"`)：与 `distribution_output` 头对应的模型的损失函数。对于参数化分布，它是负对数似然（"nll"）；对于点估计，它是均方误差 "mse"。

init_std (`float`，*可选*，默认值为 `0.02`)：用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。

norm_eps (`float`, *可选*，默认为 1e-05)：为归一化添加的数值，用于提高数值稳定性。

mask_type (`str`, *可选*，默认为 `"random"`) : 在 Masked Pretraining 模式下使用的掩码类型。允许的值为 "random" 和 "forecast"。在 Random 掩码中，数据点会被随机掩码。在 Forecast 掩码中，数据点会向序列末尾方向进行掩码。

random_mask_ratio (`float`, *可选*，默认为 0.5) : 当 `mask_type` 为 `random` 时使用的掩码比例。值越高表示掩码越多。

num_forecast_mask_patches (`int` 或 `list`，*可选*，默认为 `[2]`)：每个批次样本末尾要屏蔽的 patch 数量。如果为整数，则批次中所有样本的屏蔽 patch 数量相同。如果为列表，则批次中的样本将根据列表中定义的数量随机屏蔽。此参数仅用于预测预训练。

mask_value (`float`, *可选*, 默认为 `0.0`) : 要使用的掩码值。

masked_loss (`bool`, *可选*, 默认为 `True`) : 是否仅在掩码部分计算预训练损失，还是在整个输出上计算。

channel_consistent_masking (`bool`，*可选*，默认为 `True`)：为 true 时，时间序列所有通道的掩码将保持一致。否则，掩码位置将在各通道间有所不同。

unmasked_channel_indices (`list`，*可选*)：在预训练期间未被屏蔽的通道。

head_dropout (`float`, *可选*, 默认值为 0.2) : `PatchTSMixer` 头部的 dropout 概率。

distribution_output (`string`，*可选*，默认为 `"student_t"`)：当 loss 为 "nll" 时，模型的分布发射头。可以是 "student_t"、"normal" 或 "negative_binomial"。

prediction_length (`int`, *可选*，默认为 16)：预测任务中要预测的时间步数。也称为预测范围（Forecast Horizon）。

prediction_channel_indices (`list`, *可选*) : 要预测的通道索引列表。如果为 None，则预测所有通道。目标数据应包含所有通道，我们在计算损失之前会显式过滤预测和目标中的通道。

num_targets (`int`，*可选*，默认为 3)：回归任务中目标的数量（回归变量的维度）。

output_range (`list`, *可选*) : 用于限制回归任务输出范围。默认为 None。

head_aggregation (`str`, *可选*, 默认为 `"max_pool"`) : 为分类或回归任务启用的聚合模式。允许的值为 `None`、"use_last"、"max_pool"、"avg_pool"。

这是用于存储 PatchTSMixerModel 配置的类。它根据指定的参数实例化 Patchtsmixer 模型，并定义模型架构。使用默认值实例化配置将得到与 [ibm/patchtsmixer-etth1-pretrain](https://huggingface.co/ibm/patchtsmixer-etth1-pretrain) 类似的配置。

配置对象继承自 [PreTrainedConfig](/docs/transformers/v5.23.0/zh/main_classes/configuration#transformers.PreTrainedConfig)，可用于控制模型输出。有关更多信息，请参阅 [PreTrainedConfig](/docs/transformers/v5.23.0/zh/main_classes/configuration#transformers.PreTrainedConfig) 的文档。

示例：

```python
>>> from transformers import PatchTSMixerConfig, PatchTSMixerModel

>>> # Initializing a default PatchTSMixer configuration
>>> configuration = PatchTSMixerConfig()

>>> # Randomly initializing a model (with random weights) from the configuration
>>> model = PatchTSMixerModel(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config
```

## PatchTSMixerModel[[transformers.PatchTSMixerModel]]

#### transformers.PatchTSMixerModel[[transformers.PatchTSMixerModel]]

```python
transformers.PatchTSMixerModel(config: PatchTSMixerConfig, mask_input: bool = False)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/patchtsmixer/modeling_patchtsmixer.py#L1200)

**参数：**

config ([PatchTSMixerConfig](/docs/transformers/v5.23.0/zh/model_doc/patchtsmixer#transformers.PatchTSMixerConfig))：模型配置类，包含模型的所有参数。通过配置文件进行初始化时，不会加载与模型关联的权重，仅加载配置。请查看 [from_pretrained()](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 方法以加载模型权重。

mask_input (`bool`, *可选*, 默认为 `False`) : 是否使用 `PatchTSMixerMasking` 模块对输入进行掩码处理。

用于时间序列预测的 PatchTSMixer 模型。

该模型继承自 [PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel)。请查阅父类文档，了解该库为所有模型实现的通用方法（例如下载或保存、调整输入嵌入大小、剪枝头等）。

该模型也是 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) 的子类。请将其作为常规的 PyTorch Module 使用，有关通用用法和行为的所有事项，请参阅 PyTorch 文档。

#### forward[[transformers.PatchTSMixerModel.forward]]

```python
forward(past_values: Tensor, observed_mask: typing.Optional[torch.Tensor] = None, output_hidden_states: bool | None = None, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/patchtsmixer/modeling_patchtsmixer.py#L1226)

**参数：**

past_values (`torch.Tensor`，形状为 `(batch_size, seq_length, num_input_channels)`)：时间序列的上下文值。对于预训练任务，这表示用于预测被掩码部分的输入时间序列。对于预测任务，这表示历史/过去的时间序列值。类似地，对于分类或回归任务，它表示时间序列相应的上下文值。对于单变量时间序列，`num_input_channels` 维度应为 1。对于多变量时间序列，该值大于 1。

observed_mask (`torch.Tensor`，形状为 `(batch_size, sequence_length, num_input_channels)`，*可选*) : 布尔掩码，用于指示哪些 `past_values` 是被观测到的，哪些是缺失的。掩码值在 `[0, 1]` 中选取：- 1 表示 **已观测** 的值，- 0 表示 **缺失** 的值（即被零替换的 NaN）。

output_hidden_states (`bool`, *可选*) : 是否返回所有层的隐藏状态。有关更多详细信息，请参阅返回张量中的 `hidden_states`。

**返回：** `PatchTSMixerModelOutput` 或 `tuple(torch.Tensor)`

`PatchTSMixerModelOutput` 或 `torch.Tensor` 元组（如果传入 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[PatchTSMixerConfig](/docs/transformers/v5.23.0/zh/model_doc/patchtsmixer#transformers.PatchTSMixerConfig)）和输入。

[PatchTSMixerModel](/docs/transformers/v5.23.0/zh/model_doc/patchtsmixer#transformers.PatchTSMixerModel) 的 forward 方法重写了 `__call__` 特殊方法。

尽管前向传播的实现需要在此函数中定义，但之后应调用 `Module` 实例，而不是直接调用此函数，因为前者会负责执行预处理和后处理步骤，而后者会静默地忽略这些步骤。

- **last_hidden_state**（形状为 `(batch_size, num_channels, num_patches, d_model)` 的 `torch.Tensor`）-- 模型最后一层输出的隐藏状态。
- **hidden_states** (`tuple(torch.Tensor)`，*可选*) -- 模型每一层输出的隐藏状态。
- **patch_input**（形状为 `(batch_size, num_channels, num_patches, patch_length)` 的 `torch.Tensor`）-- 输入到模型的补丁化数据。
- **mask** (`torch.Tensor`，形状为 `(batch_size, num_channels, num_patches)`，*可选*) -- 布尔型 Tensor，在掩码补丁处为 True，否则为 False。
- **loc**（形状为 `(batch_size, 1, num_channels)` 的 `torch.Tensor`，*可选*）-- 给出上下文窗口中每个通道的均值。如果启用了 revin，则用于模型外部的 revin 反归一化。
- **scale** (`torch.Tensor`，形状为 `(batch_size, 1, num_channels)`，*可选*) -- 提供每个通道的上下文窗口标准差。如果启用了 revin，则用于模型外部的 revin 反归一化。

## PatchTSMixerForPrediction[[transformers.PatchTSMixerForPrediction]]

#### transformers.PatchTSMixerForPrediction[[transformers.PatchTSMixerForPrediction]]

```python
transformers.PatchTSMixerForPrediction(config: PatchTSMixerConfig)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/patchtsmixer/modeling_patchtsmixer.py#L1481)

**参数：**

config (`PatchTSMixerConfig`) : 配置。

**返回值：**

`None`.

用于预测应用的 `PatchTSMixer`。

#### forward[[transformers.PatchTSMixerForPrediction.forward]]

```python
forward(past_values: Tensor, observed_mask: typing.Optional[torch.Tensor] = None, future_values: typing.Optional[torch.Tensor] = None, output_hidden_states: bool | None = None, return_loss: bool = True, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/patchtsmixer/modeling_patchtsmixer.py#L1523)

**参数：**

past_values (`torch.Tensor`，形状为 `(batch_size, seq_length, num_input_channels)`)：时间序列的上下文值。对于预训练任务，这表示用于预测被掩码部分的输入时间序列。对于预测任务，这表示历史/过去的时间序列值。类似地，对于分类或回归任务，它表示时间序列相应的上下文值。对于单变量时间序列，`num_input_channels` 维度应为 1。对于多变量时间序列，该值大于 1。

observed_mask (`torch.Tensor`，形状为 `(batch_size, sequence_length, num_input_channels)`，*可选*) : 布尔掩码，用于指示哪些 `past_values` 是被观测到的，哪些是缺失的。掩码值在 `[0, 1]` 中选取：- 1 表示 **已观测** 的值，- 0 表示 **缺失** 的值（即被零替换的 NaN）。

future_values (`torch.Tensor`，形状为 `(batch_size, target_len, num_input_channels)`（用于预测任务）、`(batch_size, num_targets)`（用于回归任务）或 `(batch_size,)`（用于分类任务），*可选*）：时间序列的目标值，作为模型的标签。`future_values` 是 Transformer 在训练期间需要学习输出的内容，其输入为 `past_values`。请注意，预训练任务不需要此参数。对于预测任务，其形状应为 `(batch_size, target_len, num_input_channels)`。即使通过设置 `prediction_channel_indices` 参数中的索引来仅预测特定通道，也应传入包含所有通道的目标数据，因为针对预测和目标数据的通道筛选将在损失计算前手动应用。

output_hidden_states (`bool`, *可选*) : 是否返回所有层的隐藏状态。有关更多详细信息，请参阅返回张量中的 `hidden_states`。

return_loss (`bool`,  *可选*) : 是否在 `forward` 调用中返回损失。

**返回：** `PatchTSMixerForPredictionOutput` 或 `tuple(torch.Tensor)`

`PatchTSMixerForPredictionOutput` 或 `torch.Tensor` 元组（如果传入 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[PatchTSMixerConfig](/docs/transformers/v5.23.0/zh/model_doc/patchtsmixer#transformers.PatchTSMixerConfig)）和输入。

[PatchTSMixerForPrediction](/docs/transformers/v5.23.0/zh/model_doc/patchtsmixer#transformers.PatchTSMixerForPrediction) 的 forward 方法重写了 `__call__` 特殊方法。

尽管前向传播的实现需要在此函数中定义，但之后应调用 `Module` 实例，而不是直接调用此函数，因为前者会负责执行预处理和后处理步骤，而后者会静默地忽略这些步骤。

- **loss** (`*optional*`，当提供 `y` 时返回，`torch.Tensor`，形状为 `()`) -- 总损失。
- **prediction_outputs**（形状为 `(batch_size, prediction_length, num_input_channels)` 的 `torch.Tensor`）-- 来自预测头的预测输出。
- **last_hidden_state**（形状为 `(batch_size, num_input_channels, num_patches, d_model)` 的 `torch.Tensor`）-- 在通过 head 之前的 Backbone 嵌入。
- **hidden_states** (`tuple(torch.Tensor)`，*可选*) -- 模型每层输出处的隐藏状态，以及可选的初始嵌入输出。
- **loc** (`torch.Tensor`，*可选*，形状为 `(batch_size, 1, num_input_channels)`) -- 输入均值
- **scale** (`torch.Tensor`，*可选*，形状为 `(batch_size, 1, num_input_channels)`) -- 输入标准差

## PatchTSMixerForTimeSeriesClassification[[transformers.PatchTSMixerForTimeSeriesClassification]]

#### transformers.PatchTSMixerForTimeSeriesClassification[[transformers.PatchTSMixerForTimeSeriesClassification]]

```python
transformers.PatchTSMixerForTimeSeriesClassification(config: PatchTSMixerConfig)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/patchtsmixer/modeling_patchtsmixer.py#L1707)

**参数：**

config (`PatchTSMixerConfig`) : 配置。

**返回值：**

`None`.

用于分类应用的 `PatchTSMixer`。

#### forward[[transformers.PatchTSMixerForTimeSeriesClassification.forward]]

```python
forward(past_values: Tensor, target_values: typing.Optional[torch.Tensor] = None, output_hidden_states: bool | None = None, return_loss: bool = True, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/patchtsmixer/modeling_patchtsmixer.py#L1734)

**参数：**

past_values (`torch.Tensor`，形状为 `(batch_size, seq_length, num_input_channels)`)：时间序列的上下文值。对于预训练任务，这表示用于预测被掩码部分的输入时间序列。对于预测任务，这表示历史/过去的时间序列值。类似地，对于分类或回归任务，它表示时间序列相应的上下文值。对于单变量时间序列，`num_input_channels` 维度应为 1。对于多变量时间序列，该值大于 1。

target_values (`torch.Tensor`，形状为 `(batch_size, target_len, num_input_channels)`（用于预测任务）、`(batch_size, num_targets)`（用于回归任务）或 `(batch_size,)`（用于分类任务），*可选*）：时间序列的目标值，作为模型的标签。`target_values` 是 Transformer 在训练期间需要学习输出的内容，其输入为 `past_values`。请注意，预训练任务不需要此参数。对于预测任务，其形状应为 `(batch_size, target_len, num_input_channels)`。即使通过设置 `prediction_channel_indices` 参数中的索引来仅预测特定通道，也应传入包含所有通道的目标数据，因为预测和目标通道的筛选将在损失计算前手动应用。对于分类任务，其形状为 `(batch_size,)`。对于回归任务，其形状为 `(batch_size, num_targets)`。

output_hidden_states (`bool`, *可选*) : 是否返回所有层的隐藏状态。有关更多详细信息，请参阅返回张量中的 `hidden_states`。

return_loss (`bool`, *可选*) : 是否在 `forward` 调用中返回损失。

**返回：** `PatchTSMixerForTimeSeriesClassificationOutput` 或 `tuple(torch.Tensor)`

`PatchTSMixerForTimeSeriesClassificationOutput` 或 `torch.Tensor` 元组（如果传入 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[PatchTSMixerConfig](/docs/transformers/v5.23.0/zh/model_doc/patchtsmixer#transformers.PatchTSMixerConfig)）和输入。

[PatchTSMixerForTimeSeriesClassification](/docs/transformers/v5.23.0/zh/model_doc/patchtsmixer#transformers.PatchTSMixerForTimeSeriesClassification) 的 forward 方法重写了 `__call__` 特殊方法。

尽管前向传播的实现需要在此函数中定义，但之后应调用 `Module` 实例，而不是直接调用此函数，因为前者会负责执行预处理和后处理步骤，而后者会静默地忽略这些步骤。

- **loss** (`*optional*`，当提供 `y` 时返回，`torch.Tensor`，形状为 `()`) -- 总损失。
- **prediction_outputs**（形状为 `(batch_size, num_labels)` 的 `torch.Tensor`）-- 分类头的预测输出。
- **last_hidden_state**（形状为 `(batch_size, num_input_channels, num_patches, d_model)` 的 `torch.Tensor`）-- 在通过 head 之前的 Backbone 嵌入。
- **hidden_states** (`tuple(torch.Tensor)`，*可选*) -- 模型每层输出处的隐藏状态，以及可选的初始嵌入输出。

## PatchTSMixerForPretraining[[transformers.PatchTSMixerForPretraining]]

#### transformers.PatchTSMixerForPretraining[[transformers.PatchTSMixerForPretraining]]

```python
transformers.PatchTSMixerForPretraining(config: PatchTSMixerConfig)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/patchtsmixer/modeling_patchtsmixer.py#L1313)

**参数：**

config ([PatchTSMixerConfig](/docs/transformers/v5.23.0/zh/model_doc/patchtsmixer#transformers.PatchTSMixerConfig))：模型配置类，包含模型的所有参数。通过配置文件进行初始化时，不会加载与模型关联的权重，仅加载配置。请查看 [from_pretrained()](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 方法以加载模型权重。

用于掩码预训练的 `PatchTSMixer`。

该模型继承自 [PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel)。请查阅父类文档，了解该库为所有模型实现的通用方法（例如下载或保存、调整输入嵌入大小、剪枝头等）。

该模型也是 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) 的子类。请将其作为常规的 PyTorch Module 使用，有关通用用法和行为的所有事项，请参阅 PyTorch 文档。

#### forward[[transformers.PatchTSMixerForPretraining.forward]]

```python
forward(past_values: Tensor, observed_mask: typing.Optional[torch.Tensor] = None, output_hidden_states: bool | None = None, return_loss: bool = True, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/patchtsmixer/modeling_patchtsmixer.py#L1323)

**参数：**

past_values (`torch.Tensor`，形状为 `(batch_size, seq_length, num_input_channels)`)：时间序列的上下文值。对于预训练任务，这表示用于预测被掩码部分的输入时间序列。对于预测任务，这表示历史/过去的时间序列值。类似地，对于分类或回归任务，它表示时间序列相应的上下文值。对于单变量时间序列，`num_input_channels` 维度应为 1。对于多变量时间序列，该值大于 1。

observed_mask (`torch.Tensor`，形状为 `(batch_size, sequence_length, num_input_channels)`，*可选*) : 布尔掩码，用于指示哪些 `past_values` 是被观测到的，哪些是缺失的。掩码值在 `[0, 1]` 中选取：- 1 表示 **已观测** 的值，- 0 表示 **缺失** 的值（即被零替换的 NaN）。

output_hidden_states (`bool`, *可选*) : 是否返回所有层的隐藏状态。有关更多详细信息，请参阅返回张量中的 `hidden_states`。

return_loss (`bool`,  *可选*) : 是否在 `forward` 调用中返回损失。

**返回：** `PatchTSMixerForPreTrainingOutput` 或 `tuple(torch.Tensor)`

`PatchTSMixerForPreTrainingOutput` 或 `torch.Tensor` 元组（如果传入 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[PatchTSMixerConfig](/docs/transformers/v5.23.0/zh/model_doc/patchtsmixer#transformers.PatchTSMixerConfig)）和输入。

[PatchTSMixerForPretraining](/docs/transformers/v5.23.0/zh/model_doc/patchtsmixer#transformers.PatchTSMixerForPretraining) 的 forward 方法重写了 `__call__` 特殊方法。

尽管前向传播的实现需要在此函数中定义，但之后应调用 `Module` 实例，而不是直接调用此函数，因为前者会负责执行预处理和后处理步骤，而后者会静默地忽略这些步骤。

- **loss** (`*optional*`, returned when `y` is provided, `torch.Tensor` of shape `()`) -- Total loss
- **prediction_outputs**（形状为 `(batch_size, num_input_channels, num_patches, patch_length)` 的 `torch.Tensor`）-- 来自预训练头的预测输出。
- **last_hidden_state**（形状为 `(batch_size, num_input_channels, num_patches, d_model)` 的 `torch.Tensor`）-- 在通过 head 之前的 Backbone 嵌入。
- **hidden_states** (`tuple(torch.Tensor)`，*可选*) -- 模型每一层输出的隐藏状态。

## PatchTSMixerForRegression[[transformers.PatchTSMixerForRegression]]

#### transformers.PatchTSMixerForRegression[[transformers.PatchTSMixerForRegression]]

```python
transformers.PatchTSMixerForRegression(config: PatchTSMixerConfig)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/patchtsmixer/modeling_patchtsmixer.py#L1875)

**参数：**

config ([PatchTSMixerConfig](/docs/transformers/v5.23.0/zh/model_doc/patchtsmixer#transformers.PatchTSMixerConfig))：模型配置类，包含模型的所有参数。通过配置文件进行初始化时，不会加载与模型关联的权重，仅加载配置。请查看 [from_pretrained()](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 方法以加载模型权重。

用于回归应用的 `PatchTSMixer`。

该模型继承自 [PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel)。请查阅父类文档，了解该库为所有模型实现的通用方法（例如下载或保存、调整输入嵌入大小、剪枝头等）。

该模型也是 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) 的子类。请将其作为常规的 PyTorch Module 使用，有关通用用法和行为的所有事项，请参阅 PyTorch 文档。

#### forward[[transformers.PatchTSMixerForRegression.forward]]

```python
forward(past_values: Tensor, target_values: typing.Optional[torch.Tensor] = None, output_hidden_states: bool | None = None, return_loss: bool = True, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/patchtsmixer/modeling_patchtsmixer.py#L1913)

**参数：**

past_values (`torch.Tensor`，形状为 `(batch_size, seq_length, num_input_channels)`)：时间序列的上下文值。对于预训练任务，这表示用于预测被掩码部分的输入时间序列。对于预测任务，这表示历史/过去的时间序列值。类似地，对于分类或回归任务，它表示时间序列相应的上下文值。对于单变量时间序列，`num_input_channels` 维度应为 1。对于多变量时间序列，该值大于 1。

target_values (`torch.Tensor`，形状为 `(batch_size, target_len, num_input_channels)`（用于预测任务）、`(batch_size, num_targets)`（用于回归任务）或 `(batch_size,)`（用于分类任务），*可选*）：时间序列的目标值，作为模型的标签。`target_values` 是 Transformer 在训练期间需要学习输出的内容，其输入为 `past_values`。请注意，预训练任务不需要此参数。对于预测任务，其形状应为 `(batch_size, target_len, num_input_channels)`。即使通过设置 `prediction_channel_indices` 参数中的索引来仅预测特定通道，也应传入包含所有通道的目标数据，因为预测和目标通道的筛选将在损失计算前手动应用。对于分类任务，其形状为 `(batch_size,)`。对于回归任务，其形状为 `(batch_size, num_targets)`。

output_hidden_states (`bool`, *可选*) : 是否返回所有层的隐藏状态。有关更多详细信息，请参阅返回张量中的 `hidden_states`。

return_loss (`bool`, *可选*) : 是否在 `forward` 调用中返回损失。

**返回：** `PatchTSMixerForRegressionOutput` 或 `tuple(torch.Tensor)`

`PatchTSMixerForRegressionOutput` 或 `torch.Tensor` 元组（如果传入 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[PatchTSMixerConfig](/docs/transformers/v5.23.0/zh/model_doc/patchtsmixer#transformers.PatchTSMixerConfig)）和输入。

[PatchTSMixerForRegression](/docs/transformers/v5.23.0/zh/model_doc/patchtsmixer#transformers.PatchTSMixerForRegression) 的 forward 方法重写了 `__call__` 特殊方法。

尽管前向传播的实现需要在此函数中定义，但之后应调用 `Module` 实例，而不是直接调用此函数，因为前者会负责执行预处理和后处理步骤，而后者会静默地忽略这些步骤。

- **loss** (`*optional*`，当提供 `y` 时返回，`torch.Tensor`，形状为 `()`) -- 总损失。
- **regression_outputs**（形状为 `(batch_size, num_targets)` 的 `torch.Tensor`）-- 回归头的预测输出。
- **last_hidden_state**（形状为 `(batch_size, num_input_channels, num_patches, d_model)` 的 `torch.Tensor`）-- 在通过 head 之前的 Backbone 嵌入。
- **hidden_states** (`tuple(torch.Tensor)`，*可选*) -- 模型每层输出处的隐藏状态，以及可选的初始嵌入输出。

