Skip to content

Instantly share code, notes, and snippets.

@sergeyprokudin
Last active April 15, 2024 11:23
Show Gist options
  • Save sergeyprokudin/906df7d5943355d12d3f31f932020108 to your computer and use it in GitHub Desktop.
Save sergeyprokudin/906df7d5943355d12d3f31f932020108 to your computer and use it in GitHub Desktop.
import torch
import torch.nn as nn
def laplacian_smoothing_loss2d(Y_pred):
C, H, W = Y_pred.shape[1], Y_pred.shape[2], Y_pred.shape[3]
kernel = torch.tensor([[0, 1, 0], [1, -4, 1], [0, 1, 0]], device=device, dtype=torch.float32)
kernel = kernel.view(1, 1, 3, 3).repeat(C, 1, 1, 1)
Y_laplacian = nn.functional.conv2d(Y_pred, kernel, groups=C, padding=1)
laplacian_loss = (Y_laplacian ** 2).mean()
return laplacian_loss
def laplacian_smoothing_3d(Y_pred):
C, D, H, W = Y_pred.shape[1], Y_pred.shape[2], Y_pred.shape[3], Y_pred.shape[4]
kernel = torch.tensor([[[[0, 0, 0], [0, 1, 0], [0, 0, 0]],
[[0, 1, 0], [1, -6, 1], [0, 1, 0]],
[[0, 0, 0], [0, 1, 0], [0, 0, 0]]]],
device=device, dtype=torch.float32)
kernel = kernel.view(1, 1, 3, 3, 3).repeat(C, 1, 1, 1, 1)
Y_laplacian = nn.functional.conv3d(Y_pred, kernel, groups=C, padding=1)
laplacian_loss = (Y_laplacian ** 2).mean()
return laplacian_loss
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment