Skip to content

Instantly share code, notes, and snippets.

@madagra
Last active December 24, 2021 10:31
Show Gist options
  • Save madagra/7db7c7313a580afe7a27bc59e526ec83 to your computer and use it in GitHub Desktop.
Save madagra/7db7c7313a580afe7a27bc59e526ec83 to your computer and use it in GitHub Desktop.
import torch
def f(nn: NNApproximator, x: torch.Tensor) -> torch.Tensor:
"""Compute the value of the approximate solution from the NN model"""
return nn(x)
def df(nn: NNApproximator, x: torch.Tensor = None, order: int = 1) -> torch.Tensor:
"""Compute neural network derivative with respect to the input feature(s) using PyTorch autograd engine"""
df_value = f(nn, x)
for _ in range(order):
df_value = torch.autograd.grad(
df_value,
x,
grad_outputs=torch.ones_like(x),
create_graph=True,
retain_graph=True,
)[0]
return df_value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment