Last active
February 21, 2022 12:14
-
-
Save ptrblck/4dfd97f487c469d01a4aa8d738c893ea to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import torch | |
import torch.nn as nn | |
import torch.nn.functional as F | |
import matplotlib.pyplot as plt | |
output = F.log_softmax(torch.randn(1, 3, 24, 24), 1) | |
target = torch.zeros(1, 24, 24, dtype=torch.long) | |
target[0, 4:12, 4:12] = 1 | |
target[0, 14:20, 14:20] = 2 | |
# Edge calculation | |
bin_target = torch.where(target > 0, torch.tensor(1), torch.tensor(0)) | |
plt.imshow(bin_target[0]) | |
o = F.avg_pool2d(bin_target.float(), kernel_size=3, padding=1, stride=1) | |
plt.imshow(o[0]) | |
edge_idx = (o.ge(0.01) * o.le(0.99)).float() | |
plt.imshow(edge_idx[0]) | |
weights = torch.ones_like(edge_idx, dtype=torch.float) | |
weights_sum0 = weights.sum() | |
weights = weights + edge_idx * 2. | |
weights_sum1 = weights.sum() | |
weights = weights / weights_sum1 * weights_sum0 # Rescale weigths | |
plt.imshow(weights[0]) | |
# Calculate loss | |
criterion = nn.NLLLoss(reduce=False) | |
loss = criterion(output, target) | |
loss = loss * weights | |
loss = loss.sum() / weights.sum() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment