neurite.nn.functional
Tensor operations and functions for Neurite.
This module provides a collection of functions for manipulating and analyzing PyTorch tensors, with applications a focus on imaging. Functions include:
- Basic operations:
identity,mse,reduce - Sampling and quantization:
soft_quantize,subsample,subsample_tensor_random_dims,apply_bernoulli_mask - Filtering and smoothing:
gaussian_smoothing,filter_dim - Geometric transforms:
upsample,resample,resize,affine_to_dense_shift,volshape_to_ndgrid - Label/image utilities:
random_clear_label,sample_image_from_labels - Evaluation metrics:
dice,log_dice
These functions are written in PyTorch (optionally GPU-accelerated) and are designed to interoperate with Neurite’s samplers, layers, and models.
Examples:
>>> import torch
>>> import neurite.nn.functional as nef
>>> x = torch.randn(1, 1, 32, 32, 32)
>>> qx = nef.soft_quantize(x, nb_bins=4, softness=0.5)
>>> sx = nef.gaussian_smoothing(x, kernel_size=5, sigma=1.2)
Notes
- All functions assume tensors follow the (B, C, *spatial_dims) convention.
- Some utilities accept
Samplerobjects fromneurite.samplersfor stochastic behavior.
affine_to_dense_shift
affine_to_dense_shift(affine_a: Tensor, affine_b: Tensor, grid_size: tuple, device: str = 'cpu', dtype: dtype = torch.float32, normalize: bool = True) -> torch.Tensor
Derive a dense displacement field from affine matrices.
| PARAMETER | DESCRIPTION |
|---|---|
affine_a
|
Affine matrix A of shape (batch_size, ndim, ndim + 1), where ndim is 2 or 3.
TYPE:
|
affine_b
|
Affine matrix B of shape (batch_size, ndim, ndim + 1), same shape as affine_A.
TYPE:
|
grid_size
|
Spatial size of the grid, e.g., (H, W) for 2D or (D, H, W) for 3D.
TYPE:
|
device
|
Device for computations, default is 'cpu'.
TYPE:
|
dtype
|
Data type for computations, default is torch.float32.
TYPE:
|
normalize
|
If True, grid coordinates are normalized to [-1, 1]. Default is True.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Dense displacement field of shape (batch_size, ndim, *grid_size), where each vector represents displacement in each dimension from a to b. |
Examples:
Dense displacement field for 2x scaled affines
>>> # Make first affine with ones
>>> aff_a_2d = torch.eye(2, 2 + 1).unsqueeze(0)
>>> # Dilate original affine by 2
>>> aff_b_2d = aff_a_2d * 2
>>> grid_size_2d = (128, 128)
>>> displacement_field = affine_to_dense_shift(
... aff_a_2d, aff_b_2d, grid_size_2d
... )
Source code in neurite/nn/functional.py
apply_bernoulli_mask
Apply a Bernoulli mask to a tensor.
Sample a Bernoulli mask with the parameter p, representing the probability of
success (e.g. realizing a 1) and apply it to input_tensor via element-wise multiplcation. The
The elements of input_tensor corresponding to successes in the mask are preserved, while
failures (e.g. zeros) are set to zero.
| PARAMETER | DESCRIPTION |
|---|---|
input_tensor
|
The input tensor to be masked.
TYPE:
|
p
|
Probability of realizing a success (i.e., the probability of a 1) in the mask. Successes are preserved in the input tensor such that higher values of this parameter correspond to more elements of the input tensor being preserved. By default 0.5. Must be in the range [0, 1].
TYPE:
|
returns
|
Optionally return the subset of the input tensor corresponding to Bernoulli {'successes',
'failures'}. By default None (returns the original tensor with failures set to zero)
- Setting
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Masked tensor with approximately |
Examples:
Standard use case
>>> # Define input tensor. (Filled with ones for demonstration purposes)
>>> input_tensor = torch.ones((1, 32, 32, 32))
>>> # Mask the tensor.
>>> masked_tensor = apply_bernoulli_mask(input_tensor, p=0.9)
>>> # Return the average value of the tensor of ones, approximating the expectation of the mask
>>> # in this special case.
>>> masked_tensor.mean()
Returning successes only (as a flattened tensor representing elements from successful trials)
>>> Define input tensor. (Filled with ones for demonstration purposes)
>>> input_tensor = torch.ones((1, 32, 32, 32))
>>> # Get masked tensor
>>> masked_tensor = apply_bernoulli_mask(input_tensor, p=0.9, returns='successes')
>>> # Compute original shape and masked shape
>>> original_shape, masked_shape = input_tensor.flatten().shape[0], masked_tensor.shape[0]
>>> # Compute difference in size as a percent. Should be ~= `p`
>>> print((masked_shape/original_shape))
Source code in neurite/nn/functional.py
build_normalization
build_normalization(normalization_type: Union[str, Type[Module], Module, None], ndim: Optional[int] = None, num_features: Optional[int] = None, num_groups: Optional[int] = None, eps: float = 1e-05, affine: bool = True, **kwargs) -> nn.Module
Factory for various normalization layers.
| PARAMETER | DESCRIPTION |
|---|---|
normalization_type
|
Type of normalization. Must be one of 'batch', 'instance', 'layer', 'group', or a custom
TYPE:
|
ndim
|
Dimensionality for batch/instance normalization: - 1 -> Norm1d - 2 -> Norm2d - 3 -> *Norm3d Required for 'batch' or 'instance' normalizations.
TYPE:
|
num_features
|
Number of input features or channels. Required for 'batch', 'instance', 'layer', and 'group' normalizations. For layer normalization, this is the size of the normalized dimension. For batch and instance normalizations, this is typically the number of channels/features.
TYPE:
|
num_groups
|
Number of groups for GroupNorm. Required for 'group' normalization.
TYPE:
|
eps
|
A value added to the denominator for numerical stability. Default is 1e-5.
TYPE:
|
affine
|
If True, the layer has learnable affine parameters. Default is True.
TYPE:
|
**kwargs
|
Additional keyword arguments are passed directly to the normalization class constructor. This enables further customization without modifying this class.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Module
|
Configured and initialized normalization layer. |
Examples:
Normalize with a custom normalization layer
Normalize with a custom, uninitialized normalization layer
>>> norm_b = nn.InstanceNorm2d
>>> norm_B = build_normalization(norm_b, num_features=16)
>>> norm_B(x)
...
Normalize with text-based input
>>> norm_C = build_normalization(normalization_type='instance', ndim=2, num_features=16)
>>> norm_C(x)
...
Source code in neurite/nn/functional.py
1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 | |
checkerboard
Generate a checkerboard pattern in 2D or 3D.
This function creates an image with a checkerboard pattern where alternating
squares of size square_size are filled with ones, while the rest remain zero.
| PARAMETER | DESCRIPTION |
|---|---|
image_shape
|
Shape of the output image tensor. The expected format is: - (B, C, H, W) for 2D images - (B, C, D, H, W) for 3D images Default is (1, 1, 16, 16) for a single-channel 2D image.
TYPE:
|
square_size
|
The size of each square in the checkerboard pattern. The default value is 3.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
A tensor of shape |
Example
img = checkerboard((1, 1, 6, 6), square_size=2) img[0, 0] tensor([[1., 1., 0., 0., 1., 1.], [1., 1., 0., 0., 1., 1.], [0., 0., 1., 1., 0., 0.], [0., 0., 1., 1., 0., 0.], [1., 1., 0., 0., 1., 1.], [1., 1., 0., 0., 1., 1.]])
Source code in neurite/nn/functional.py
constant_shift_field
constant_shift_field(shape: tuple = (1, 1, 16, 16), shift_size: int = 1, normalize: bool = False, device: str = 'cpu') -> torch.Tensor
Makes a simple flow field for testing registration in N-dimensional space.
This function generates a flow field with channels that represent the transformations to each spatial dimension. E.g. channel 1 represents the dense transformation on the x-axis, channel 2 represents the dense transformation on the y axis, and so on...
| PARAMETER | DESCRIPTION |
|---|---|
shape
|
Shape of the input tensor, expected as (B, C, *spatial_dims). Default is (1, 1, 4, 4) for a 2D case.
TYPE:
|
shift_size
|
Shift magnitude for each axis. If int, same shift on all axes. If list/tuple, length must equal number of spatial dims. If Tensor, must have shape (n_spatial_dims,). Default is 1.
TYPE:
|
normalize
|
If True, normalize the first spatial channel by (size - 1), where size is the extent of that axis. Default is False.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
flow_field
|
A tensor representing the flow field, shaped as (B, n_spatial_dims, *spatial_dims). The first spatial dimension is shifted by +1 in a normalized manner.
TYPE:
|
Example
flow = constant_shift_field((1, 1, 4, 4), device='cpu') flow.shape torch.Size([1, 2, 4, 4])
flow_3d = constant_shift_field((1, 1, 4, 4, 4), device='cpu') flow_3d.shape torch.Size([1, 3, 4, 4, 4])
Source code in neurite/nn/functional.py
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 | |
crop_to_nearest_multiple
Crop the spatial dimensions of a tensor to the nearest multiple of
multiple. Supports 1D, 2D, or 3D spatial dimensions.
| PARAMETER | DESCRIPTION |
|---|---|
tensor
|
The input tensor with shape (B, C, *spatial_dims), where
TYPE:
|
multiple
|
The multiple to which spatial dimensions are cropped. Default is 128.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
The tensor with spatial dimensions cropped to the nearest multiple of
|
Examples:
>>> import torch
>>> tensor_1d = torch.randn(1, 3, 250) # 1D spatial tensor
>>> cropped_1d = crop_to_nearest_multiple(tensor_1d, multiple=64)
>>> cropped_1d.shape
torch.Size([1, 3, 192])
>>> tensor_2d = torch.randn(1, 3, 250, 330) # 2D spatial tensor
>>> cropped_2d = crop_to_nearest_multiple(tensor_2d, multiple=128)
>>> cropped_2d.shape
torch.Size([1, 3, 128, 256])
>>> tensor_3d = torch.randn(1, 3, 100, 250, 330) # 3D spatial tensor
>>> cropped_3d = crop_to_nearest_multiple(tensor_3d, multiple=64)
>>> cropped_3d.shape
torch.Size([1, 3, 64, 192, 320])
Source code in neurite/nn/functional.py
1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 | |
cross_expand
cross_expand(x1: Tensor, x2: Tensor, return_batched: bool = True) -> Tuple[torch.Tensor, torch.Tensor]
Expands x1 and x2 along new dimensions to create pairwise combinations.
Each slice in x1 is expanded along a new axis to match every slice in x2, and vice versa.
This is essentially just taking the cartesian product of two tensors at their second dimension.
| PARAMETER | DESCRIPTION |
|---|---|
x1
|
Input tensor of shape (B, Sx1, Cx1, ...), where Sx1 is the number of slices or subimages.
TYPE:
|
x2
|
Input tensor of shape (B, Sx2, Cx2, ...), where Sx2 is the number of slices or subimages.
TYPE:
|
return_batched
|
Return paired expanded tensors patched into the batch dimension.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor or Tuple[Tensor, Tensor]
|
|
References
J. G. Ortiz et al., "UniverSeg: Universal Medical Image Segmentation," GitHub repository, 2023. Available: https://github.com/JJGO/UniverSeg
Examples:
Cross expansion of two 2D tensors
>>> x1 = torch.randn(1, 3, 4, 5, 6)
>>> x2 = torch.randn(1, 7, 8, 9, 10)
>>> x1_cross_expanded, x2_cross_expanded = cross_expand(x1, x2)
>>> print(x1_cross_expanded.shape, x2_cross_expanded.shape)
torch.Size([1, 3, 7, 4, 5, 6]) torch.Size([1, 3, 7, 8, 9, 10])
Source code in neurite/nn/functional.py
1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 | |
dice
dice(*segs: Tensor, smooth_numerator: float = 1e-12, smooth_denominator: float = 1e-12, reduction: str = 'mean', reduction_dim: Union[int, Tuple[int, ...]] = (0, 1), keepdims: bool = True) -> torch.Tensor
Compute Dice score over multiple segmentation maps.
| PARAMETER | DESCRIPTION |
|---|---|
*segs
|
Two or more segmentation tensors of shape (B, C, *spatial_dims) with values in [0, 1].
TYPE:
|
smooth_numerator
|
Smoothing constant added to the numerator.
TYPE:
|
smooth_denominator
|
Smoothing constant added to the denominator.
TYPE:
|
reduction
|
The type of reduction to apply. Supported values for multidimensional reductions are: 'mean', 'sum', 'median', 'amax', 'amin', 'std', 'var', 'var_mean'; for single-dimension reductions: 'argmin', 'argmax', and all multidimensionals. Default is 'mean'.
TYPE:
|
reduction_dim
|
Dimension(s) over which to apply the reduction. For multidimensional reductions, pass a tuple of dimensions; for single-dimension reductions, pass an integer. Default is (0, 1)
TYPE:
|
keepdims
|
Whether to retain reduced dimensions as a singleton. Default is True.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Tensor of shape (B, C) whose entries represent the dice score for each batch and class. |
Examples:
Compute dice for 2 segmentation tensors (batch=2, classes=1, H=W=32) with no reduction
>>> seg1 = torch.rand((2, 1, 32, 32))
>>> seg2 = torch.rand((2, 1, 32, 32))
>>> score = dice(seg1, seg2, reduction=None)
>>> print(score.shape)
torch.Size([2, 1])
Compute the dice for three classes (batch=2, classes=3)
>>> segs = [torch.rand((2, 3, 64, 64)) for _ in range(3)]
>>> per_class = dice(*segs, reduction='mean')
>>> print(per_class.shape)
tensor([[0.2487]])
Source code in neurite/nn/functional.py
1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 | |
filter_dim
Filters slices of a tensor that contain NaNs, infinite values, or are entirely zero.
| PARAMETER | DESCRIPTION |
|---|---|
tensor
|
An n-dimensional tensor.
TYPE:
|
verbose
|
If True, prints the number of elements filtered for each condition. Default is False.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
The filtered tensor containing only slice elements without NaNs, infinite values, and not entirely zeros. |
Source code in neurite/nn/functional.py
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 | |
gaussian_smoothing
gaussian_smoothing(input_tensor: Tensor, kernel_size: Union[int, Sampler] = 3, sigma: Union[float, int, Sampler] = 1) -> torch.Tensor
Apply Gaussian smoothing to the {1D, 2D, 3D} input tensor.
| PARAMETER | DESCRIPTION |
|---|---|
input_tensor
|
The input tensor, assumed to be 1D, 2D, or 3D.
TYPE:
|
kernel_size
|
Size of the Gaussian kernel, default is 3.
TYPE:
|
sigma
|
Standard deviation of the Gaussian kernel, default is 1.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
smoothed_tensor
|
The smoothed tensor.
TYPE:
|
Examples:
>>> import torch
# Make an input tensor ~N(1, 0)
>>> input_tensor = torch.rand(1, 1, 16, 16, 16)
# Smooth it
>>> smoothed_tensor = gaussian_smoothing(input_tensor)
Source code in neurite/nn/functional.py
identity
infer_linear_interpolation_mode
Infer the interpolation mode for F.interpolate() from tensor dimensions.
| PARAMETER | DESCRIPTION |
|---|---|
num_spatial
|
Tensor with batch and channel dimensions, and with {1, 2, 3} spatial dimensions.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
mode
|
Interpolation mode string: - 'linear' for 1D - 'bilinear' for 2D - 'trilinear' for 3D
TYPE:
|
Examples:
>>> # Look at output for different number of spatial dims
>>> infer_linear_interpolation_mode(1)
'linear'
>>> infer_linear_interpolation_mode(3)
'trilinear'
Source code in neurite/nn/functional.py
log_dice
log_dice(*segs, smooth_numerator: float = 1e-12, smooth_denominator: float = 1e-12, reduction: str = 'mean', reduction_dim: Union[int, Tuple[int, ...]] = (0, 1), keepdims: bool = True, enforce_valid_probabilities: bool = False) -> torch.Tensor
Compute the Dice coefficient in the log domain given two tensors representing log probabilities.
| PARAMETER | DESCRIPTION |
|---|---|
*segs
|
Two or more segmentation tensors of shape (B, C, *spatial_dims) representing log-probabilities.
TYPE:
|
smooth_numerator
|
Smoothing constant added to the numerator to avoid log(0). By default, 1e-12.
TYPE:
|
smooth_denominator
|
Smoothing constant added to the denominator to avoid log(0). By default, 1e-12.
TYPE:
|
reduction
|
The type of reduction to apply. Supported values for multidimensional reductions are: 'mean', 'sum', 'median', 'amax', 'amin', 'std', 'var', 'var_mean'; for single-dimension reductions: 'argmin', 'argmax', and all multidimensionals. Default is 'mean'.
TYPE:
|
reduction_dim
|
Dimension(s) over which to apply the reduction. For multidimensional reductions, pass a tuple of dimensions; for single-dimension reductions, pass an integer. Default is (0, 1)
TYPE:
|
keepdims
|
Whether to retain reduced dimensions as a singleton. Default is True.
TYPE:
|
enforce_valid_probabilities
|
Ensure input segmentations represent valid probabilities by checking that ensuring exp(seg1) and exp(seg2) sum to 1.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
The Dice coefficient in the log domain over batch and channel dimensions. |
Notes
The Dice coefficient for two probability maps is: Dice(seg1, seg2) = 2 * seg1 * seg2 / (seg1^2 + seg2^2).
In log space, given L_1 = log(seg1) and L_2 = log(seg2): LogDice(L_1, L_2) = log(2) + L_1 + L_2 - log(exp(2 * L_1) + exp(2 * L_2)).
Examples:
>>> # Computing log_dice of random tensors
>>> seg1 = ne.samplers.RandInt(0, 1)((1, 1, 32, 32))
>>> seg2 = ne.samplers.RandInt(0, 1)((1, 1, 32, 32))
>>> log_dice = ne.utils.log_dice(seg1, seg2)
>>> # Expecting log(0.5) ~= -0.69314
>>> log_dice
tensor([[-0.6970]])
>>> # Converting to linear domain, should be about 0.5
>>> torch.exp(log_dice)
tensor([[0.4981]])
Source code in neurite/nn/functional.py
1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 | |
logistic
logistic(logits: Tensor, slope: float = 1.0, lower_asymptote: float = 0.0, upper_asymptote: float = 1.0) -> torch.Tensor
Apply a scaled and shifted logistic function to input logits.
This function computes a generalized logistic (sigmoid) function that maps input logits to a
range bounded by lower_asymptote and upper_asymptote. The slope parameter controls the
steepness of the transition between these asymptotic values.
| PARAMETER | DESCRIPTION |
|---|---|
logits
|
Unnormalized output (score), such as the outputs of a segmentation model.
TYPE:
|
slope
|
The slope of the logistic function. A higher value results in a steeper transition between the asymptotic bounds. Default is 1.0.
TYPE:
|
lower_asymptote
|
The lower bound of output values (asymptote) as logits tend to infinity. Default is 0.0.
TYPE:
|
upper_asymptote
|
The maximum bound output values (asymptote) as logits tend to negative infinity. Default is 1.0.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Result of the logistic function which can be interpreted as probabilities/normalized scores. |
Source code in neurite/nn/functional.py
mse
Calculates the mean squared error (MSE) between the elements of tensor1 and tensor2.
| PARAMETER | DESCRIPTION |
|---|---|
tensor1
|
An input tensor.
TYPE:
|
tensor2
|
A tensor with the same shape as
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
The mean squared error between |
Examples:
>>> import torch
# First tensor with zero mean, unit variance
>>> tensor1 = torch.randn((1, 16, 16, 16))
# Other tensor with zero mean, unit variance, and same shape as `tensor1`
>>> tensor2 = torch.randn((1, 16, 16, 16))
# Calculate mse
>>> mse_value = mse(tensor1, tensor2)
# Print `mse_value` (should be approximately 2.0)
>>> print(mse_value)
Source code in neurite/nn/functional.py
random_clear_label
random_clear_label(input_tensor: Tensor, label_tensor: Tensor, prob: Union[float, int, Sampler] = 0.5, exclude_zero: bool = True, seed: int = None) -> torch.Tensor
Erase regions of an image from randomly selected regions in a label map.
Identify unique labels within the label_tensor and, based on a specified probability,
designate regions of the input_tensor to be erased (set to zero).
| PARAMETER | DESCRIPTION |
|---|---|
input_tensor
|
Image or tensor to clear.
TYPE:
|
label_tensor
|
Label map corresponding to sampling domain from which to select regions for clearing.
TYPE:
|
prob
|
Probability of any label/region being selected for erasure as determined by iid Bernoulli trials, by default 0.5.
TYPE:
|
exclude_zero
|
Optionally exclude zero (uaually background) from the list of potential regions to clear (never clear zero labels), by default True.
TYPE:
|
seed
|
A random seed or sampler to control the randomness of label clearing operations. If provided, it ensures reproducibility of the clearing process. By default, None.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
The modified tensor with specified labels cleared (set to zero). If no labels are cleared,
the original |
Examples:
Clearing labels with a fixed probability
>>> input_tensor = torch.tensor([0.1, 0.2, 0.3, 0.4, 0.5, 0.6])
>>> label_tensor = torch.tensor([1, 2, 3, 4, 5, 6])
>>> cleared_tensor = random_clear_label(input_tensor, label_tensor, prob=0.5)
>>> print(cleared_tensor)
tensor([0.0, 0.0, 0.3, 0.0, 0.5, 0.6])
Excluding label 0 from being cleared
>>> input_tensor = torch.tensor([0.1, 0.2, 0.3, 0.4, 0.5, 0.6])
>>> label_tensor = torch.tensor([0, 0, 0, 0, 0, 0])
>>> cleared_tensor = random_clear_label(input_tensor, label_tensor, prob=1.0, exclude_zero=True)
>>> print(cleared_tensor)
torch.tensor([0.1, 0.2, 0.3, 0.4, 0.5, 0.6])
Reproducibility with a seed
>>> input_tensor = torch.tensor([0.1, 0.2, 0.3, 0.4, 0.5, 0.6])
>>> label_tensor = torch.tensor([1, 2, 3, 4, 5, 6])
>>> cleared_tensor1 = random_clear_label(input_tensor, label_tensor, prob=1.0, seed=42)
>>> cleared_tensor2 = random_clear_label(input_tensor, label_tensor, prob=1.0, seed=42)
>>> print(torch.equal(cleared_tensor1, cleared_tensor2))
True
Source code in neurite/nn/functional.py
665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 | |
random_flip
Randomly flips an image (or set of images) along the given dimension.
| PARAMETER | DESCRIPTION |
|---|---|
dim
|
The dimension along which to flip. Note that the first dimension is the channel dimension.
TYPE:
|
*args
|
The image(s) to flip.
TYPE:
|
prob
|
The probability of flipping the image(s).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor or tuple[Tensor]
|
The flipped image(s). |
Source code in neurite/nn/functional.py
reduce
reduce(tensor: Tensor, reduction: str = 'mean', dim: Union[Tuple[int, ...], int] = None, keepdims: bool = False) -> torch.Tensor
Apply any torch reduction on a tensor.
This function applies a reduction (e.g., mean, sum, median) on the input tensor across one or
more dimensions. For reductions that operate on multiple dimensions, the dim can be
a tuple of dimensions. For reductions that operate on a single dimension (e.g., argmin, argmax),
dim must be an integer.
| PARAMETER | DESCRIPTION |
|---|---|
tensor
|
The input tensor to reduce.
TYPE:
|
reduction
|
The type of reduction to apply. Supported values for multidimensional reductions are: None, 'mean', 'sum', 'median', 'amax', 'amin', 'std', 'var', 'var_mean'; for single dimension reductions: 'argmin', 'argmax', and all multidimensionals. Default is None; all dimensions are reduced to return a scalar.
TYPE:
|
dim
|
Dimension(s) over which to apply the reduction. For multidimensional reductions, pass a tuple of dimensions; for single-dimension reductions, pass an integer. Default is (0, 1).
TYPE:
|
keepdims
|
Whether to retain reduced dimensions as a singleton. Default is False.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
The reduced tensor. |
| RAISES | DESCRIPTION |
|---|---|
AssertionError
|
If a single-dimension reduction (e.g., 'argmin', 'argmax') is requested with a
|
Examples:
>>> # Make a random tensor
>>> input_tensor = torch.randn(3, 4, 128, 128)
>>> # Getting the means from each batch
>>> reduce(input_tensor, reduction='mean', dim=(1, 2, 3))
tensor([-0.0004, -0.0021, -0.0052])
>>> # Getting the largest value from each batch
>>> reduce(input_tensor, reduction='amax', dim=(1, 2, 3))
tensor([4.6618, 3.9218, 4.1831])
Source code in neurite/nn/functional.py
1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 | |
resample
resample(input_tensor: Tensor, resample_dimension: Union[int, List[int]] = None, downsample_stride: Union[int, List[int]] = 2, upsample_scale_factor: Union[Union[int, float], List[Union[int, float]]] = 2, mode: Literal['linear', 'nearest', 'bicubic', 'area', 'nearest-exact'] = 'linear', shape: tuple = None) -> torch.Tensor
Subsample input_tensor by a factor stride, then upsample it by scale_factor.
Combines subsample and upsample by first subsampling input_tensor along a
given dimension by stride, then upsampling back to shape.
| PARAMETER | DESCRIPTION |
|---|---|
input_tensor
|
The tensor to resample.
TYPE:
|
resample_dimension
|
The dimension(s) that should be resampled. If None, all dimensions are resampled. Default is None.
TYPE:
|
downsample_stride
|
Factor by which to subsample. Default is 2.
TYPE:
|
upsample_scale_factor
|
Factor by which to upsample. Default is 2.
TYPE:
|
mode
|
Interpolation mode for upsampling. Options include 'nearest', 'linear', 'bicubic', 'area', and 'nearest-exact'. Default is 'linear'.
TYPE:
|
shape
|
Spatial dimensions (without batch or channel dims) to upsample the subsampled tensor into.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
The resampled tensor with the same batch and channel dims as |
Examples:
>>> import torch
>>> input_tensor = torch.randn(1, 3, 32, 32)
>>> # Subsample rows/cols by 2, then upsample to (64, 64)
>>> res = resample(
... input_tensor, shape=(64, 64),
... subsampling_dimension=2, stride=2,
... mode='bilinear'
... )
>>> print(res.shape)
torch.Size([1, 3, 64, 64])
Source code in neurite/nn/functional.py
resize
resize(image: Tensor, scale_factor: List[float] = None, shape: List[int] = None, nearest: bool = False) -> torch.Tensor
Resize an image with the option of scaling and/or setting to a new shape.
| PARAMETER | DESCRIPTION |
|---|---|
image
|
An input tensor with shape (C, H, W[, D]) to resize.
TYPE:
|
scale_factor
|
Multiplicative factor(s) for scaling the input tensor. If a float, then the same scale factor is applied to all spatial dimensions. If a tuple, then the scaling factor for each dimension should be provided.
TYPE:
|
shape
|
Target shape of the output tensor.
TYPE:
|
nearest
|
If True, use nearest neighbor interpolation. Otherwise, use linear interpolation.
TYPE:
|
Returns:
torch.Tensor
The resized tensor with the shape specified by shape or scaled by scale_factor.
Notes
TODO: This function has numpy operations and other general things (e.g. antialiasing) that Adrian wants to refactor.
Source code in neurite/nn/functional.py
1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 | |
sample_image_from_labels
sample_image_from_labels(label_tensor: Tensor, mean_sampler: Sampler = ne.samplers.Uniform(0, 1), noise_sampler: Sampler = ne.samplers.Normal, noise_variance: Union[float, int, Sampler] = 0.25) -> torch.Tensor
Generate an image from a label map by sampling a random intensity for each label.
Identify all unique integer labels in label_tensor and assigns each a mean intensity in the
corresponding output image (sampled_image). The mean intensity serves as the mean for a noise
distribution modeled by noise_sampler. The variance of the noise model may be a fixed quantity
or sampled from another distribution defined by noise_variance.
| PARAMETER | DESCRIPTION |
|---|---|
label_tensor
|
A tensor with batch and channel dimensions containing integer labels defining distinct regions.
TYPE:
|
mean_sampler
|
A
TYPE:
|
noise_sampler
|
A
TYPE:
|
noise_variance
|
The variance of the noise model. It can be a fixed quantity (int or float), or a sampled
quantity in the case a
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
A tensor of sampled image intensities with the same shape as |
Source code in neurite/nn/functional.py
soft_quantize
soft_quantize(input_tensor: Tensor, nb_bins: int = 16, softness: Union[float, int] = 1.0, min_clip: Union[float, int] = -float('inf'), max_clip: Union[float, int] = float('inf'), return_log: bool = False) -> torch.Tensor
Quantize continuous values into discrete bins.
Instead of assigning each value to a single bin, use a soft assignment based on the distance between each value and the bin centers. Particularly useful for taking gradients during quantization.
| PARAMETER | DESCRIPTION |
|---|---|
input_tensor
|
Input tensor to softly quantize.
TYPE:
|
nb_bins
|
The number of discrete bins to softly quantize the input values into. By default, 16
TYPE:
|
softness
|
The softness factor for quantization. A higher value gives smoother quantization. By default 1.0
TYPE:
|
min_clip
|
Clip data lower than this value before calculating bin centers. By default
TYPE:
|
max_clip
|
Clip data higher than this value before calculating bin centers. By default
TYPE:
|
return_log
|
Optionally return the log of the softly quantized tensor. By default False
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Softly quantized tensor with the same dimensions as |
Examples:
>>> import torch
>>> import matplotlib.pyplot as plt
# Make a random 3D tensor with zero mean and unit variance.
>>> input_tensor = torch.randn(1, 1, 32, 32, 32)
# Compute the softly quantized tensor with a low softness to approximate (and visualize) a
# pseudo-hard quantization.
>>> softly_quantized_tensor = soft_quantize(input_tensor, nb_bins=4, softness=0.5)
# Visualize the softly quantized tensor.
>>> plt.imshow(softly_quantized_tensor[0, 0, 16])
Source code in neurite/nn/functional.py
subsample
subsample(input_tensor: Tensor, stride: Union[List, Tuple, int, None] = 2, subsampling_dimension: Union[List, Literal[0, 1, 2], int, None] = None) -> torch.Tensor
Subsamples input_tensor by a factor stride along the specified dimension.
Downsample a specified dimension of a PyTorch tensor by a given stride. This is achieved by
interleaving dropouts, meaning that every stride-th element along the selected dimension is
kept, while the others are discarded.
| PARAMETER | DESCRIPTION |
|---|---|
input_tensor
|
The tensor to sample from.
TYPE:
|
subsampling_dimension
|
The dimension (or axis) along which the subsampling will occur. By default 0.
TYPE:
|
stride
|
Factor by which to subsample (interleave dropouts). By default 2.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
subsampled_tensor
|
Tensor that has been subsampled.
TYPE:
|
Examples:
>>> import torch
# Define 2D tensor of shape (5, 5)
>>> input_tensor = torch.arange(25).view(5, 5)
# Visualize the tensor
>>> print(input_tensor)
tensor([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]])
# Subsample along the first dimension (the columns)
>>> subsampled_tensor = subsample(input_tensor, subsampling_dimension=1)
# With the default stride (of 2), every other column should have been dropped out.
>>> print(subsampled_tensor)
tensor([[ 0, 2, 4],
[ 5, 7, 9],
[10, 12, 14],
[15, 17, 19],
[20, 22, 24]])
# We could, of course, keep the default `subsampling_dimension=0` and subsample the rows:
>>> subsampled_tensor = subsample(input_tensor, subsampling_dimension=1)
>>> print(subsampled_tensor)
tensor([[ 0, 1, 2, 3, 4],
[10, 11, 12, 13, 14],
[20, 21, 22, 23, 24]])
Source code in neurite/nn/functional.py
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 | |
subsample_tensor_random_dims
subsample_tensor_random_dims(input_tensor: Tensor, stride: int = 2, forbidden_dims: list = (0, 1), p: float = 0.5, max_concurrent_subsamplings: int = None) -> torch.Tensor
Subsample the input tensor along randomly selected dimensions
This extends neurite.utils.subsample() by applying constraints on which dimensions to
subsample (forbidden_dims), the stride, and the probability of subsampling.
| PARAMETER | DESCRIPTION |
|---|---|
input_tensor
|
The input tensor to be subsampled. Assumed to have batch and channel dimensions.
TYPE:
|
stride
|
The stride value to use when subsampling a given dimension. By default, 2. - A stride of 1 does not result in any subsampling. - A stride of 2 will reduce the elements of the selected dimension by 1/2.
TYPE:
|
forbidden_dims
|
A list of dimensions that should not be subsampled. If None, no dimensions are forbidden from subsampling. Default is (0, 1) to ignore batch and channel dimensions.
TYPE:
|
p
|
The probability of selecting each dimension for subsampling. This probability is applied as an independent Bernoulli trial for each dimension. By default, 0.5.
TYPE:
|
max_concurrent_subsamplings
|
The maximum number of dimensions that can be subsampled simultaneously. If
None, the number of concurrent subsamplings is set to the number of dimensions
in
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
The subsampled tensor after applying the specified dimensional subsampling. |
Examples:
>>> import torch
>>> # Define input tensor with batch and channel dimensions, and spatial dims=(5, 5)
>>> input_tensor = torch.arange(25).view(1, 1, 5, 5)
>>> # Visualize the tensor
>>> print(input_tensor)
tensor([[[[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]]]])
>>> # Subsample the tensor. This may now (randomly) subsample more than one dimension.
>>> subsampled_tensor = subsample_tensor_random_dims(input_tensor)
>>> print(subsampled_tensor)
tensor([[[[ 0, 3],
[10, 13],
[20, 23]]]])
>>> # Subsample by defining the stride range.
>>> subsampled_tensor = subsample_tensor_random_dims(input_tensor, stride=4)
>>> print(subsampled_tensor)
tensor([[[[ 0, 4],
[20, 24]]]])
Source code in neurite/nn/functional.py
426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 | |
upsample
upsample(input_tensor: Tensor, mode: Literal['linear', 'nearest', 'bicubic', 'area', 'nearest-exact'] = 'linear', scale_factor: float = 2, shape: tuple = None) -> torch.Tensor
Upsamples 1D, 2D, or 3D tensors to a given shape.
| PARAMETER | DESCRIPTION |
|---|---|
input_tensor
|
The input tensor to be upsampled. Assumed to have batch and channel dimensions.
TYPE:
|
shape
|
Spatial dimensions (without batch or channel dimensions) to upsample
TYPE:
|
mode
|
Interpolation mode for upsampling. Options include 'nearest', 'linear', 'bicubic', 'area', and 'nearest-exact'. Default is 'linear'.
TYPE:
|
Examples:
>>> # 2D Upsampling
>>> input_tensor = torch.randn(1, 3, 32, 32) # (B, C, H, W)
>>> upsampled_tensor = upsample(input_tensor, shape=(64, 64), mode='bilinear')
>>> print(upsampled_tensor.shape)
torch.Size([1, 3, 64, 64])
>>> # 3D Upsampling
>>> input_tensor = torch.randn(1, 3, 32, 32, 32) # (B, C, D, H, W)
>>> upsampled_tensor = upsample(input_tensor, shape=(64, 64, 64), mode='bilinear')
>>> print(upsampled_tensor.shape)
torch.Size([1, 3, 64, 64, 64])
Source code in neurite/nn/functional.py
volshape_to_ndgrid
volshape_to_ndgrid(size: Tuple[int], device: Union[str, device] = 'cpu', dtype: Union[str, dtype] = torch.float32, normalize: bool = False, indexing: Literal['ij', 'xy'] = 'ij') -> torch.Tensor
Generate a grid of spatial coordinates.
Define the coordinate axes by generating vectors for each spatial dimension represented by the
elements of shape, then creates a grid representing all spatial coords.
| PARAMETER | DESCRIPTION |
|---|---|
size
|
Size of the spatial dimensions of the input tensor. e.g. (H, W) or (D, W, H)
TYPE:
|
device
|
The device on which the grid will reside. By default "cpu"
TYPE:
|
dtype
|
The data type of the tensor grid, by default
TYPE:
|
indexing
|
Indexing mode passed to
TYPE:
|
normalize
|
Normalize each dimension of the grid to the range [-1, 1]. Otherwise, the grid coords span
from 0 to
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
A tensor of shape |
Examples:
Make a 2d grid of size (3, 2)
>>> the_grid = volshape_to_ndgrid(size=(3, 2))
>>> print(the_grid.shape)
torch.Size([1, 2, 3, 2])
>>> print(the_grid)
tensor([[[[-1., -1.],
[ 0., 0.],
[ 1., 1.]],
[[-1., 1.],
[-1., 1.],
[-1., 1.]]]])