# PatchTST

## 概述

PatchTST 模型由 Yuqi Nie、Nam H. Nguyen、Phanwadee Sinthong 和 Jayant Kalagnanam 在 [A Time Series is Worth 64 Words: Long-term Forecasting with Transformers](https://huggingface.co/papers/2211.14730) 中提出。

从宏观层面来看，该模型将时间序列向量化为指定大小的补丁（patch），然后通过 Transformer 对由此生成的向量序列进行编码，最后通过相应的输出头（head）输出预测长度（prediction length）的预测结果。该模型如下图所示：

![model](https://github.com/namctin/transformers/assets/8100/150af169-29de-419a-8d98-eb78251c21fa)

该论文的摘要如下：

*我们提出了一种基于 Transformer 的模型的高效设计，用于多变量时间序列预测和自监督表示学习。该设计基于两个关键组件：(i) 将时间序列分割为子序列级别的 patch，并将其作为输入 token 提供给 Transformer；(ii) 通道独立性，即每个通道包含一个单变量时间序列，且所有序列共享相同的 embedding 和 Transformer 权重。Patching 设计天然具有三重优势：embedding 中保留了局部语义信息；在相同的回看窗口下，注意力图的计算量和内存占用呈二次方降低；并且模型能够关注更长的历史。与最先进的基于 Transformer 的模型相比，我们的通道独立 patch 时间序列 Transformer（PatchTST）能够显著提升长期预测的准确性。我们还将该模型应用于自监督预训练任务，并取得了出色的微调性能，其效果优于在大型数据集上的有监督训练。将一个数据集上掩码预训练的表示迁移到其他数据集，也能产生最先进的预测准确性。*

该模型由 [namctin](https://huggingface.co/namctin)、[gsinthong](https://huggingface.co/gsinthong)、[diepi](https://huggingface.co/diepi)、[vijaye12](https://huggingface.co/vijaye12)、[wmgifford](https://huggingface.co/wmgifford) 和 [kashif](https://huggingface.co/kashif) 贡献。原始代码可在[此处](https://github.com/yuqinie98/PatchTST)找到。

## 使用技巧

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

## 资源

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

## PatchTSTConfig[[transformers.PatchTSTConfig]]

#### transformers.PatchTSTConfig[[transformers.PatchTSTConfig]]

```python
transformers.PatchTSTConfig(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, num_input_channels: int = 1, context_length: int = 32, distribution_output: str = 'student_t', loss: str | None = 'mse', patch_length: int = 1, patch_stride: int = 1, num_hidden_layers: int = 3, d_model: int = 128, num_attention_heads: int = 4, share_embedding: bool = True, channel_attention: bool = False, ffn_dim: int = 512, norm_type: str = 'batchnorm', norm_eps: float = 1e-05, attention_dropout: float | int = 0.0, positional_dropout: float | int = 0.0, path_dropout: float | int = 0.0, ff_dropout: float | int = 0.0, bias: bool = True, activation_function: str = 'gelu', pre_norm: bool = True, positional_encoding_type: str = 'sincos', use_cls_token: bool = False, init_std: float = 0.02, share_projection: bool = True, scaling: str | bool | None = 'std', do_mask_input: bool | None = None, mask_type: str = 'random', random_mask_ratio: float = 0.5, num_forecast_mask_patches: list[int] | tuple[int, ...] | int | None = (2,), channel_consistent_masking: bool | None = False, unmasked_channel_indices: list[int] | None = None, mask_value: int = 0, pooling_type: str | None = 'mean', head_dropout: float | int = 0.0, prediction_length: int = 24, num_targets: int = 1, output_range: list | None = None, num_parallel_samples: int = 100)
```

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

**参数：**

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

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

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

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

patch_length (`int`，*可选*，默认为 1)：定义分块化过程中的分块长度。

patch_stride (`int`，*可选*，默认为 1)：定义分块过程的步长。

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

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

num_attention_heads (`int`，*可选*，默认为 4)：Transformer 编码器中每个注意力层的注意力头数量。

share_embedding (`bool`, *可选*, 默认为 `True`) : 在所有通道间共享输入嵌入。

channel_attention (`bool`, *可选*, 默认为 `False`) : 在 Transformer 中启用通道注意力块，以允许各通道之间相互关注。

ffn_dim (`int`，*可选*，默认值为 512)：Transformer 编码器中“中间”（通常称为前馈）层的维度。

norm_type (`str` , *可选*, 默认为 `"batchnorm"`) : 每个 Transformer 层的归一化。可以是 `"batchnorm"` 或 `"layernorm"`。

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

attention_dropout (`Union[float, int]`，*可选*，默认值为 `0.0`)：注意力概率的 dropout 比率。

positional_dropout (`float`, *可选*，默认为 0.0)：位置嵌入层中的 dropout 概率。

path_dropout (`float`, *可选*，默认为 0.0)：残差块中的 dropout 路径。

ff_dropout (`float`, *可选*，默认为 0.0)：前馈网络两层之间使用的 dropout 概率。

bias (`bool`，*可选*，默认为 `True`)：是否在前馈网络中添加偏置。

activation_function (`str`, *可选*, 默认为 `"gelu"`) : Transformer 中的非线性激活函数（字符串）。支持 `"gelu"` 和 `"relu"`。

pre_norm (`bool`，*可选*，默认为 `True`)：如果 pre_norm 设置为 `True`，则在自注意力之前应用归一化。否则，归一化在残差块之后应用。

positional_encoding_type (`str`，*可选*，默认为 `"sincos"`)：位置编码。支持 `"random"` 和 `"sincos"` 选项。

use_cls_token (`bool`，*可选*，默认为 `False`)：是否使用 cls token。

init_std (`float`, *可选*，默认为 0.02)：截断正态权重初始化分布的标准差。

share_projection (`bool`, *可选*, 默认为 `True`) : 在预测头中跨不同通道共享投影层。

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

do_mask_input (`bool`, *可选*) : 在预训练期间应用掩码。

mask_type (`str`，*可选*，默认为 `"random"`)：掩码类型。目前仅支持 `"random"` 和 `"forecast"`。

random_mask_ratio (`float`, *可选*, 默认值为 0.5) : 在随机预训练期间用于掩蔽输入数据的掩蔽比例。

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

channel_consistent_masking (`bool`，*可选*，默认为 `False`)：如果通道一致性掩码为 True，则所有通道将具有相同的掩码模式。

unmasked_channel_indices (`list`, *可选*) : 在预训练期间未被屏蔽的通道索引。列表中的值为 1 到 `num_input_channels` 之间的数字

mask_value (`int`，*可选*，默认为 0)：掩码补丁中的值将由 `mask_value` 填充。

pooling_type (`str`，*可选*，默认为 `"mean"`)：嵌入的池化方式。支持 `"mean"`、`"max"` 和 `None`。

head_dropout (`float`, *可选*，默认为 0.0)：head 的 dropout 概率。

prediction_length (`int`，*可选*，默认为 24)：模型将输出的预测步长。

num_targets (`int`，*可选*，默认为 1)：回归和分类任务的目标数量。对于分类任务，即类别数。

output_range (`list`, *可选*) : 回归任务的输出范围。可以设置输出值的范围，以强制模型生成该范围内的值。

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

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

配置对象继承自 [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 PatchTSTConfig, PatchTSTModel

>>> # Initializing an PatchTST configuration with 12 time steps for prediction
>>> configuration = PatchTSTConfig(prediction_length=12)

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

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

## PatchTSTModel[[transformers.PatchTSTModel]]

#### transformers.PatchTSTModel[[transformers.PatchTSTModel]]

```python
transformers.PatchTSTModel(config: PatchTSTConfig)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/patchtst/modeling_patchtst.py#L1066)

**参数：**

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

未添加任何特定头部的裸 Patchtst 模型，直接输出原始隐藏状态。

该模型继承自 [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.PatchTSTModel.forward]]

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

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/patchtst/modeling_patchtst.py#L1085)

**参数：**

past_values (`torch.Tensor`，形状为 `(bs, sequence_length, num_input_channels)`，*必需*)：模型的输入序列

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

future_values (`torch.BoolTensor`，形状为 `(batch_size, prediction_length, num_input_channels)`，*可选*)：与 `past_values` 关联的未来目标值

output_hidden_states (`bool`, *可选*) : 是否返回所有层的隐藏状态

output_attentions (`bool`, *可选*) : 是否返回所有层的输出注意力

return_dict (`bool`, *可选*) : 是否返回 `ModelOutput` 而不是普通元组。

**返回值：**

`PatchTSTModelOutput` 或 `torch.Tensor` 元组（如果 `return_dict`=False 或 `config.return_dict`=False）

示例：

```python
>>> from huggingface_hub import hf_hub_download
>>> import torch
>>> from transformers import PatchTSTModel

>>> file = hf_hub_download(
...     repo_id="hf-internal-testing/etth1-hourly-batch", filename="train-batch.pt", repo_type="dataset"
... )
>>> batch = torch.load(file)

>>> model = PatchTSTModel.from_pretrained("namctin/patchtst_etth1_pretrain")

>>> # during training, one provides both past and future values
>>> outputs = model(
...     past_values=batch["past_values"],
...     future_values=batch["future_values"],
... )

>>> last_hidden_state = outputs.last_hidden_state
```

## PatchTSTForPrediction[[transformers.PatchTSTForPrediction]]

#### transformers.PatchTSTForPrediction[[transformers.PatchTSTForPrediction]]

```python
transformers.PatchTSTForPrediction(config: PatchTSTConfig)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/patchtst/modeling_patchtst.py#L1560)

**参数：**

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

用于预测的 PatchTST 模型。

该模型继承自 [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.PatchTSTForPrediction.forward]]

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

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/patchtst/modeling_patchtst.py#L1590)

**参数：**

past_values (`torch.Tensor`，形状为 `(bs, sequence_length, num_input_channels)`，*必需*)：模型的输入序列

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

future_values (`torch.Tensor`，形状为 `(bs, forecast_len, num_input_channels)`，*可选*)：与 `past_values` 关联的未来目标值

output_hidden_states (`bool`, *可选*) : 是否返回所有层的隐藏状态

output_attentions (`bool`, *可选*) : 是否返回所有层的输出注意力

return_dict (`bool`, *可选*) : 是否返回 `ModelOutput` 而不是普通元组。

**返回值：**

`PatchTSTForPredictionOutput` 或 `torch.Tensor` 元组（如果 `return_dict`=False 或 `config.return_dict`=False）

示例：

```python
>>> from huggingface_hub import hf_hub_download
>>> import torch
>>> from transformers import PatchTSTConfig, PatchTSTForPrediction

>>> file = hf_hub_download(
...     repo_id="hf-internal-testing/etth1-hourly-batch", filename="train-batch.pt", repo_type="dataset"
... )
>>> batch = torch.load(file)

>>> # Prediction task with 7 input channels and prediction length is 96
>>> model = PatchTSTForPrediction.from_pretrained("namctin/patchtst_etth1_forecast")

>>> # during training, one provides both past and future values
>>> outputs = model(
...     past_values=batch["past_values"],
...     future_values=batch["future_values"],
... )

>>> loss = outputs.loss
>>> loss.backward()

>>> # during inference, one only provides past values, the model outputs future values
>>> outputs = model(past_values=batch["past_values"])
>>> prediction_outputs = outputs.prediction_outputs
```

## PatchTSTForClassification[[transformers.PatchTSTForClassification]]

#### transformers.PatchTSTForClassification[[transformers.PatchTSTForClassification]]

```python
transformers.PatchTSTForClassification(config: PatchTSTConfig)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/patchtst/modeling_patchtst.py#L1366)

**参数：**

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

用于分类模型的 PatchTST。

该模型继承自 [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.PatchTSTForClassification.forward]]

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

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/patchtst/modeling_patchtst.py#L1381)

**参数：**

past_values (`torch.Tensor`，形状为 `(bs, sequence_length, num_input_channels)`，*必需*)：模型的输入序列

target_values (`torch.Tensor`, *可选*) : 与 `past_values` 关联的标签

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

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

output_attentions (`bool`, *可选*) : 是否返回所有注意力层的注意力张量。有关更多详细信息，请参阅返回张量中的 `attentions`。

return_dict (`bool`, *可选*) : 是否返回 [ModelOutput](/docs/transformers/v5.23.0/zh/main_classes/output#transformers.utils.ModelOutput) 而不是普通元组。

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

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

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

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

- **loss** (`*optional*`，当提供 `labels` 时返回，形状为 `(1,)` 的 `torch.Tensor`) -- 总损失，为掩码语言建模损失与下一句预测（分类）损失之和。
- **prediction_logits**（形状为 `(batch_size, num_targets)` 的 `torch.Tensor`）-- PatchTST 建模头的预测分数（SoftMax 之前的分数）。
- **hidden_states** (`tuple[torch.Tensor]`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（如果模型具有嵌入层，则包含嵌入层输出的一个张量，以及每个层输出的一个张量），形状为 `(batch_size, sequence_length, hidden_size)`。

  模型在每一层输出处的隐藏状态，以及可选的初始嵌入输出。
- **attentions** (`tuple[torch.Tensor]`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。

  经过注意力 softmax 后的注意力权重，用于在自注意力头中计算加权平均值。

示例：

```python
>>> from transformers import PatchTSTConfig, PatchTSTForClassification

>>> # classification task with two input channel2 and 3 classes
>>> config = PatchTSTConfig(
...     num_input_channels=2,
...     num_targets=3,
...     context_length=512,
...     patch_length=12,
...     stride=12,
...     use_cls_token=True,
... )
>>> model = PatchTSTForClassification(config=config)

>>> # during inference, one only provides past values
>>> past_values = torch.randn(20, 512, 2)
>>> outputs = model(past_values=past_values)
>>> labels = outputs.prediction_logits
```

## PatchTSTForPretraining[[transformers.PatchTSTForPretraining]]

#### transformers.PatchTSTForPretraining[[transformers.PatchTSTForPretraining]]

```python
transformers.PatchTSTForPretraining(config: PatchTSTConfig)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/patchtst/modeling_patchtst.py#L1212)

**参数：**

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

用于预训练模型的 PatchTST。

该模型继承自 [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.PatchTSTForPretraining.forward]]

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

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/patchtst/modeling_patchtst.py#L1223)

**参数：**

past_values (`torch.Tensor`，形状为 `(bs, sequence_length, num_input_channels)`，*必需*)：模型的输入序列

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

output_hidden_states (`bool`, *可选*) : 是否返回所有层的隐藏状态

output_attentions (`bool`, *可选*) : 是否返回所有层的输出注意力

return_dict (`bool`, *可选*) : 是否返回 `ModelOutput` 而不是普通元组。

**返回值：**

`PatchTSTForPretrainingOutput` 或 `torch.Tensor` 元组（如果 `return_dict`=False 或 `config.return_dict`=False）

示例：

```python
>>> from huggingface_hub import hf_hub_download
>>> import torch
>>> from transformers import PatchTSTConfig, PatchTSTForPretraining

>>> file = hf_hub_download(
...     repo_id="hf-internal-testing/etth1-hourly-batch", filename="train-batch.pt", repo_type="dataset"
... )
>>> batch = torch.load(file)

>>> # Config for random mask pretraining
>>> config = PatchTSTConfig(
...     num_input_channels=7,
...     context_length=512,
...     patch_length=12,
...     stride=12,
...     mask_type='random',
...     random_mask_ratio=0.4,
...     use_cls_token=True,
... )
>>> # Config for forecast mask pretraining
>>> config = PatchTSTConfig(
...     num_input_channels=7,
...     context_length=512,
...     patch_length=12,
...     stride=12,
...     mask_type='forecast',
...     num_forecast_mask_patches=5,
...     use_cls_token=True,
... )
>>> model = PatchTSTForPretraining(config)

>>> # during training, one provides both past and future values
>>> outputs = model(past_values=batch["past_values"])

>>> loss = outputs.loss
>>> loss.backward()
```

## PatchTSTForRegression[[transformers.PatchTSTForRegression]]

#### transformers.PatchTSTForRegression[[transformers.PatchTSTForRegression]]

```python
transformers.PatchTSTForRegression(config: PatchTSTConfig)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/patchtst/modeling_patchtst.py#L1809)

**参数：**

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

用于回归的 PatchTST 模型。

该模型继承自 [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.PatchTSTForRegression.forward]]

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

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/patchtst/modeling_patchtst.py#L1836)

**参数：**

past_values (`torch.Tensor`，形状为 `(bs, sequence_length, num_input_channels)`，*必需*)：模型的输入序列

target_values (`torch.Tensor`，形状为 `(bs, num_input_channels)`)：与 `past_values` 关联的目标值

past_observed_mask (`torch.BoolTensor`，形状为 `(batch_size, sequence_length, num_input_channels)`，*可选*)：布尔掩码，用于指示哪些 `past_values` 是被观测到的，哪些是缺失的。掩码值在 `[0, 1]` 中选取： - 1 表示 **已观测** 的值， - 0 表示 **缺失** 的值（即被零替换的 NaN）。是否返回 `ModelOutput` 而不是普通元组。

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

output_attentions (`bool`, *可选*) : 是否返回所有注意力层的注意力张量。有关更多详细信息，请参阅返回张量中的 `attentions`。

return_dict (`bool`, *可选*) : 是否返回 [ModelOutput](/docs/transformers/v5.23.0/zh/main_classes/output#transformers.utils.ModelOutput) 而不是普通元组。

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

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

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

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

- **loss** (`*optional*`, returned when `labels` is provided, `torch.Tensor` of shape `(1,)`) -- MSE loss.
- **regression_outputs**（形状为 `(batch_size, num_targets)` 的 `torch.Tensor`）-- 时间序列建模头的回归输出。
- **hidden_states** (`tuple[torch.Tensor]`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（如果模型具有嵌入层，则包含嵌入层输出的一个张量，以及每个层输出的一个张量），形状为 `(batch_size, sequence_length, hidden_size)`。

  模型在每一层输出处的隐藏状态，以及可选的初始嵌入输出。
- **attentions** (`tuple[torch.Tensor]`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。

  经过注意力 softmax 后的注意力权重，用于在自注意力头中计算加权平均值。

示例：

```python
>>> from transformers import PatchTSTConfig, PatchTSTForRegression

>>> # Regression task with 6 input channels and regress 2 targets
>>> model = PatchTSTForRegression.from_pretrained("namctin/patchtst_etth1_regression")

>>> # during inference, one only provides past values, the model outputs future values
>>> past_values = torch.randn(20, 512, 6)
>>> outputs = model(past_values=past_values)
>>> regression_outputs = outputs.regression_outputs
```

