# Разреженная авторегрессия

В этом разделе мы используем NeuralProphet для работы с данными с разрешением в 5 минут (ежедневные температуры в Йосемити). Это продолжение учебного пособия `Учебник 4: Авторегрессия`. В то время как четвертый учебник охватывает авторегрессию в общем, настоящий блокнот сосредоточен на разреженности.

```python
if "google.colab" in str(get_ipython()):
    # Удаляем предустановленные пакеты из Colab, чтобы избежать конфликтов
    !pip uninstall -y torch notebook notebook_shim tensorflow tensorflow-datasets prophet torchaudio torchdata torchtext torchvision
    !pip install git+https://github.com/ourownstory/neural_prophet.git@examples_cond_seas # может занять некоторое время
    #!pip install neuralprophet # намного быстрее, но может не иметь последних обновлений/исправлений ошибок

import pandas as pd
from neuralprophet import NeuralProphet, set_log_level, df_utils

set_log_level("ERROR")

```

```python
data_location = "https://raw.githubusercontent.com/ourownstory/neuralprophet-data/main/datasets/"
df = pd.read_csv(data_location + "yosemite_temps.csv")
```

### Разрежение коэффициентов AR

Компонент авторегрессии в NeuralProphet определяется как AR-Net ([статья](https://arxiv.org/abs/1911.12436), [github](https://github.com/ourownstory/AR-Net)). Следовательно, мы можем установить значение `ar_reg` больше нуля, если хотим вызвать разреженность в коэффициентах AR.

Однако подгонка модели с несколькими компонентами и регуляризациями может быть более сложной и в некоторых случаях вам может понадобиться вручную управлять гиперпараметрами обучения.

Мы начнем с установки регуляризации на 0.1

```python
m = NeuralProphet(
    n_lags=6 * 12,
    n_forecasts=3 * 12,
    n_changepoints=0,
    weekly_seasonality=False,
    daily_seasonality=False,
    learning_rate=0.01,
    ar_reg=0.1,
)
m.set_plotting_backend("plotly-static")
metrics = m.fit(df, freq="5min")  # validate_each_epoch=True, plot_live_loss=True
```

```python
m.plot_parameters()
```

<figure><img src="https://neuralprophet.com/_images/how-to-guides_feature-guides_sparse_autoregression_yosemite_temps_6_0.svg" alt=""><figcaption></figcaption></figure>

```python
m = m.highlight_nth_step_ahead_of_each_forecast(1)
m.plot_parameters()
```

<figure><img src="https://neuralprophet.com/_images/how-to-guides_feature-guides_sparse_autoregression_yosemite_temps_7_0.svg" alt=""><figcaption></figcaption></figure>

```python
m = m.highlight_nth_step_ahead_of_each_forecast(36)
m.plot_parameters()
```

<figure><img src="https://neuralprophet.com/_images/how-to-guides_feature-guides_sparse_autoregression_yosemite_temps_8_0.svg" alt=""><figcaption></figcaption></figure>

### Дальнейшее снижение ненулевых AR-коэффициентов

Повышая значение `ar_reg`, мы можем дополнительно уменьшить количество ненулевых весов. Здесь мы устанавливаем его равным 1.

```python
m = NeuralProphet(
    n_lags=6 * 12,
    n_forecasts=3 * 12,
    n_changepoints=0,
    daily_seasonality=False,
    weekly_seasonality=False,
    learning_rate=0.01,
    ar_reg=1,
)
m.set_plotting_backend("plotly-static")
metrics = m.fit(df, freq="5min")
```

```python
m.plot_parameters()
```

<figure><img src="https://neuralprophet.com/_images/how-to-guides_feature-guides_sparse_autoregression_yosemite_temps_11_0.svg" alt=""><figcaption></figcaption></figure>

```python
m = m.highlight_nth_step_ahead_of_each_forecast(1)
m.plot_parameters()
```

<figure><img src="https://neuralprophet.com/_images/how-to-guides_feature-guides_sparse_autoregression_yosemite_temps_12_0.svg" alt=""><figcaption></figcaption></figure>

```python
m = m.highlight_nth_step_ahead_of_each_forecast(36)
m.plot_parameters()
```

<figure><img src="https://neuralprophet.com/_images/how-to-guides_feature-guides_sparse_autoregression_yosemite_temps_13_0.svg" alt=""><figcaption></figcaption></figure>

### Крайняя разреженность

Чем выше мы устанавливаем `ar_reg`, тем меньше ненулевых весов учитывается моделью. Здесь мы устанавливаем его равным 10, что должно привести к одному ненулевому лагу.

{% hint style="danger" %}
**Примечание:** Крайние значения могут привести к нестабильности обучения.
{% endhint %}

```python
m = NeuralProphet(
    n_lags=6 * 12,
    n_forecasts=3 * 12,
    n_changepoints=0,
    daily_seasonality=False,
    weekly_seasonality=False,
    learning_rate=0.01,
    ar_reg=10,
)
m.set_plotting_backend("plotly-static")
metrics = m.fit(df, freq="5min")
```

```python
m.plot_parameters()
```

<figure><img src="https://neuralprophet.com/_images/how-to-guides_feature-guides_sparse_autoregression_yosemite_temps_16_0.svg" alt=""><figcaption></figcaption></figure>

```python
m = m.highlight_nth_step_ahead_of_each_forecast(1)
m.plot_parameters()
```

<figure><img src="https://neuralprophet.com/_images/how-to-guides_feature-guides_sparse_autoregression_yosemite_temps_17_0.svg" alt=""><figcaption></figcaption></figure>

```python
m = m.highlight_nth_step_ahead_of_each_forecast(36)
m.plot_parameters()
```

<figure><img src="https://neuralprophet.com/_images/how-to-guides_feature-guides_sparse_autoregression_yosemite_temps_18_0.svg" alt=""><figcaption></figcaption></figure>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://bemind.gitbook.io/neural/neuralprophet/rukovodstva-po-funkciyam/razrezhennaya-avtoregressiya.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
