Skip to content

Commit

Permalink
[MNT] update nbeats/sub_modules.py to remove overhead in tensor creat…
Browse files Browse the repository at this point in the history
…ion (#1580)

This commit  removes a warning raised by nbeats/sub_module.py: 
`UserWarning: Creating a tensor from a list of numpy.ndarrays is
extremely slow. Please consider converting the list to a single
numpy.ndarray with numpy.array() before converting to a tensor.`
This commit replaces the relevant sections with the appropriate code to
remove the warning in the nbeats submodule. (similar to
#754)

Co-authored-by: Felix Hirwa Nshuti <[email protected]>
  • Loading branch information
d-schmitt and fnhirwa authored Jan 6, 2025
1 parent 18153aa commit 1331d57
Showing 1 changed file with 9 additions and 20 deletions.
29 changes: 9 additions & 20 deletions pytorch_forecasting/models/nbeats/sub_modules.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,33 +111,21 @@ def __init__(
else (thetas_dim // 2, thetas_dim // 2 + 1)
)
s1_b = torch.tensor(
[
np.cos(2 * np.pi * i * backcast_linspace)
for i in self.get_frequencies(p1)
],
np.cos(2 * np.pi * self.get_frequencies(p1)[:, None] * backcast_linspace),
dtype=torch.float32,
) # H/2-1
s2_b = torch.tensor(
[
np.sin(2 * np.pi * i * backcast_linspace)
for i in self.get_frequencies(p2)
],
np.sin(2 * np.pi * self.get_frequencies(p2)[:, None] * backcast_linspace),
dtype=torch.float32,
)
self.register_buffer("S_backcast", torch.cat([s1_b, s2_b]))

s1_f = torch.tensor(
[
np.cos(2 * np.pi * i * forecast_linspace)
for i in self.get_frequencies(p1)
],
np.cos(2 * np.pi * self.get_frequencies(p1)[:, None] * forecast_linspace),
dtype=torch.float32,
) # H/2-1
s2_f = torch.tensor(
[
np.sin(2 * np.pi * i * forecast_linspace)
for i in self.get_frequencies(p2)
],
np.sin(2 * np.pi * self.get_frequencies(p2)[:, None] * forecast_linspace),
dtype=torch.float32,
)
self.register_buffer("S_forecast", torch.cat([s1_f, s2_f]))
Expand Down Expand Up @@ -183,14 +171,15 @@ def __init__(
norm = np.sqrt(
forecast_length / thetas_dim
) # ensure range of predictions is comparable to input

thetas_dims_range = np.array(range(thetas_dim))
coefficients = torch.tensor(
[backcast_linspace**i for i in range(thetas_dim)], dtype=torch.float32
backcast_linspace ** thetas_dims_range[:, None],
dtype=torch.float32,
)
self.register_buffer("T_backcast", coefficients * norm)

coefficients = torch.tensor(
[forecast_linspace**i for i in range(thetas_dim)], dtype=torch.float32
forecast_linspace ** thetas_dims_range[:, None],
dtype=torch.float32,
)
self.register_buffer("T_forecast", coefficients * norm)

Expand Down

0 comments on commit 1331d57

Please sign in to comment.