Skip to content

Instantly share code, notes, and snippets.

@madagra
Last active December 25, 2022 11:46
Show Gist options
  • Save madagra/2c710ff3d9e936d9a206d0ca517ef073 to your computer and use it in GitHub Desktop.
Save madagra/2c710ff3d9e936d9a206d0ca517ef073 to your computer and use it in GitHub Desktop.
Loss function with physics-informed machine learning
import torch
import torch.nn as nn
R = 1.0 # rate of maximum population growth parameterizing the equation
X_BOUNDARY = 0.0 # boundary condition coordinate
F_BOUNDARY = 0.5 # boundary condition value
def loss_fn(params: torch.Tensor, x: torch.Tensor) -> torch.Tensor:
# interior loss
f_value = f(x, params)
interior = dfdx(x, params) - R * f_value * (1 - f_value)
# boundary loss
x0 = X_BOUNDARY
f0 = F_BOUNDARY
x_boundary = torch.tensor([x0])
f_boundary = torch.tensor([f0])
boundary = f(x_boundary, params) - f_boundary
loss = nn.MSELoss()
loss_value = loss(interior, torch.zeros_like(interior)) + loss(
boundary, torch.zeros_like(boundary)
)
return loss_value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment