index int64 0 50.7k | project_path stringclasses 279
values | completion_path stringlengths 57 199 | signature_postion stringlengths 3 11 | class_position stringlengths 3 11 | function_name stringlengths 1 62 | class_name stringlengths 0 55 | body_position stringlengths 3 11 | body_position_with_comments stringlengths 3 11 | masked_class stringlengths 14 8.32k | masked_class_with_comment stringlengths 14 8.32k | func_body stringlengths 9 6.72k | func_body_with_comment stringlengths 9 6.72k | len_func_body int64 1 643 | len_input int64 10 2.02k | len_output int64 4 1.9k | total int64 20 2.05k | file_code stringlengths 14 442k | file_code_with_comment stringlengths 14 442k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
29,640 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/functional/pairwise/euclidean.py | 47,53 | 1,90 | pairwise_euclidean_distance | 53,90 | 53,90 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | r"""Calculate pairwise euclidean distances.
.. math::
d_{euc}(x,y) = ||x - y||_2 = \sqrt{\sum_{d=1}^D (x_d - y_d)^2}
If both :math:`x` and :math:`y` are passed in, the calculation will be performed pairwise between
the rows of :math:`x` and :math:`y`.
If only :math:`x` is passed in, the ca... | r"""Calculate pairwise euclidean distances.
.. math::
d_{euc}(x,y) = ||x - y||_2 = \sqrt{\sum_{d=1}^D (x_d - y_d)^2}
If both :math:`x` and :math:`y` are passed in, the calculation will be performed pairwise between
the rows of :math:`x` and :math:`y`.
If only :math:`x` is passed in, the ca... | 192 | 584 | 662 | 1,246 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | |
29,641 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/functional/pairwise/helpers.py | 19,22 | 1,61 | _check_input | 30,46 | 22,46 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | if x.ndim != 2:
raise ValueError(f"Expected argument `x` to be a 2D tensor of shape `[N, d]` but got {x.shape}")
if y is not None:
if y.ndim != 2 or y.shape[1] != x.shape[1]:
raise ValueError(
"Expected argument `y` to be a 2D tensor of shape `[M, d]` where"
... | """Check that input has the right dimensionality and sets the ``zero_diagonal`` argument if user has not set it.
Args:
x: tensor of shape ``[N,d]``
y: if provided, a tensor of shape ``[M,d]``
zero_diagonal: determines if the diagonal of the distance matrix should be set to zero
"""... | 86 | 484 | 216 | 700 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | |
29,642 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/functional/pairwise/linear.py | 42,48 | 1,85 | pairwise_linear_similarity | 48,85 | 48,85 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | r"""Calculate pairwise linear similarity.
.. math::
s_{lin}(x,y) = <x,y> = \sum_{d=1}^D x_d \cdot y_d
If both :math:`x` and :math:`y` are passed in, the calculation will be performed pairwise between
the rows of :math:`x` and :math:`y`.
If only :math:`x` is passed in, the calculation will ... | r"""Calculate pairwise linear similarity.
.. math::
s_{lin}(x,y) = <x,y> = \sum_{d=1}^D x_d \cdot y_d
If both :math:`x` and :math:`y` are passed in, the calculation will be performed pairwise between
the rows of :math:`x` and :math:`y`.
If only :math:`x` is passed in, the calculation will ... | 194 | 485 | 593 | 1,078 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | |
29,643 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/functional/pairwise/manhattan.py | 41,47 | 1,84 | pairwise_manhattan_distance | 47,84 | 47,84 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | r"""Calculate pairwise manhattan distance.
.. math::
d_{man}(x,y) = ||x-y||_1 = \sum_{d=1}^D |x_d - y_d|
If both :math:`x` and :math:`y` are passed in, the calculation will be performed pairwise between
the rows of :math:`x` and :math:`y`.
If only :math:`x` is passed in, the calculation wi... | r"""Calculate pairwise manhattan distance.
.. math::
d_{man}(x,y) = ||x-y||_1 = \sum_{d=1}^D |x_d - y_d|
If both :math:`x` and :math:`y` are passed in, the calculation will be performed pairwise between
the rows of :math:`x` and :math:`y`.
If only :math:`x` is passed in, the calculation wi... | 192 | 504 | 589 | 1,093 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | |
29,644 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/functional/pairwise/minkowski.py | 24,27 | 1,94 | _pairwise_minkowski_distance_update | 36,49 | 27,49 | # Copyright The PyTorch Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | # Copyright The PyTorch Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | x, y, zero_diagonal = _check_input(x, y, zero_diagonal)
if not (isinstance(exponent, (float, int)) and exponent >= 1):
raise TorchMetricsUserError(f"Argument ``p`` must be a float or int greater than 1, but got {exponent}")
# upcast to float64 to prevent precision issues
_orig_dtype = x.dtype
... | """Calculate the pairwise minkowski distance matrix.
Args:
x: tensor of shape ``[N,d]``
y: tensor of shape ``[M,d]``
exponent: int or float larger than 1, exponent to which the difference between preds and target is to be raised
zero_diagonal: determines if the diagonal of the d... | 60 | 1,141 | 223 | 1,364 | # Copyright The PyTorch Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | # Copyright The PyTorch Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | |
29,645 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/functional/regression/concordance.py | 33,34 | 1,69 | concordance_corrcoef | 34,69 | 34,69 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | r"""Compute concordance correlation coefficient that measures the agreement between two variables.
.. math::
\rho_c = \frac{2 \rho \sigma_x \sigma_y}{\sigma_x^2 + \sigma_y^2 + (\mu_x - \mu_y)^2}
where :math:`\mu_x, \mu_y` is the means for the two variables, :math:`\sigma_x^2, \sigma_y^2` are the c... | r"""Compute concordance correlation coefficient that measures the agreement between two variables.
.. math::
\rho_c = \frac{2 \rho \sigma_x \sigma_y}{\sigma_x^2 + \sigma_y^2 + (\mu_x - \mu_y)^2}
where :math:`\mu_x, \mu_y` is the means for the two variables, :math:`\sigma_x^2, \sigma_y^2` are the c... | 175 | 417 | 669 | 1,086 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | |
29,646 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/functional/regression/cosine_similarity.py | 45,46 | 1,102 | _cosine_similarity_compute | 62,75 | 46,75 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | dot_product = (preds * target).sum(dim=-1)
preds_norm = preds.norm(dim=-1)
target_norm = target.norm(dim=-1)
similarity = dot_product / (preds_norm * target_norm)
reduction_mapping = {
"sum": torch.sum,
"mean": torch.mean,
"none": lambda x: x,
None: lambda x: x,
}... | """Compute Cosine Similarity.
Args:
preds: Predicted tensor
target: Ground truth tensor
reduction:
The method of reducing along the batch dimension using sum, mean or taking the individual scores
Example:
>>> target = torch.tensor([[1, 2, 3, 4], [1, 2, 3, 4]])
... | 39 | 1,061 | 156 | 1,217 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | |
29,647 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/functional/regression/csi.py | 23,26 | 1,113 | _critical_success_index_update | 37,61 | 26,61 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | _check_same_shape(preds, target)
if keep_sequence_dim is None:
sum_dims = None
elif not 0 <= keep_sequence_dim < preds.ndim:
raise ValueError(f"Expected keep_sequence dim to be in range [0, {preds.ndim}] but got {keep_sequence_dim}")
else:
sum_dims = tuple(i for i in range(preds... | """Update and return variables required to compute Critical Success Index. Checks for same shape of tensors.
Args:
preds: Predicted tensor
target: Ground truth tensor
threshold: Values above or equal to threshold are replaced with 1, below by 0
keep_sequence_dim: Index of the se... | 108 | 1,158 | 391 | 1,549 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | |
29,648 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/functional/regression/explained_variance.py | 25,26 | 1,142 | _explained_variance_update | 33,46 | 26,46 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | _check_same_shape(preds, target)
num_obs = preds.size(0)
sum_error = torch.sum(target - preds, dim=0)
diff = target - preds
sum_squared_error = torch.sum(diff * diff, dim=0)
sum_target = torch.sum(target, dim=0)
sum_squared_target = torch.sum(target * target, dim=0)
return num_obs, su... | """Update and returns variables required to compute Explained Variance. Checks for same shape of input tensors.
Args:
preds: Predicted tensor
target: Ground truth tensor
"""
_check_same_shape(preds, target)
num_obs = preds.size(0)
sum_error = torch.sum(target - preds, dim=0)
... | 38 | 1,618 | 162 | 1,780 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | |
29,650 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/functional/regression/kendall.py | 33,35 | 26,38 | _name | _MetricVariant | 35,38 | 35,38 | class _MetricVariant(EnumStr):
"""Enumerate for metric variants."""
A = "a"
B = "b"
C = "c"
@staticmethod
def _name() -> str:
FILL_FUNC_BODY | class _MetricVariant(EnumStr):
"""Enumerate for metric variants."""
A = "a"
B = "b"
C = "c"
@staticmethod
def _name() -> str:
FILL_FUNC_BODY | return "variant"
| return "variant"
| 2 | 68 | 11 | 79 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... |
29,651 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/functional/regression/kendall.py | 45,47 | 38,50 | _name | _TestAlternative | 47,50 | 47,50 | class _TestAlternative(EnumStr):
"""Enumerate for test alternative options."""
TWO_SIDED = "two-sided"
LESS = "less"
GREATER = "greater"
@staticmethod
def _name() -> str:
FILL_FUNC_BODY | class _TestAlternative(EnumStr):
"""Enumerate for test alternative options."""
TWO_SIDED = "two-sided"
LESS = "less"
GREATER = "greater"
@staticmethod
def _name() -> str:
FILL_FUNC_BODY | return "alternative"
| return "alternative"
| 2 | 80 | 12 | 92 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... |
29,652 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/functional/regression/kl_divergence.py | 83,86 | 1,134 | kl_divergence | 86,134 | 86,134 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | r"""Compute `KL divergence`_.
.. math::
D_{KL}(P||Q) = \sum_{x\in\mathcal{X}} P(x) \log\frac{P(x)}{Q{x}}
Where :math:`P` and :math:`Q` are probability distributions where :math:`P` usually represents a distribution
over data and :math:`Q` is often a prior or approximation of :math:`P`. It shou... | r"""Compute `KL divergence`_.
.. math::
D_{KL}(P||Q) = \sum_{x\in\mathcal{X}} P(x) \log\frac{P(x)}{Q{x}}
Where :math:`P` and :math:`Q` are probability distributions where :math:`P` usually represents a distribution
over data and :math:`Q` is often a prior or approximation of :math:`P`. It shou... | 357 | 1,002 | 868 | 1,870 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | |
29,653 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/functional/regression/log_cosh.py | 64,65 | 1,97 | log_cosh_error | 65,97 | 65,97 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | r"""Compute the `LogCosh Error`_.
.. math:: \text{LogCoshError} = \log\left(\frac{\exp(\hat{y} - y) + \exp(\hat{y - y})}{2}\right)
Where :math:`y` is a tensor of target values, and :math:`\hat{y}` is a tensor of predictions.
Args:
preds: estimated labels with shape ``(batch_size,)`` or `(batc... | r"""Compute the `LogCosh Error`_.
.. math:: \text{LogCoshError} = \log\left(\frac{\exp(\hat{y} - y) + \exp(\hat{y - y})}{2}\right)
Where :math:`y` is a tensor of target values, and :math:`\hat{y}` is a tensor of predictions.
Args:
preds: estimated labels with shape ``(batch_size,)`` or `(batc... | 133 | 725 | 563 | 1,288 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | |
29,654 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/functional/regression/log_mse.py | 22,23 | 1,77 | _mean_squared_log_error_update | 30,35 | 23,35 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | _check_same_shape(preds, target)
sum_squared_log_error = torch.sum(torch.pow(torch.log1p(preds) - torch.log1p(target), 2))
return sum_squared_log_error, target.numel()
| """Return variables required to compute Mean Squared Log Error. Checks for same shape of tensors.
Args:
preds: Predicted tensor
target: Ground truth tensor
"""
_check_same_shape(preds, target)
sum_squared_log_error = torch.sum(torch.pow(torch.log1p(preds) - torch.log1p(target), 2))... | 11 | 789 | 82 | 871 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | |
29,655 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/functional/regression/mae.py | 22,23 | 1,77 | _mean_absolute_error_update | 32,39 | 23,39 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | _check_same_shape(preds, target)
preds = preds if preds.is_floating_point else preds.float() # type: ignore[truthy-function] # todo
target = target if target.is_floating_point else target.float() # type: ignore[truthy-function] # todo
sum_abs_error = torch.sum(torch.abs(preds - target))
return sum... | """Update and returns variables required to compute Mean Absolute Error.
Check for same shape of input tensors.
Args:
preds: Predicted tensor
target: Ground truth tensor
"""
_check_same_shape(preds, target)
preds = preds if preds.is_floating_point else preds.float() # type: i... | 34 | 712 | 128 | 840 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | |
29,656 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/functional/regression/mape.py | 69,70 | 1,92 | mean_absolute_percentage_error | 90,92 | 70,92 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | sum_abs_per_error, num_obs = _mean_absolute_percentage_error_update(preds, target)
return _mean_absolute_percentage_error_compute(sum_abs_per_error, num_obs)
| """Compute mean absolute percentage error.
Args:
preds: estimated labels
target: ground truth labels
Return:
Tensor with MAPE
Note:
The epsilon value is taken from `scikit-learn's implementation of MAPE`_.
Example:
>>> from torchmetrics.functional.regressi... | 8 | 926 | 62 | 988 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | |
29,657 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/functional/regression/minkowski.py | 59,60 | 1,85 | minkowski_distance | 60,85 | 60,85 | # Copyright The PyTorch Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | # Copyright The PyTorch Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | r"""Compute the `Minkowski distance`_.
.. math:: d_{\text{Minkowski}} = \\sum_{i}^N (| y_i - \\hat{y_i} |^p)^\frac{1}{p}
This metric can be seen as generalized version of the standard euclidean distance which corresponds to minkowski
distance with p=2.
Args:
preds: estimated labels of typ... | r"""Compute the `Minkowski distance`_.
.. math:: d_{\text{Minkowski}} = \\sum_{i}^N (| y_i - \\hat{y_i} |^p)^\frac{1}{p}
This metric can be seen as generalized version of the standard euclidean distance which corresponds to minkowski
distance with p=2.
Args:
preds: estimated labels of typ... | 108 | 649 | 350 | 999 | # Copyright The PyTorch Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | # Copyright The PyTorch Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | |
29,658 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/functional/regression/mse.py | 42,43 | 1,83 | _mean_squared_error_compute | 58,61 | 43,61 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | return sum_squared_error / num_obs if squared else torch.sqrt(sum_squared_error / num_obs)
| """Compute Mean Squared Error.
Args:
sum_squared_error: Sum of square of errors over all observations
num_obs: Number of predictions or observations
squared: Returns RMSE value if set to False.
Example:
>>> preds = torch.tensor([0., 1, 2, 3])
>>> target = torch.tens... | 10 | 910 | 38 | 948 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | |
29,659 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/functional/regression/pearson.py | 25,36 | 1,147 | _pearson_corrcoef_update | 52,80 | 36,80 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Data checking
_check_same_shape(preds, target)
_check_data_shape_to_num_outputs(preds, target, num_outputs)
num_obs = preds.shape[0]
cond = num_prior.mean() > 0 or num_obs == 1
if cond:
mx_new = (num_prior * mean_x + preds.sum(0)) / (num_prior + num_obs)
my_new = (num_prior * ... | """Update and returns variables required to compute Pearson Correlation Coefficient.
Check for same shape of input tensors.
Args:
preds: estimated scores
target: ground truth scores
mean_x: current mean estimate of x tensor
mean_y: current mean estimate of y tensor
... | 111 | 1,493 | 415 | 1,908 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | |
29,661 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/functional/regression/rse.py | 22,29 | 1,81 | _relative_squared_error_compute | 47,54 | 29,54 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | epsilon = torch.finfo(sum_squared_error.dtype).eps
rse = sum_squared_error / torch.clamp(sum_squared_obs - sum_obs * sum_obs / num_obs, min=epsilon)
if not squared:
rse = torch.sqrt(rse)
return torch.mean(rse)
| """Computes Relative Squared Error.
Args:
sum_squared_obs: Sum of square of all observations
sum_obs: Sum of all observations
sum_squared_error: Residual sum of squares
num_obs: Number of predictions or observations
squared: Returns RRSE value if set to False.
Examp... | 23 | 927 | 103 | 1,030 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | |
29,662 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/functional/regression/spearman.py | 112,113 | 1,142 | spearman_corrcoef | 113,142 | 113,142 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | r"""Compute `spearmans rank correlation coefficient`_.
.. math:
r_s = = \frac{cov(rg_x, rg_y)}{\sigma_{rg_x} * \sigma_{rg_y}}
where :math:`rg_x` and :math:`rg_y` are the rank associated to the variables x and y. Spearmans correlations
coefficient corresponds to the standard pearsons correlatio... | r"""Compute `spearmans rank correlation coefficient`_.
.. math:
r_s = = \frac{cov(rg_x, rg_y)}{\sigma_{rg_x} * \sigma_{rg_y}}
where :math:`rg_x` and :math:`rg_y` are the rank associated to the variables x and y. Spearmans correlations
coefficient corresponds to the standard pearsons correlatio... | 122 | 1,339 | 458 | 1,797 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | |
29,663 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/functional/regression/symmetric_mape.py | 68,69 | 1,98 | symmetric_mean_absolute_percentage_error | 69,98 | 69,98 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | r"""Compute symmetric mean absolute percentage error (SMAPE_).
.. math:: \text{SMAPE} = \frac{2}{n}\sum_1^n\frac{| y_i - \hat{y_i} |}{max(| y_i | + | \hat{y_i} |, \epsilon)}
Where :math:`y` is a tensor of target values, and :math:`\hat{y}` is a tensor of predictions.
Args:
preds: estimated ... | r"""Compute symmetric mean absolute percentage error (SMAPE_).
.. math:: \text{SMAPE} = \frac{2}{n}\sum_1^n\frac{| y_i - \hat{y_i} |}{max(| y_i | + | \hat{y_i} |, \epsilon)}
Where :math:`y` is a tensor of target values, and :math:`\hat{y}` is a tensor of predictions.
Args:
preds: estimated ... | 85 | 762 | 371 | 1,133 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | |
29,665 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/functional/regression/utils.py | 17,20 | 1,44 | _check_data_shape_to_num_outputs | 30,44 | 20,44 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | if preds.ndim > 2 or target.ndim > 2:
raise ValueError(
f"Expected both predictions and target to be either 1- or 2-dimensional tensors,"
f" but got {target.ndim} and {preds.ndim}."
)
cond1 = False
if not allow_1d_reshape:
cond1 = num_outputs == 1 and not (pre... | """Check that predictions and target have the correct shape, else raise error.
Args:
preds: Predicted tensor
target: Ground truth tensor
num_outputs: Number of outputs in multioutput setting
allow_1d_reshape: Allow that for num_outputs=1 that preds and target does not need to be... | 85 | 334 | 228 | 562 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | |
29,666 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/functional/regression/wmape.py | 59,60 | 1,87 | weighted_mean_absolute_percentage_error | 60,87 | 60,87 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | r"""Compute weighted mean absolute percentage error (`WMAPE`_).
The output of WMAPE metric is a non-negative floating point, where the optimal value is 0. It is computes as:
.. math::
\text{WMAPE} = \frac{\sum_{t=1}^n | y_t - \hat{y}_t | }{\sum_{t=1}^n |y_t| }
Where :math:`y` is a tensor of t... | r"""Compute weighted mean absolute percentage error (`WMAPE`_).
The output of WMAPE metric is a non-negative floating point, where the optimal value is 0. It is computes as:
.. math::
\text{WMAPE} = \frac{\sum_{t=1}^n | y_t - \hat{y}_t | }{\sum_{t=1}^n |y_t| }
Where :math:`y` is a tensor of t... | 96 | 541 | 354 | 895 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | |
29,667 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/functional/retrieval/_deprecated.py | 73,76 | 1,150 | _retrieval_precision | 85,89 | 76,89 | from typing import Optional, Tuple
from torch import Tensor
from torchmetrics.functional.retrieval.average_precision import retrieval_average_precision
from torchmetrics.functional.retrieval.fall_out import retrieval_fall_out
from torchmetrics.functional.retrieval.hit_rate import retrieval_hit_rate
from torchmetrics.... | from typing import Optional, Tuple
from torch import Tensor
from torchmetrics.functional.retrieval.average_precision import retrieval_average_precision
from torchmetrics.functional.retrieval.fall_out import retrieval_fall_out
from torchmetrics.functional.retrieval.hit_rate import retrieval_hit_rate
from torchmetrics.... | _deprecated_root_import_func("retrieval_precision", "retrieval")
return retrieval_precision(preds=preds, target=target, top_k=top_k, adaptive_k=adaptive_k)
| """Wrapper for deprecated import.
>>> from torch import tensor
>>> preds = tensor([0.2, 0.3, 0.5])
>>> target = tensor([True, False, True])
>>> _retrieval_precision(preds, target, top_k=2)
tensor(0.5000)
"""
_deprecated_root_import_func("retrieval_precision", "retrieval")
return re... | 7 | 1,973 | 66 | 2,039 | from typing import Optional, Tuple
from torch import Tensor
from torchmetrics.functional.retrieval.average_precision import retrieval_average_precision
from torchmetrics.functional.retrieval.fall_out import retrieval_fall_out
from torchmetrics.functional.retrieval.hit_rate import retrieval_hit_rate
from torchmetrics.... | from typing import Optional, Tuple
from torch import Tensor
from torchmetrics.functional.retrieval.average_precision import retrieval_average_precision
from torchmetrics.functional.retrieval.fall_out import retrieval_fall_out
from torchmetrics.functional.retrieval.hit_rate import retrieval_hit_rate
from torchmetrics.... | |
29,668 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/functional/retrieval/hit_rate.py | 22,23 | 1,62 | retrieval_hit_rate | 52,62 | 23,62 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | preds, target = _check_retrieval_functional_inputs(preds, target)
if top_k is None:
top_k = preds.shape[-1]
if not (isinstance(top_k, int) and top_k > 0):
raise ValueError("`top_k` has to be a positive integer or None")
relevant = target[torch.argsort(preds, dim=-1, descending=True)][... | """Compute the hit rate for information retrieval.
The hit rate is 1.0 if there is at least one relevant document among all the top `k` retrieved documents.
``preds`` and ``target`` should be of the same shape and live on the same device. If no ``target`` is ``True``,
``0`` is returned. ``target`` mus... | 39 | 597 | 144 | 741 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | |
29,669 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/functional/retrieval/ndcg.py | 22,23 | 1,114 | _tie_average_dcg | 34,45 | 23,45 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | _, inv, counts = torch.unique(-preds, return_inverse=True, return_counts=True)
ranked = torch.zeros_like(counts, dtype=torch.float32)
ranked.scatter_add_(0, inv, target.to(dtype=ranked.dtype))
ranked = ranked / counts
groups = counts.cumsum(dim=0) - 1
discount_sums = torch.zeros_like(counts, dty... | """Translated version of sklearns `_tie_average_dcg` function.
Args:
target: ground truth about each document relevance.
preds: estimated probabilities of each document to be relevant.
discount_cumsum: cumulative sum of the discount.
Returns:
The cumulative gain of the tied... | 38 | 1,217 | 199 | 1,416 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | |
29,670 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/functional/retrieval/precision_recall_curve.py | 24,27 | 1,101 | retrieval_precision_recall_curve | 74,101 | 27,101 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | preds, target = _check_retrieval_functional_inputs(preds, target)
if not isinstance(adaptive_k, bool):
raise ValueError("`adaptive_k` has to be a boolean")
if max_k is None:
max_k = preds.shape[-1]
if not (isinstance(max_k, int) and max_k > 0):
raise ValueError("`max_k` has to... | """Compute precision-recall pairs for different k (from 1 to `max_k`).
In a ranked retrieval context, appropriate sets of retrieved documents are naturally given by
the top k retrieved documents.
Recall is the fraction of relevant documents retrieved among all the relevant documents.
Precision is ... | 110 | 885 | 424 | 1,309 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | |
29,671 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/functional/segmentation/generalized_dice.py | 42,49 | 1,139 | _generalized_dice_update | 50,92 | 49,92 | # Copyright The PyTorch Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | # Copyright The PyTorch Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | _check_same_shape(preds, target)
if preds.ndim < 3:
raise ValueError(f"Expected both `preds` and `target` to have at least 3 dimensions, but got {preds.ndim}.")
if (preds.bool() != preds).any(): # preds is an index tensor
preds = torch.nn.functional.one_hot(preds, num_classes=num_classes).... | """Update the state with the current prediction and target."""
_check_same_shape(preds, target)
if preds.ndim < 3:
raise ValueError(f"Expected both `preds` and `target` to have at least 3 dimensions, but got {preds.ndim}.")
if (preds.bool() != preds).any(): # preds is an index tensor
p... | 164 | 1,382 | 618 | 2,000 | # Copyright The PyTorch Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | # Copyright The PyTorch Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | |
29,672 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/functional/segmentation/mean_iou.py | 24,29 | 1,110 | _mean_iou_validate_args | 30,38 | 29,38 | # Copyright The PyTorch Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | # Copyright The PyTorch Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | if num_classes <= 0:
raise ValueError(f"Expected argument `num_classes` must be a positive integer, but got {num_classes}.")
if not isinstance(include_background, bool):
raise ValueError(f"Expected argument `include_background` must be a boolean, but got {include_background}.")
if not isinst... | """Validate the arguments of the metric."""
if num_classes <= 0:
raise ValueError(f"Expected argument `num_classes` must be a positive integer, but got {num_classes}.")
if not isinstance(include_background, bool):
raise ValueError(f"Expected argument `include_background` must be a boolean, b... | 46 | 1,343 | 130 | 1,473 | # Copyright The PyTorch Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | # Copyright The PyTorch Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | |
29,674 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/functional/text/edit.py | 22,27 | 1,120 | _edit_distance_update | 27,47 | 27,47 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | if isinstance(preds, str):
preds = [preds]
if isinstance(target, str):
target = [target]
if not all(isinstance(x, str) for x in preds):
raise ValueError(f"Expected all values in argument `preds` to be string type, but got {preds}")
if not all(isinstance(x, str) for x in target):
... | if isinstance(preds, str):
preds = [preds]
if isinstance(target, str):
target = [target]
if not all(isinstance(x, str) for x in preds):
raise ValueError(f"Expected all values in argument `preds` to be string type, but got {preds}")
if not all(isinstance(x, str) for x in target):
... | 95 | 1,165 | 283 | 1,448 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | |
29,675 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/image/d_lambda.py | 96,97 | 30,155 | update | SpectralDistortionIndex | 98,102 | 97,102 | class SpectralDistortionIndex(Metric):
"""Compute Spectral Distortion Index (SpectralDistortionIndex_) also now as D_lambda.
The metric is used to compare the spectral distortion between two images.
As input to ``forward`` and ``update`` the metric accepts the following input
- ``preds`` (:class:`~to... | class SpectralDistortionIndex(Metric):
"""Compute Spectral Distortion Index (SpectralDistortionIndex_) also now as D_lambda.
The metric is used to compare the spectral distortion between two images.
As input to ``forward`` and ``update`` the metric accepts the following input
- ``preds`` (:class:`~to... | preds, target = _spectral_distortion_index_update(preds, target)
self.preds.append(preds)
self.target.append(target)
| """Update state with preds and target."""
preds, target = _spectral_distortion_index_update(preds, target)
self.preds.append(preds)
self.target.append(target)
| 7 | 1,450 | 50 | 1,500 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... |
29,677 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/image/ergas.py | 108,109 | 31,159 | compute | ErrorRelativeGlobalDimensionlessSynthesis | 110,114 | 109,114 | class ErrorRelativeGlobalDimensionlessSynthesis(Metric):
r"""Calculate the `Error relative global dimensionless synthesis`_ (ERGAS) metric.
This metric is used to calculate the accuracy of Pan sharpened image considering normalized average error of each
band of the result image. It is defined as:
.. ... | class ErrorRelativeGlobalDimensionlessSynthesis(Metric):
r"""Calculate the `Error relative global dimensionless synthesis`_ (ERGAS) metric.
This metric is used to calculate the accuracy of Pan sharpened image considering normalized average error of each
band of the result image. It is defined as:
.. ... | preds = dim_zero_cat(self.preds)
target = dim_zero_cat(self.target)
return _ergas_compute(preds, target, self.ratio, self.reduction)
| """Compute explained variance over state."""
preds = dim_zero_cat(self.preds)
target = dim_zero_cat(self.target)
return _ergas_compute(preds, target, self.ratio, self.reduction)
| 11 | 1,509 | 58 | 1,567 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... |
29,685 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/image/rase.py | 90,91 | 29,138 | compute | RelativeAverageSpectralError | 92,96 | 91,96 | class RelativeAverageSpectralError(Metric):
"""Computes Relative Average Spectral Error (RASE) (RelativeAverageSpectralError_).
As input to ``forward`` and ``update`` the metric accepts the following input
- ``preds`` (:class:`~torch.Tensor`): Predictions from model of shape ``(N,C,H,W)``
- ``target``... | class RelativeAverageSpectralError(Metric):
"""Computes Relative Average Spectral Error (RASE) (RelativeAverageSpectralError_).
As input to ``forward`` and ``update`` the metric accepts the following input
- ``preds`` (:class:`~torch.Tensor`): Predictions from model of shape ``(N,C,H,W)``
- ``target``... | preds = dim_zero_cat(self.preds)
target = dim_zero_cat(self.target)
return relative_average_spectral_error(preds, target, self.window_size)
| """Compute Relative Average Spectral Error (RASE)."""
preds = dim_zero_cat(self.preds)
target = dim_zero_cat(self.target)
return relative_average_spectral_error(preds, target, self.window_size)
| 10 | 1,204 | 59 | 1,263 | # Copyright The PyTorch Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | # Copyright The PyTorch Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... |
29,686 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/image/rmse_sw.py | 97,100 | 29,138 | plot | RootMeanSquaredErrorUsingSlidingWindow | 137,138 | 100,138 | class RootMeanSquaredErrorUsingSlidingWindow(Metric):
"""Computes Root Mean Squared Error (RMSE) using sliding window.
As input to ``forward`` and ``update`` the metric accepts the following input
- ``preds`` (:class:`~torch.Tensor`): Predictions from model of shape ``(N,C,H,W)``
- ``target`` (:class:... | class RootMeanSquaredErrorUsingSlidingWindow(Metric):
"""Computes Root Mean Squared Error (RMSE) using sliding window.
As input to ``forward`` and ``update`` the metric accepts the following input
- ``preds`` (:class:`~torch.Tensor`): Predictions from model of shape ``(N,C,H,W)``
- ``target`` (:class:... | return self._plot(val, ax)
| """Plot a single or multiple values from the metric.
Args:
val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
If no value is provided, will automatically call `metric.compute` and plot that result.
ax: An mat... | 3 | 1,394 | 12 | 1,406 | # Copyright The PyTorch Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | # Copyright The PyTorch Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... |
29,687 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/nominal/fleiss_kappa.py | 100,101 | 29,139 | plot | FleissKappa | 138,139 | 101,139 | class FleissKappa(Metric):
r"""Calculatees `Fleiss kappa`_ a statistical measure for inter agreement between raters.
.. math::
\kappa = \frac{\bar{p} - \bar{p_e}}{1 - \bar{p_e}}
where :math:`\bar{p}` is the mean of the agreement probability over all raters and :math:`\bar{p_e}` is the mean
agr... | class FleissKappa(Metric):
r"""Calculatees `Fleiss kappa`_ a statistical measure for inter agreement between raters.
.. math::
\kappa = \frac{\bar{p} - \bar{p_e}}{1 - \bar{p_e}}
where :math:`\bar{p}` is the mean of the agreement probability over all raters and :math:`\bar{p_e}` is the mean
agr... | return self._plot(val, ax)
| """Plot a single or multiple values from the metric.
Args:
val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
If no value is provided, will automatically call `metric.compute` and plot that result.
ax: An mat... | 3 | 1,413 | 12 | 1,425 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... |
29,688 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/regression/concordance.py | 78,79 | 27,134 | compute | ConcordanceCorrCoef | 80,93 | 79,93 | class ConcordanceCorrCoef(PearsonCorrCoef):
r"""Compute concordance correlation coefficient that measures the agreement between two variables.
.. math::
\rho_c = \frac{2 \rho \sigma_x \sigma_y}{\sigma_x^2 + \sigma_y^2 + (\mu_x - \mu_y)^2}
where :math:`\mu_x, \mu_y` is the means for the two variabl... | class ConcordanceCorrCoef(PearsonCorrCoef):
r"""Compute concordance correlation coefficient that measures the agreement between two variables.
.. math::
\rho_c = \frac{2 \rho \sigma_x \sigma_y}{\sigma_x^2 + \sigma_y^2 + (\mu_x - \mu_y)^2}
where :math:`\mu_x, \mu_y` is the means for the two variabl... | if (self.num_outputs == 1 and self.mean_x.numel() > 1) or (self.num_outputs > 1 and self.mean_x.ndim > 1):
mean_x, mean_y, var_x, var_y, corr_xy, n_total = _final_aggregation(
self.mean_x, self.mean_y, self.var_x, self.var_y, self.corr_xy, self.n_total
)
else:
... | """Compute final concordance correlation coefficient over metric states."""
if (self.num_outputs == 1 and self.mean_x.numel() > 1) or (self.num_outputs > 1 and self.mean_x.ndim > 1):
mean_x, mean_y, var_x, var_y, corr_xy, n_total = _final_aggregation(
self.mean_x, self.mean_y... | 57 | 1,156 | 248 | 1,404 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... |
29,689 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/regression/cosine_similarity.py | 85,86 | 29,139 | update | CosineSimilarity | 87,92 | 86,92 | class CosineSimilarity(Metric):
r"""Compute the `Cosine Similarity`_.
.. math::
cos_{sim}(x,y) = \frac{x \cdot y}{||x|| \cdot ||y||} =
\frac{\sum_{i=1}^n x_i y_i}{\sqrt{\sum_{i=1}^n x_i^2}\sqrt{\sum_{i=1}^n y_i^2}}
where :math:`y` is a tensor of target values, and :math:`x` is a tensor of ... | class CosineSimilarity(Metric):
r"""Compute the `Cosine Similarity`_.
.. math::
cos_{sim}(x,y) = \frac{x \cdot y}{||x|| \cdot ||y||} =
\frac{\sum_{i=1}^n x_i y_i}{\sqrt{\sum_{i=1}^n x_i^2}\sqrt{\sum_{i=1}^n y_i^2}}
where :math:`y` is a tensor of target values, and :math:`x` is a tensor of ... | preds, target = _cosine_similarity_update(preds, target)
self.preds.append(preds)
self.target.append(target)
| """Update metric states with predictions and targets."""
preds, target = _cosine_similarity_update(preds, target)
self.preds.append(preds)
self.target.append(target)
| 7 | 1,226 | 50 | 1,276 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... |
29,692 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/regression/pearson.py | 159,160 | 73,214 | compute | PearsonCorrCoef | 161,173 | 160,173 | class PearsonCorrCoef(Metric):
r"""Compute `Pearson Correlation Coefficient`_.
.. math::
P_{corr}(x,y) = \frac{cov(x,y)}{\sigma_x \sigma_y}
Where :math:`y` is a tensor of target values, and :math:`x` is a tensor of predictions.
As input to ``forward`` and ``update`` the metric accepts the fol... | class PearsonCorrCoef(Metric):
r"""Compute `Pearson Correlation Coefficient`_.
.. math::
P_{corr}(x,y) = \frac{cov(x,y)}{\sigma_x \sigma_y}
Where :math:`y` is a tensor of target values, and :math:`x` is a tensor of predictions.
As input to ``forward`` and ``update`` the metric accepts the fol... | if (self.num_outputs == 1 and self.mean_x.numel() > 1) or (self.num_outputs > 1 and self.mean_x.ndim > 1):
# multiple devices, need further reduction
_, _, var_x, var_y, corr_xy, n_total = _final_aggregation(
self.mean_x, self.mean_y, self.var_x, self.var_y, self.corr_xy,... | """Compute pearson correlation coefficient over state."""
if (self.num_outputs == 1 and self.mean_x.numel() > 1) or (self.num_outputs > 1 and self.mean_x.ndim > 1):
# multiple devices, need further reduction
_, _, var_x, var_y, corr_xy, n_total = _final_aggregation(
... | 55 | 1,610 | 220 | 1,830 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... |
29,693 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/regression/spearman.py | 97,98 | 29,150 | update | SpearmanCorrCoef | 99,103 | 98,103 | class SpearmanCorrCoef(Metric):
r"""Compute `spearmans rank correlation coefficient`_.
.. math:
r_s = = \frac{cov(rg_x, rg_y)}{\sigma_{rg_x} * \sigma_{rg_y}}
where :math:`rg_x` and :math:`rg_y` are the rank associated to the variables :math:`x` and :math:`y`.
Spearmans correlations coefficient... | class SpearmanCorrCoef(Metric):
r"""Compute `spearmans rank correlation coefficient`_.
.. math:
r_s = = \frac{cov(rg_x, rg_y)}{\sigma_{rg_x} * \sigma_{rg_y}}
where :math:`rg_x` and :math:`rg_y` are the rank associated to the variables :math:`x` and :math:`y`.
Spearmans correlations coefficient... | preds, target = _spearman_corrcoef_update(preds, target, num_outputs=self.num_outputs)
self.preds.append(preds.to(self.dtype))
self.target.append(target.to(self.dtype))
| """Update state with predictions and targets."""
preds, target = _spearman_corrcoef_update(preds, target, num_outputs=self.num_outputs)
self.preds.append(preds.to(self.dtype))
self.target.append(target.to(self.dtype))
| 8 | 1,397 | 77 | 1,474 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... |
29,694 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/retrieval/auroc.py | 120,121 | 28,164 | _metric | RetrievalAUROC | 121,123 | 121,123 | class RetrievalAUROC(RetrievalMetric):
"""Compute area under the receiver operating characteristic curve (AUROC) for information retrieval.
Works with binary target data. Accepts float predictions from a model output.
As input to ``forward`` and ``update`` the metric accepts the following input:
- ``... | class RetrievalAUROC(RetrievalMetric):
"""Compute area under the receiver operating characteristic curve (AUROC) for information retrieval.
Works with binary target data. Accepts float predictions from a model output.
As input to ``forward`` and ``update`` the metric accepts the following input:
- ``... | return retrieval_auroc(preds, target, top_k=self.top_k, max_fpr=self.max_fpr)
| return retrieval_auroc(preds, target, top_k=self.top_k, max_fpr=self.max_fpr)
| 5 | 1,776 | 39 | 1,815 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... |
29,695 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/retrieval/average_precision.py | 116,117 | 28,160 | _metric | RetrievalMAP | 117,119 | 117,119 | class RetrievalMAP(RetrievalMetric):
"""Compute `Mean Average Precision`_.
Works with binary target data. Accepts float predictions from a model output.
As input to ``forward`` and ``update`` the metric accepts the following input:
- ``preds`` (:class:`~torch.Tensor`): A float tensor of shape ``(N, .... | class RetrievalMAP(RetrievalMetric):
"""Compute `Mean Average Precision`_.
Works with binary target data. Accepts float predictions from a model output.
As input to ``forward`` and ``update`` the metric accepts the following input:
- ``preds`` (:class:`~torch.Tensor`): A float tensor of shape ``(N, .... | return retrieval_average_precision(preds, target, top_k=self.k)
| return retrieval_average_precision(preds, target, top_k=self.k)
| 4 | 1,620 | 28 | 1,648 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... |
29,696 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/retrieval/hit_rate.py | 117,118 | 28,161 | _metric | RetrievalHitRate | 118,120 | 118,120 | class RetrievalHitRate(RetrievalMetric):
"""Compute `IR HitRate`.
Works with binary target data. Accepts float predictions from a model output.
As input to ``forward`` and ``update`` the metric accepts the following input:
- ``preds`` (:class:`~torch.Tensor`): A float tensor of shape ``(N, ...)``
... | class RetrievalHitRate(RetrievalMetric):
"""Compute `IR HitRate`.
Works with binary target data. Accepts float predictions from a model output.
As input to ``forward`` and ``update`` the metric accepts the following input:
- ``preds`` (:class:`~torch.Tensor`): A float tensor of shape ``(N, ...)``
... | return retrieval_hit_rate(preds, target, top_k=self.top_k)
| return retrieval_hit_rate(preds, target, top_k=self.top_k)
| 4 | 1,628 | 29 | 1,657 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... |
29,697 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/retrieval/ndcg.py | 121,124 | 28,162 | plot | RetrievalNormalizedDCG | 161,162 | 124,162 | class RetrievalNormalizedDCG(RetrievalMetric):
"""Compute `Normalized Discounted Cumulative Gain`_.
Works with binary or positive integer target data. Accepts float predictions from a model output.
As input to ``forward`` and ``update`` the metric accepts the following input:
- ``preds`` (:class:`~to... | class RetrievalNormalizedDCG(RetrievalMetric):
"""Compute `Normalized Discounted Cumulative Gain`_.
Works with binary or positive integer target data. Accepts float predictions from a model output.
As input to ``forward`` and ``update`` the metric accepts the following input:
- ``preds`` (:class:`~to... | return self._plot(val, ax)
| """Plot a single or multiple values from the metric.
Args:
val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
If no value is provided, will automatically call `metric.compute` and plot that result.
ax: An mat... | 3 | 1,671 | 12 | 1,683 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... |
29,698 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/retrieval/precision.py | 126,129 | 28,167 | plot | RetrievalPrecision | 166,167 | 129,167 | class RetrievalPrecision(RetrievalMetric):
"""Compute `IR Precision`_.
Works with binary target data. Accepts float predictions from a model output.
As input to ``forward`` and ``update`` the metric accepts the following input:
- ``preds`` (:class:`~torch.Tensor`): A float tensor of shape ``(N, ...)`... | class RetrievalPrecision(RetrievalMetric):
"""Compute `IR Precision`_.
Works with binary target data. Accepts float predictions from a model output.
As input to ``forward`` and ``update`` the metric accepts the following input:
- ``preds`` (:class:`~torch.Tensor`): A float tensor of shape ``(N, ...)`... | return self._plot(val, ax)
| """Plot a single or multiple values from the metric.
Args:
val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
If no value is provided, will automatically call `metric.compute` and plot that result.
ax: An mat... | 3 | 1,752 | 12 | 1,764 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... |
29,701 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/retrieval/precision_recall_curve.py | 388,391 | 296,430 | plot | RetrievalRecallAtFixedPrecision | 428,430 | 391,430 | class RetrievalRecallAtFixedPrecision(RetrievalPrecisionRecallCurve):
"""Compute `IR Recall at fixed Precision`_.
As input to ``forward`` and ``update`` the metric accepts the following input:
- ``preds`` (:class:`~torch.Tensor`): A float tensor of shape ``(N, ...)``
- ``target`` (:class:`~torch.Tenso... | class RetrievalRecallAtFixedPrecision(RetrievalPrecisionRecallCurve):
"""Compute `IR Recall at fixed Precision`_.
As input to ``forward`` and ``update`` the metric accepts the following input:
- ``preds`` (:class:`~torch.Tensor`): A float tensor of shape ``(N, ...)``
- ``target`` (:class:`~torch.Tenso... | val = val or self.compute()[0]
return self._plot(val, ax)
| """Plot a single or multiple values from the metric.
Args:
val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
If no value is provided, will automatically call `metric.compute` and plot that result.
ax: An mat... | 8 | 1,670 | 26 | 1,696 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... |
29,702 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/retrieval/r_precision.py | 93,94 | 27,137 | _metric | RetrievalRPrecision | 94,96 | 94,96 | class RetrievalRPrecision(RetrievalMetric):
"""Compute `IR R-Precision`_.
Works with binary target data. Accepts float predictions from a model output.
As input to ``forward`` and ``update`` the metric accepts the following input:
- ``preds`` (:class:`~torch.Tensor`): A float tensor of shape ``(N, ..... | class RetrievalRPrecision(RetrievalMetric):
"""Compute `IR R-Precision`_.
Works with binary target data. Accepts float predictions from a model output.
As input to ``forward`` and ``update`` the metric accepts the following input:
- ``preds`` (:class:`~torch.Tensor`): A float tensor of shape ``(N, ..... | return retrieval_r_precision(preds, target)
| return retrieval_r_precision(preds, target)
| 3 | 1,367 | 19 | 1,386 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... |
29,703 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/retrieval/recall.py | 116,117 | 28,160 | _metric | RetrievalRecall | 117,119 | 117,119 | class RetrievalRecall(RetrievalMetric):
"""Compute `IR Recall`_.
Works with binary target data. Accepts float predictions from a model output.
As input to ``forward`` and ``update`` the metric accepts the following input:
- ``preds`` (:class:`~torch.Tensor`): A float tensor of shape ``(N, ...)``
... | class RetrievalRecall(RetrievalMetric):
"""Compute `IR Recall`_.
Works with binary target data. Accepts float predictions from a model output.
As input to ``forward`` and ``update`` the metric accepts the following input:
- ``preds`` (:class:`~torch.Tensor`): A float tensor of shape ``(N, ...)``
... | return retrieval_recall(preds, target, top_k=self.top_k)
| return retrieval_recall(preds, target, top_k=self.top_k)
| 4 | 1,617 | 27 | 1,644 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... |
29,704 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/retrieval/reciprocal_rank.py | 116,117 | 28,160 | _metric | RetrievalMRR | 117,119 | 117,119 | class RetrievalMRR(RetrievalMetric):
"""Compute `Mean Reciprocal Rank`_.
Works with binary target data. Accepts float predictions from a model output.
As input to ``forward`` and ``update`` the metric accepts the following input:
- ``preds`` (:class:`~torch.Tensor`): A float tensor of shape ``(N, ...... | class RetrievalMRR(RetrievalMetric):
"""Compute `Mean Reciprocal Rank`_.
Works with binary target data. Accepts float predictions from a model output.
As input to ``forward`` and ``update`` the metric accepts the following input:
- ``preds`` (:class:`~torch.Tensor`): A float tensor of shape ``(N, ...... | return retrieval_reciprocal_rank(preds, target, top_k=self.top_k)
| return retrieval_reciprocal_rank(preds, target, top_k=self.top_k)
| 4 | 1,632 | 31 | 1,663 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... |
29,706 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/text/sacre_bleu.py | 102,103 | 34,158 | update | SacreBLEUScore | 104,115 | 103,115 | class SacreBLEUScore(BLEUScore):
"""Calculate `BLEU score`_ of machine translated text with one or more references.
This implementation follows the behaviour of `SacreBLEU`_. The SacreBLEU implementation differs from the NLTK BLEU
implementation in tokenization techniques.
As input to ``forward`` and ... | class SacreBLEUScore(BLEUScore):
"""Calculate `BLEU score`_ of machine translated text with one or more references.
This implementation follows the behaviour of `SacreBLEU`_. The SacreBLEU implementation differs from the NLTK BLEU
implementation in tokenization techniques.
As input to ``forward`` and ... | self.preds_len, self.target_len = _bleu_score_update(
preds,
target,
self.numerator,
self.denominator,
self.preds_len,
self.target_len,
self.n_gram,
self.tokenizer,
)
| """Update state with predictions and targets."""
self.preds_len, self.target_len = _bleu_score_update(
preds,
target,
self.numerator,
self.denominator,
self.preds_len,
self.target_len,
self.n_gram,
self.token... | 13 | 1,363 | 94 | 1,457 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... |
29,707 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/utilities/compute.py | 77,78 | 1,163 | _auc_format_inputs | 79,93 | 78,93 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | x = x.squeeze() if x.ndim > 1 else x
y = y.squeeze() if y.ndim > 1 else y
if x.ndim > 1 or y.ndim > 1:
raise ValueError(
f"Expected both `x` and `y` tensor to be 1d, but got tensors with dimension {x.ndim} and {y.ndim}"
)
if x.numel() != y.numel():
raise ValueError(
... | """Check that auc input is correct."""
x = x.squeeze() if x.ndim > 1 else x
y = y.squeeze() if y.ndim > 1 else y
if x.ndim > 1 or y.ndim > 1:
raise ValueError(
f"Expected both `x` and `y` tensor to be 1d, but got tensors with dimension {x.ndim} and {y.ndim}"
)
if x.numel... | 72 | 1,675 | 186 | 1,861 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | |
29,709 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/utilities/distributed.py | 97,98 | 1,148 | gather_all_tensors | 111,148 | 98,148 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | if group is None:
group = torch.distributed.group.WORLD
# convert tensors to contiguous format
result = result.contiguous()
world_size = torch.distributed.get_world_size(group)
torch.distributed.barrier(group=group)
# if the tensor is scalar, things are easy
if result.ndim == 0:
... | """Gather all tensors from several ddp processes onto a list that is broadcasted to all processes.
Works on tensors that have the same number of dimensions, but where each dimension may differ. In this case
tensors are padded, gathered and then trimmed to secure equal workload for all processes.
Args:... | 152 | 1,201 | 578 | 1,779 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | |
29,710 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/utilities/prints.py | 42,43 | 1,74 | _warn | 43,46 | 43,46 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | warnings.warn(*args, **kwargs) # noqa: B028
| warnings.warn(*args, **kwargs) # noqa: B028
| 5 | 742 | 26 | 768 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | |
29,711 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/wrappers/abstract.py | 32,33 | 19,43 | _wrap_update | WrapperMetric | 34,36 | 33,36 | class WrapperMetric(Metric):
"""Abstract base class for wrapper metrics.
Wrapper metrics are characterized by them wrapping another metric, and forwarding all calls to the wrapped metric.
This means that all logic regarding synchronization etc. is handled by the wrapped metric, and the wrapper metric
s... | class WrapperMetric(Metric):
"""Abstract base class for wrapper metrics.
Wrapper metrics are characterized by them wrapping another metric, and forwarding all calls to the wrapped metric.
This means that all logic regarding synchronization etc. is handled by the wrapped metric, and the wrapper metric
s... | return update
| """Overwrite to do nothing, because the default wrapped functionality is handled by the wrapped metric."""
return update
| 2 | 278 | 7 | 285 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... |
29,713 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/wrappers/bootstrapping.py | 125,126 | 54,214 | update | BootStrapper | 131,148 | 126,148 | class BootStrapper(WrapperMetric):
r"""Using `Turn a Metric into a Bootstrapped`_.
That can automate the process of getting confidence intervals for metric values. This wrapper
class basically keeps multiple copies of the same base metric in memory and whenever ``update`` or
``forward`` is called, all ... | class BootStrapper(WrapperMetric):
r"""Using `Turn a Metric into a Bootstrapped`_.
That can automate the process of getting confidence intervals for metric values. This wrapper
class basically keeps multiple copies of the same base metric in memory and whenever ``update`` or
``forward`` is called, all ... | args_sizes = apply_to_collection(args, Tensor, len)
kwargs_sizes = apply_to_collection(kwargs, Tensor, len)
if len(args_sizes) > 0:
size = args_sizes[0]
elif len(kwargs_sizes) > 0:
size = next(iter(kwargs_sizes.values()))
else:
raise ValueError... | """Update the state of the base metric.
Any tensor passed in will be bootstrapped along dimension 0.
"""
args_sizes = apply_to_collection(args, Tensor, len)
kwargs_sizes = apply_to_collection(kwargs, Tensor, len)
if len(args_sizes) > 0:
size = args_sizes[0]
... | 68 | 1,724 | 290 | 2,014 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... |
29,715 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/wrappers/feature_share.py | 40,41 | 26,45 | forward | NetworkCache | 42,45 | 41,45 | class NetworkCache(Module):
"""Create a cached version of a network to be shared between metrics.
Because the different metrics may invoke the same network multiple times, we can save time by caching the input-
output pairs of the network.
"""
def __init__(self, network: Module, max_size: int = 1... | class NetworkCache(Module):
"""Create a cached version of a network to be shared between metrics.
Because the different metrics may invoke the same network multiple times, we can save time by caching the input-
output pairs of the network.
"""
def __init__(self, network: Module, max_size: int = 1... | return self.network(*args, **kwargs)
| """Call the network with the given arguments."""
return self.network(*args, **kwargs)
| 3 | 182 | 17 | 199 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... |
29,716 | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics | /home/hieuvd/dung_repo/raw/stars_02/Lightning-AI_torchmetrics/torchmetrics/src/torchmetrics/wrappers/minmax.py | 99,100 | 29,160 | forward | MinMaxMetric | 101,103 | 100,103 | class MinMaxMetric(WrapperMetric):
"""Wrapper metric that tracks both the minimum and maximum of a scalar/tensor across an experiment.
The min/max value will be updated each time ``.compute`` is called.
Args:
base_metric:
The metric of which you want to keep track of its maximum and mi... | class MinMaxMetric(WrapperMetric):
"""Wrapper metric that tracks both the minimum and maximum of a scalar/tensor across an experiment.
The min/max value will be updated each time ``.compute`` is called.
Args:
base_metric:
The metric of which you want to keep track of its maximum and mi... | return super(WrapperMetric, self).forward(*args, **kwargs)
| """Use the original forward method of the base metric class."""
return super(WrapperMetric, self).forward(*args, **kwargs)
| 4 | 1,570 | 21 | 1,591 | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright The Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... |
29,722 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/depth_anything/blocks.py | 4,5 | 1,154 | _make_scratch | 5,37 | 5,37 | import torch.nn as nn
def _make_scratch(in_shape, out_shape, groups=1, expand=False):
FILL_FUNC_BODYclass ResidualConvUnit(nn.Module):
"""Residual convolution module.
"""
def __init__(self, features, activation, bn):
"""Init.
Args:
features (int): number of features
"... | import torch.nn as nn
def _make_scratch(in_shape, out_shape, groups=1, expand=False):
FILL_FUNC_BODYclass ResidualConvUnit(nn.Module):
"""Residual convolution module.
"""
def __init__(self, features, activation, bn):
"""Init.
Args:
features (int): number of features
"... | scratch = nn.Module()
out_shape1 = out_shape
out_shape2 = out_shape
out_shape3 = out_shape
if len(in_shape) >= 4:
out_shape4 = out_shape
if expand:
out_shape1 = out_shape
out_shape2 = out_shape*2
out_shape3 = out_shape*4
if len(in_shape) >= 4:
... | scratch = nn.Module()
out_shape1 = out_shape
out_shape2 = out_shape
out_shape3 = out_shape
if len(in_shape) >= 4:
out_shape4 = out_shape
if expand:
out_shape1 = out_shape
out_shape2 = out_shape*2
out_shape3 = out_shape*4
if len(in_shape) >= 4:
... | 87 | 981 | 398 | 1,379 | import torch.nn as nn
def _make_scratch(in_shape, out_shape, groups=1, expand=False):
FILL_FUNC_BODYclass ResidualConvUnit(nn.Module):
"""Residual convolution module.
"""
def __init__(self, features, activation, bn):
"""Init.
Args:
features (int): number of features
"... | import torch.nn as nn
def _make_scratch(in_shape, out_shape, groups=1, expand=False):
FILL_FUNC_BODYclass ResidualConvUnit(nn.Module):
"""Residual convolution module.
"""
def __init__(self, features, activation, bn):
"""Init.
Args:
features (int): number of features
"... | |
29,723 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/depth_anything/blocks.py | 126,127 | 95,154 | forward | FeatureFusionBlock | 132,154 | 127,154 | class FeatureFusionBlock(nn.Module):
"""Feature fusion block.
"""
def __init__(self, features, activation, deconv=False, bn=False, expand=False, align_corners=True, size=None):
"""Init.
Args:
features (int): number of features
"""
super(FeatureFusionBlock, self)... | class FeatureFusionBlock(nn.Module):
"""Feature fusion block.
"""
def __init__(self, features, activation, deconv=False, bn=False, expand=False, align_corners=True, size=None):
"""Init.
Args:
features (int): number of features
"""
super(FeatureFusionBlock, self)... | output = xs[0]
if len(xs) == 2:
res = self.resConfUnit1(xs[1])
output = self.skip_add.add(output, res)
output = self.resConfUnit2(output)
if (size is None) and (self.size is None):
modifier = {"scale_factor": 2}
elif size is None:
... | """Forward pass.
Returns:
tensor: output
"""
output = xs[0]
if len(xs) == 2:
res = self.resConfUnit1(xs[1])
output = self.skip_add.add(output, res)
output = self.resConfUnit2(output)
if (size is None) and (self.size is None)... | 55 | 326 | 213 | 539 | import torch.nn as nn
def _make_scratch(in_shape, out_shape, groups=1, expand=False):
scratch = nn.Module()
out_shape1 = out_shape
out_shape2 = out_shape
out_shape3 = out_shape
if len(in_shape) >= 4:
out_shape4 = out_shape
if expand:
out_shape1 = out_shape
out_shape2 ... | import torch.nn as nn
def _make_scratch(in_shape, out_shape, groups=1, expand=False):
scratch = nn.Module()
out_shape1 = out_shape
out_shape2 = out_shape
out_shape3 = out_shape
if len(in_shape) >= 4:
out_shape4 = out_shape
if expand:
out_shape1 = out_shape
out_shape2 ... |
29,724 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/depth_anything/blocks.py | 69,70 | 37,95 | forward | ResidualConvUnit | 78,95 | 70,95 | class ResidualConvUnit(nn.Module):
"""Residual convolution module.
"""
def __init__(self, features, activation, bn):
"""Init.
Args:
features (int): number of features
"""
super().__init__()
self.bn = bn
self.groups=1
self.conv1 = nn.Co... | class ResidualConvUnit(nn.Module):
"""Residual convolution module.
"""
def __init__(self, features, activation, bn):
"""Init.
Args:
features (int): number of features
"""
super().__init__()
self.bn = bn
self.groups=1
self.conv1 = nn.Co... |
out = self.activation(x)
out = self.conv1(out)
if self.bn==True:
out = self.bn1(out)
out = self.activation(out)
out = self.conv2(out)
if self.bn==True:
out = self.bn2(out)
if self.groups > 1:
out = self.conv_me... | """Forward pass.
Args:
x (tensor): input
Returns:
tensor: output
"""
out = self.activation(x)
out = self.conv1(out)
if self.bn==True:
out = self.bn1(out)
out = self.activation(out)
out = self.c... | 32 | 311 | 145 | 456 | import torch.nn as nn
def _make_scratch(in_shape, out_shape, groups=1, expand=False):
scratch = nn.Module()
out_shape1 = out_shape
out_shape2 = out_shape
out_shape3 = out_shape
if len(in_shape) >= 4:
out_shape4 = out_shape
if expand:
out_shape1 = out_shape
out_shape2 ... | import torch.nn as nn
def _make_scratch(in_shape, out_shape, groups=1, expand=False):
scratch = nn.Module()
out_shape1 = out_shape
out_shape2 = out_shape
out_shape3 = out_shape
if len(in_shape) >= 4:
out_shape4 = out_shape
if expand:
out_shape1 = out_shape
out_shape2 ... |
29,726 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/depth_anything/dpt.py | 103,104 | 22,139 | forward | DPTHead | 104,139 | 104,139 | class DPTHead(nn.Module):
def __init__(self, nclass, in_channels, features=256, use_bn=False, out_channels=[256, 512, 1024, 1024], use_clstoken=False):
super(DPTHead, self).__init__()
self.nclass = nclass
self.use_clstoken = use_clstoken
self.projects = nn.ModuleLis... | class DPTHead(nn.Module):
def __init__(self, nclass, in_channels, features=256, use_bn=False, out_channels=[256, 512, 1024, 1024], use_clstoken=False):
super(DPTHead, self).__init__()
self.nclass = nclass
self.use_clstoken = use_clstoken
self.projects = nn.ModuleLis... | out = []
for i, x in enumerate(out_features):
if self.use_clstoken:
x, cls_token = x[0], x[1]
readout = cls_token.unsqueeze(1).expand_as(x)
x = self.readout_projects[i](torch.cat((x, readout), -1))
else:
x = x[0]
... | out = []
for i, x in enumerate(out_features):
if self.use_clstoken:
x, cls_token = x[0], x[1]
readout = cls_token.unsqueeze(1).expand_as(x)
x = self.readout_projects[i](torch.cat((x, readout), -1))
else:
x = x[0]
... | 97 | 1,009 | 576 | 1,585 | import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
from huggingface_hub import PyTorchModelHubMixin, hf_hub_download
from depth_anything.blocks import FeatureFusionBlock, _make_scratch
def _make_fusion_block(features, use_bn, size = None):
return FeatureFusionBlock(
featur... | import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
from huggingface_hub import PyTorchModelHubMixin, hf_hub_download
from depth_anything.blocks import FeatureFusionBlock, _make_scratch
def _make_fusion_block(features, use_bn, size = None):
return FeatureFusionBlock(
featur... |
29,727 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/depth_anything/dpt.py | 155,156 | 139,169 | forward | DPT_DINOv2 | 156,169 | 156,169 | class DPT_DINOv2(nn.Module):
def __init__(self, encoder='vitl', features=256, out_channels=[256, 512, 1024, 1024], use_bn=False, use_clstoken=False, localhub=True):
super(DPT_DINOv2, self).__init__()
assert encoder in ['vits', 'vitb', 'vitl']
# in case the Internet connecti... | class DPT_DINOv2(nn.Module):
def __init__(self, encoder='vitl', features=256, out_channels=[256, 512, 1024, 1024], use_bn=False, use_clstoken=False, localhub=True):
super(DPT_DINOv2, self).__init__()
assert encoder in ['vits', 'vitb', 'vitl']
# in case the Internet connecti... | h, w = x.shape[-2:]
features = self.pretrained.get_intermediate_layers(x, 4, return_class_token=True)
patch_h, patch_w = h // 14, w // 14
depth = self.depth_head(features, patch_h, patch_w)
depth = F.interpolate(depth, size=(h, w), mode="bilinear", align_corner... | h, w = x.shape[-2:]
features = self.pretrained.get_intermediate_layers(x, 4, return_class_token=True)
patch_h, patch_w = h // 14, w // 14
depth = self.depth_head(features, patch_h, patch_w)
depth = F.interpolate(depth, size=(h, w), mode="bilinear", align_corner... | 35 | 341 | 159 | 500 | import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
from huggingface_hub import PyTorchModelHubMixin, hf_hub_download
from depth_anything.blocks import FeatureFusionBlock, _make_scratch
def _make_fusion_block(features, use_bn, size = None):
return FeatureFusionBlock(
featur... | import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
from huggingface_hub import PyTorchModelHubMixin, hf_hub_download
from depth_anything.blocks import FeatureFusionBlock, _make_scratch
def _make_fusion_block(features, use_bn, size = None):
return FeatureFusionBlock(
featur... |
29,729 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/depth_anything/util/transform.py | 111,112 | 54,211 | get_size | Resize | 112,168 | 112,168 | class Resize(object):
"""Resize sample to given size (width, height).
"""
def __init__(
self,
width,
height,
resize_target=True,
keep_aspect_ratio=False,
ensure_multiple_of=1,
resize_method="lower_bound",
image_interpolation_method=cv2.INTER_A... | class Resize(object):
"""Resize sample to given size (width, height).
"""
def __init__(
self,
width,
height,
resize_target=True,
keep_aspect_ratio=False,
ensure_multiple_of=1,
resize_method="lower_bound",
image_interpolation_method=cv2.INTER_A... | # determine new height and width
scale_height = self.__height / height
scale_width = self.__width / width
if self.__keep_aspect_ratio:
if self.__resize_method == "lower_bound":
# scale such that output size is lower bound
if scale_width > scal... | # determine new height and width
scale_height = self.__height / height
scale_width = self.__width / width
if self.__keep_aspect_ratio:
if self.__resize_method == "lower_bound":
# scale such that output size is lower bound
if scale_width > scal... | 180 | 1,072 | 613 | 1,685 | import random
from PIL import Image, ImageOps, ImageFilter
import torch
from torchvision import transforms
import torch.nn.functional as F
import numpy as np
import cv2
import math
def apply_min_size(sample, size, image_interpolation_method=cv2.INTER_AREA):
"""Rezise the sample to ensure the given size. Keeps as... | import random
from PIL import Image, ImageOps, ImageFilter
import torch
from torchvision import transforms
import torch.nn.functional as F
import numpy as np
import cv2
import math
def apply_min_size(sample, size, image_interpolation_method=cv2.INTER_AREA):
"""Rezise the sample to ensure the given size. Keeps as... |
29,731 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/metric_depth/zoedepth/data/ddad.py | 123,124 | 1,126 | get_ddad_loader | 124,126 | 124,126 | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | dataset = DDAD(data_dir_root, resize_shape)
return DataLoader(dataset, batch_size, **kwargs)
| dataset = DDAD(data_dir_root, resize_shape)
return DataLoader(dataset, batch_size, **kwargs)
| 8 | 1,418 | 35 | 1,453 | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | |
29,732 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/metric_depth/zoedepth/data/ddad.py | 51,52 | 34,82 | to_tensor | ToTensor | 52,82 | 52,82 | class ToTensor(object):
def __init__(self, resize_shape):
# self.normalize = transforms.Normalize(
# mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
self.normalize = lambda x : x
self.resize = transforms.Resize(resize_shape)
def __call__(self, sample):
image, ... | class ToTensor(object):
def __init__(self, resize_shape):
# self.normalize = transforms.Normalize(
# mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
self.normalize = lambda x : x
self.resize = transforms.Resize(resize_shape)
def __call__(self, sample):
image, ... |
if isinstance(pic, np.ndarray):
img = torch.from_numpy(pic.transpose((2, 0, 1)))
return img
# # handle PIL Image
if pic.mode == 'I':
img = torch.from_numpy(np.array(pic, np.int32, copy=False))
elif pic.mode == 'I;16':
img = torch.... |
if isinstance(pic, np.ndarray):
img = torch.from_numpy(pic.transpose((2, 0, 1)))
return img
# # handle PIL Image
if pic.mode == 'I':
img = torch.from_numpy(np.array(pic, np.int32, copy=False))
elif pic.mode == 'I;16':
img = torch.... | 87 | 226 | 365 | 591 | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... |
29,733 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/metric_depth/zoedepth/data/diml_indoor_test.py | 120,121 | 1,126 | get_diml_indoor_loader | 121,126 | 121,126 | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | dataset = DIML_Indoor(data_dir_root)
return DataLoader(dataset, batch_size, **kwargs)
# get_diml_indoor_loader(data_dir_root="datasets/diml/indoor/test/HR")
# get_diml_indoor_loader(data_dir_root="datasets/diml/indoor/test/LR")
| dataset = DIML_Indoor(data_dir_root)
return DataLoader(dataset, batch_size, **kwargs)
# get_diml_indoor_loader(data_dir_root="datasets/diml/indoor/test/HR")
# get_diml_indoor_loader(data_dir_root="datasets/diml/indoor/test/LR")
| 11 | 1,380 | 104 | 1,484 | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | |
29,734 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/metric_depth/zoedepth/data/diml_indoor_test.py | 51,52 | 34,81 | to_tensor | ToTensor | 52,81 | 52,81 | class ToTensor(object):
def __init__(self):
# self.normalize = transforms.Normalize(
# mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
self.normalize = lambda x : x
self.resize = transforms.Resize((480, 640))
def __call__(self, sample):
image, depth = sample['... | class ToTensor(object):
def __init__(self):
# self.normalize = transforms.Normalize(
# mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
self.normalize = lambda x : x
self.resize = transforms.Resize((480, 640))
def __call__(self, sample):
image, depth = sample['... |
if isinstance(pic, np.ndarray):
img = torch.from_numpy(pic.transpose((2, 0, 1)))
return img
# # handle PIL Image
if pic.mode == 'I':
img = torch.from_numpy(np.array(pic, np.int32, copy=False))
elif pic.mode == 'I;16':
img = torch.... |
if isinstance(pic, np.ndarray):
img = torch.from_numpy(pic.transpose((2, 0, 1)))
return img
# # handle PIL Image
if pic.mode == 'I':
img = torch.from_numpy(np.array(pic, np.int32, copy=False))
elif pic.mode == 'I;16':
img = torch.... | 87 | 230 | 363 | 593 | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... |
29,735 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/metric_depth/zoedepth/data/diml_outdoor_test.py | 109,110 | 1,115 | get_diml_outdoor_loader | 110,115 | 110,115 | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | dataset = DIML_Outdoor(data_dir_root)
return DataLoader(dataset, batch_size, **kwargs)
# get_diml_outdoor_loader(data_dir_root="datasets/diml/outdoor/test/HR")
# get_diml_outdoor_loader(data_dir_root="datasets/diml/outdoor/test/LR")
| dataset = DIML_Outdoor(data_dir_root)
return DataLoader(dataset, batch_size, **kwargs)
# get_diml_outdoor_loader(data_dir_root="datasets/diml/outdoor/test/HR")
# get_diml_outdoor_loader(data_dir_root="datasets/diml/outdoor/test/LR")
| 11 | 1,281 | 104 | 1,385 | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | |
29,736 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/metric_depth/zoedepth/data/diml_outdoor_test.py | 48,49 | 34,78 | to_tensor | ToTensor | 49,78 | 49,78 | class ToTensor(object):
def __init__(self):
# self.normalize = transforms.Normalize(
# mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
self.normalize = lambda x : x
def __call__(self, sample):
image, depth = sample['image'], sample['depth']
image = self.to_ten... | class ToTensor(object):
def __init__(self):
# self.normalize = transforms.Normalize(
# mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
self.normalize = lambda x : x
def __call__(self, sample):
image, depth = sample['image'], sample['depth']
image = self.to_ten... |
if isinstance(pic, np.ndarray):
img = torch.from_numpy(pic.transpose((2, 0, 1)))
return img
# # handle PIL Image
if pic.mode == 'I':
img = torch.from_numpy(np.array(pic, np.int32, copy=False))
elif pic.mode == 'I;16':
img = torch.... |
if isinstance(pic, np.ndarray):
img = torch.from_numpy(pic.transpose((2, 0, 1)))
return img
# # handle PIL Image
if pic.mode == 'I':
img = torch.from_numpy(np.array(pic, np.int32, copy=False))
elif pic.mode == 'I;16':
img = torch.... | 87 | 198 | 363 | 561 | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... |
29,737 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/metric_depth/zoedepth/data/diode.py | 121,122 | 1,126 | get_diode_loader | 122,126 | 122,126 | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | dataset = DIODE(data_dir_root)
return DataLoader(dataset, batch_size, **kwargs)
# get_diode_loader(data_dir_root="datasets/diode/val/outdoor")
| dataset = DIODE(data_dir_root)
return DataLoader(dataset, batch_size, **kwargs)
# get_diode_loader(data_dir_root="datasets/diode/val/outdoor")
| 9 | 1,372 | 62 | 1,434 | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | |
29,738 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/metric_depth/zoedepth/data/diode.py | 51,52 | 34,82 | to_tensor | ToTensor | 52,82 | 52,82 | class ToTensor(object):
def __init__(self):
# self.normalize = transforms.Normalize(
# mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
self.normalize = lambda x : x
self.resize = transforms.Resize(480)
def __call__(self, sample):
image, depth = sample['image']... | class ToTensor(object):
def __init__(self):
# self.normalize = transforms.Normalize(
# mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
self.normalize = lambda x : x
self.resize = transforms.Resize(480)
def __call__(self, sample):
image, depth = sample['image']... |
if isinstance(pic, np.ndarray):
img = torch.from_numpy(pic.transpose((2, 0, 1)))
return img
# # handle PIL Image
if pic.mode == 'I':
img = torch.from_numpy(np.array(pic, np.int32, copy=False))
elif pic.mode == 'I;16':
img = torch.... |
if isinstance(pic, np.ndarray):
img = torch.from_numpy(pic.transpose((2, 0, 1)))
return img
# # handle PIL Image
if pic.mode == 'I':
img = torch.from_numpy(np.array(pic, np.int32, copy=False))
elif pic.mode == 'I;16':
img = torch.... | 87 | 222 | 365 | 587 | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... |
29,739 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/metric_depth/zoedepth/data/ibims.py | 79,80 | 1,82 | get_ibims_loader | 80,82 | 80,82 | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | dataloader = DataLoader(iBims(config), batch_size=batch_size, **kwargs)
return dataloader
| dataloader = DataLoader(iBims(config), batch_size=batch_size, **kwargs)
return dataloader
| 7 | 1,059 | 36 | 1,095 | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | |
29,740 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/metric_depth/zoedepth/data/preprocess.py | 82,83 | 1,155 | get_white_border | 90,100 | 83,100 | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | if value == 255:
# assert range of values in rgb image is [0, 255]
assert np.max(rgb_image) <= 255 and np.min(rgb_image) >= 0, "RGB image values are not in range [0, 255]."
assert rgb_image.max() > 1, "RGB image values are not in range [0, 255]."
elif value == 1:
# assert range o... | """Crops the white border of the RGB.
Args:
rgb: RGB image, shape (H, W, 3).
Returns:
Crop parameters.
"""
if value == 255:
# assert range of values in rgb image is [0, 255]
assert np.max(rgb_image) <= 255 and np.min(rgb_image) >= 0, "RGB image values are not in rang... | 81 | 1,630 | 208 | 1,838 | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | |
29,741 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/metric_depth/zoedepth/data/sun_rgbd_loader.py | 113,114 | 1,116 | get_sunrgbd_loader | 114,116 | 114,116 | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | dataset = SunRGBD(data_dir_root)
return DataLoader(dataset, batch_size, **kwargs)
| dataset = SunRGBD(data_dir_root)
return DataLoader(dataset, batch_size, **kwargs)
| 7 | 1,495 | 32 | 1,527 | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | |
29,742 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/metric_depth/zoedepth/data/sun_rgbd_loader.py | 48,49 | 34,78 | to_tensor | ToTensor | 49,78 | 49,78 | class ToTensor(object):
def __init__(self):
# self.normalize = transforms.Normalize(
# mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
self.normalize = lambda x : x
def __call__(self, sample):
image, depth = sample['image'], sample['depth']
image = self.to_ten... | class ToTensor(object):
def __init__(self):
# self.normalize = transforms.Normalize(
# mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
self.normalize = lambda x : x
def __call__(self, sample):
image, depth = sample['image'], sample['depth']
image = self.to_ten... |
if isinstance(pic, np.ndarray):
img = torch.from_numpy(pic.transpose((2, 0, 1)))
return img
# # handle PIL Image
if pic.mode == 'I':
img = torch.from_numpy(np.array(pic, np.int32, copy=False))
elif pic.mode == 'I;16':
img = torch.... |
if isinstance(pic, np.ndarray):
img = torch.from_numpy(pic.transpose((2, 0, 1)))
return img
# # handle PIL Image
if pic.mode == 'I':
img = torch.from_numpy(np.array(pic, np.int32, copy=False))
elif pic.mode == 'I;16':
img = torch.... | 87 | 196 | 363 | 559 | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... |
29,744 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/metric_depth/zoedepth/data/transforms.py | 273,274 | 154,330 | make_letter_box | Resize | 274,280 | 274,280 | class Resize(object):
"""Resize sample to given size (width, height).
"""
def __init__(
self,
width,
height,
resize_target=True,
keep_aspect_ratio=False,
ensure_multiple_of=1,
resize_method="lower_bound",
image_interpolation_method=cv2.INTER_A... | class Resize(object):
"""Resize sample to given size (width, height).
"""
def __init__(
self,
width,
height,
resize_target=True,
keep_aspect_ratio=False,
ensure_multiple_of=1,
resize_method="lower_bound",
image_interpolation_method=cv2.INTER_A... | top = bottom = (self.__height - sample.shape[0]) // 2
left = right = (self.__width - sample.shape[1]) // 2
sample = cv2.copyMakeBorder(
sample, top, bottom, left, right, cv2.BORDER_CONSTANT, None, 0)
return sample
| top = bottom = (self.__height - sample.shape[0]) // 2
left = right = (self.__width - sample.shape[1]) // 2
sample = cv2.copyMakeBorder(
sample, top, bottom, left, right, cv2.BORDER_CONSTANT, None, 0)
return sample
| 31 | 1,644 | 91 | 1,735 | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... |
29,745 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/metric_depth/zoedepth/data/vkitti.py | 136,137 | 1,152 | get_vkitti_loader | 137,141 | 137,141 | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | dataset = VKITTI(data_dir_root)
return DataLoader(dataset, batch_size, **kwargs)
| dataset = VKITTI(data_dir_root)
return DataLoader(dataset, batch_size, **kwargs)
| 7 | 1,740 | 36 | 1,776 | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | |
29,746 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/metric_depth/zoedepth/data/vkitti.py | 52,53 | 35,82 | to_tensor | ToTensor | 53,82 | 53,82 | class ToTensor(object):
def __init__(self):
self.normalize = transforms.Normalize(
mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
# self.resize = transforms.Resize((375, 1242))
def __call__(self, sample):
image, depth = sample['image'], sample['depth']
image... | class ToTensor(object):
def __init__(self):
self.normalize = transforms.Normalize(
mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
# self.resize = transforms.Resize((375, 1242))
def __call__(self, sample):
image, depth = sample['image'], sample['depth']
image... |
if isinstance(pic, np.ndarray):
img = torch.from_numpy(pic.transpose((2, 0, 1)))
return img
# # handle PIL Image
if pic.mode == 'I':
img = torch.from_numpy(np.array(pic, np.int32, copy=False))
elif pic.mode == 'I;16':
img = torch.... |
if isinstance(pic, np.ndarray):
img = torch.from_numpy(pic.transpose((2, 0, 1)))
return img
# # handle PIL Image
if pic.mode == 'I':
img = torch.from_numpy(np.array(pic, np.int32, copy=False))
elif pic.mode == 'I;16':
img = torch.... | 87 | 218 | 363 | 581 | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... |
29,748 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/metric_depth/zoedepth/data/vkitti2.py | 53,54 | 35,83 | to_tensor | ToTensor | 54,83 | 54,83 | class ToTensor(object):
def __init__(self):
# self.normalize = transforms.Normalize(
# mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
self.normalize = lambda x: x
# self.resize = transforms.Resize((375, 1242))
def __call__(self, sample):
image, depth = sample... | class ToTensor(object):
def __init__(self):
# self.normalize = transforms.Normalize(
# mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
self.normalize = lambda x: x
# self.resize = transforms.Resize((375, 1242))
def __call__(self, sample):
image, depth = sample... |
if isinstance(pic, np.ndarray):
img = torch.from_numpy(pic.transpose((2, 0, 1)))
return img
# # handle PIL Image
if pic.mode == 'I':
img = torch.from_numpy(np.array(pic, np.int32, copy=False))
elif pic.mode == 'I;16':
img = torch.... |
if isinstance(pic, np.ndarray):
img = torch.from_numpy(pic.transpose((2, 0, 1)))
return img
# # handle PIL Image
if pic.mode == 'I':
img = torch.from_numpy(np.array(pic, np.int32, copy=False))
elif pic.mode == 'I;16':
img = torch.... | 87 | 233 | 363 | 596 | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... |
29,749 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/metric_depth/zoedepth/models/base_models/dpt_dinov2/blocks.py | 4,5 | 1,154 | _make_scratch | 5,37 | 5,37 | import torch.nn as nn
def _make_scratch(in_shape, out_shape, groups=1, expand=False):
FILL_FUNC_BODYclass ResidualConvUnit(nn.Module):
"""Residual convolution module.
"""
def __init__(self, features, activation, bn):
"""Init.
Args:
features (int): number of features
"... | import torch.nn as nn
def _make_scratch(in_shape, out_shape, groups=1, expand=False):
FILL_FUNC_BODYclass ResidualConvUnit(nn.Module):
"""Residual convolution module.
"""
def __init__(self, features, activation, bn):
"""Init.
Args:
features (int): number of features
"... | scratch = nn.Module()
out_shape1 = out_shape
out_shape2 = out_shape
out_shape3 = out_shape
if len(in_shape) >= 4:
out_shape4 = out_shape
if expand:
out_shape1 = out_shape
out_shape2 = out_shape*2
out_shape3 = out_shape*4
if len(in_shape) >= 4:
... | scratch = nn.Module()
out_shape1 = out_shape
out_shape2 = out_shape
out_shape3 = out_shape
if len(in_shape) >= 4:
out_shape4 = out_shape
if expand:
out_shape1 = out_shape
out_shape2 = out_shape*2
out_shape3 = out_shape*4
if len(in_shape) >= 4:
... | 87 | 981 | 398 | 1,379 | import torch.nn as nn
def _make_scratch(in_shape, out_shape, groups=1, expand=False):
FILL_FUNC_BODYclass ResidualConvUnit(nn.Module):
"""Residual convolution module.
"""
def __init__(self, features, activation, bn):
"""Init.
Args:
features (int): number of features
"... | import torch.nn as nn
def _make_scratch(in_shape, out_shape, groups=1, expand=False):
FILL_FUNC_BODYclass ResidualConvUnit(nn.Module):
"""Residual convolution module.
"""
def __init__(self, features, activation, bn):
"""Init.
Args:
features (int): number of features
"... | |
29,750 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/metric_depth/zoedepth/models/base_models/dpt_dinov2/blocks.py | 126,127 | 95,154 | forward | FeatureFusionBlock | 132,154 | 127,154 | class FeatureFusionBlock(nn.Module):
"""Feature fusion block.
"""
def __init__(self, features, activation, deconv=False, bn=False, expand=False, align_corners=True, size=None):
"""Init.
Args:
features (int): number of features
"""
super(FeatureFusionBlock, self)... | class FeatureFusionBlock(nn.Module):
"""Feature fusion block.
"""
def __init__(self, features, activation, deconv=False, bn=False, expand=False, align_corners=True, size=None):
"""Init.
Args:
features (int): number of features
"""
super(FeatureFusionBlock, self)... | output = xs[0]
if len(xs) == 2:
res = self.resConfUnit1(xs[1])
output = self.skip_add.add(output, res)
output = self.resConfUnit2(output)
if (size is None) and (self.size is None):
modifier = {"scale_factor": 2}
elif size is None:
... | """Forward pass.
Returns:
tensor: output
"""
output = xs[0]
if len(xs) == 2:
res = self.resConfUnit1(xs[1])
output = self.skip_add.add(output, res)
output = self.resConfUnit2(output)
if (size is None) and (self.size is None)... | 55 | 326 | 213 | 539 | import torch.nn as nn
def _make_scratch(in_shape, out_shape, groups=1, expand=False):
scratch = nn.Module()
out_shape1 = out_shape
out_shape2 = out_shape
out_shape3 = out_shape
if len(in_shape) >= 4:
out_shape4 = out_shape
if expand:
out_shape1 = out_shape
out_shape2 ... | import torch.nn as nn
def _make_scratch(in_shape, out_shape, groups=1, expand=False):
scratch = nn.Module()
out_shape1 = out_shape
out_shape2 = out_shape
out_shape3 = out_shape
if len(in_shape) >= 4:
out_shape4 = out_shape
if expand:
out_shape1 = out_shape
out_shape2 ... |
29,751 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/metric_depth/zoedepth/models/base_models/dpt_dinov2/blocks.py | 69,70 | 37,95 | forward | ResidualConvUnit | 78,95 | 70,95 | class ResidualConvUnit(nn.Module):
"""Residual convolution module.
"""
def __init__(self, features, activation, bn):
"""Init.
Args:
features (int): number of features
"""
super().__init__()
self.bn = bn
self.groups=1
self.conv1 = nn.Co... | class ResidualConvUnit(nn.Module):
"""Residual convolution module.
"""
def __init__(self, features, activation, bn):
"""Init.
Args:
features (int): number of features
"""
super().__init__()
self.bn = bn
self.groups=1
self.conv1 = nn.Co... |
out = self.activation(x)
out = self.conv1(out)
if self.bn==True:
out = self.bn1(out)
out = self.activation(out)
out = self.conv2(out)
if self.bn==True:
out = self.bn2(out)
if self.groups > 1:
out = self.conv_me... | """Forward pass.
Args:
x (tensor): input
Returns:
tensor: output
"""
out = self.activation(x)
out = self.conv1(out)
if self.bn==True:
out = self.bn1(out)
out = self.activation(out)
out = self.c... | 32 | 311 | 145 | 456 | import torch.nn as nn
def _make_scratch(in_shape, out_shape, groups=1, expand=False):
scratch = nn.Module()
out_shape1 = out_shape
out_shape2 = out_shape
out_shape3 = out_shape
if len(in_shape) >= 4:
out_shape4 = out_shape
if expand:
out_shape1 = out_shape
out_shape2 ... | import torch.nn as nn
def _make_scratch(in_shape, out_shape, groups=1, expand=False):
scratch = nn.Module()
out_shape1 = out_shape
out_shape2 = out_shape
out_shape3 = out_shape
if len(in_shape) >= 4:
out_shape4 = out_shape
if expand:
out_shape1 = out_shape
out_shape2 ... |
29,754 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/metric_depth/zoedepth/models/base_models/midas.py | 113,114 | 50,175 | get_size | Resize | 114,171 | 114,171 | class Resize(object):
"""Resize sample to given size (width, height).
"""
def __init__(
self,
width,
height,
resize_target=True,
keep_aspect_ratio=False,
ensure_multiple_of=1,
resize_method="lower_bound",
):
"""Init.
Args:
... | class Resize(object):
"""Resize sample to given size (width, height).
"""
def __init__(
self,
width,
height,
resize_target=True,
keep_aspect_ratio=False,
ensure_multiple_of=1,
resize_method="lower_bound",
):
"""Init.
Args:
... | # determine new height and width
scale_height = self.__height / height
scale_width = self.__width / width
if self.__keep_aspect_ratio:
if self.__resize_method == "lower_bound":
# scale such that output size is lower bound
if scale_width > scal... | # determine new height and width
scale_height = self.__height / height
scale_width = self.__width / width
if self.__keep_aspect_ratio:
if self.__resize_method == "lower_bound":
# scale such that output size is lower bound
if scale_width > scal... | 181 | 760 | 616 | 1,376 | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... |
29,755 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/metric_depth/zoedepth/models/depth_model.py | 57,58 | 35,153 | _infer_with_pad_aug | DepthModel | 75,99 | 58,99 | class DepthModel(nn.Module):
def __init__(self):
super().__init__()
self.device = 'cpu'
def to(self, device) -> nn.Module:
self.device = device
return super().to(device)
def forward(self, x, *args, **kwargs):
raise NotImplementedError
def _infer(sel... | class DepthModel(nn.Module):
def __init__(self):
super().__init__()
self.device = 'cpu'
def to(self, device) -> nn.Module:
self.device = device
return super().to(device)
def forward(self, x, *args, **kwargs):
raise NotImplementedError
def _infer(sel... | # assert x is nchw and c = 3
assert x.dim() == 4, "x must be 4 dimensional, got {}".format(x.dim())
assert x.shape[1] == 3, "x must have 3 channels, got {}".format(x.shape[1])
if pad_input:
assert fh > 0 or fw > 0, "atlease one of fh and fw must be greater than 0"
... | """
Inference interface for the model with padding augmentation
Padding augmentation fixes the boundary artifacts in the output depth map.
Boundary artifacts are sometimes caused by the fact that the model is trained on NYU raw dataset which has a black or white border around the image.
... | 132 | 1,536 | 404 | 1,940 | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... |
29,757 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/metric_depth/zoedepth/models/layers/attractor.py | 85,86 | 60,139 | forward | AttractorLayer | 94,139 | 86,139 | class AttractorLayer(nn.Module):
def __init__(self, in_features, n_bins, n_attractors=16, mlp_dim=128, min_depth=1e-3, max_depth=10,
alpha=300, gamma=2, kind='sum', attractor_type='exp', memory_efficient=False):
"""
Attractor layer for bin centers. Bin centers are bounded on the int... | class AttractorLayer(nn.Module):
def __init__(self, in_features, n_bins, n_attractors=16, mlp_dim=128, min_depth=1e-3, max_depth=10,
alpha=300, gamma=2, kind='sum', attractor_type='exp', memory_efficient=False):
"""
Attractor layer for bin centers. Bin centers are bounded on the int... | if prev_b_embedding is not None:
if interpolate:
prev_b_embedding = nn.functional.interpolate(
prev_b_embedding, x.shape[-2:], mode='bilinear', align_corners=True)
x = x + prev_b_embedding
A = self._net(x)
eps = 1e-3
A = A + ep... | """
Args:
x (torch.Tensor) : feature block; shape - n, c, h, w
b_prev (torch.Tensor) : previous bin centers normed; shape - n, prev_nbins, h, w
Returns:
tuple(torch.Tensor,torch.Tensor) : new bin centers normed and scaled; shape - n, nbins, h, w
... | 169 | 493 | 671 | 1,164 | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... |
29,758 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/metric_depth/zoedepth/models/layers/attractor.py | 164,165 | 139,209 | forward | AttractorLayerUnnormed | 173,209 | 165,209 | class AttractorLayerUnnormed(nn.Module):
def __init__(self, in_features, n_bins, n_attractors=16, mlp_dim=128, min_depth=1e-3, max_depth=10,
alpha=300, gamma=2, kind='sum', attractor_type='exp', memory_efficient=False):
"""
Attractor layer for bin centers. Bin centers are unbounded
... | class AttractorLayerUnnormed(nn.Module):
def __init__(self, in_features, n_bins, n_attractors=16, mlp_dim=128, min_depth=1e-3, max_depth=10,
alpha=300, gamma=2, kind='sum', attractor_type='exp', memory_efficient=False):
"""
Attractor layer for bin centers. Bin centers are unbounded
... | if prev_b_embedding is not None:
if interpolate:
prev_b_embedding = nn.functional.interpolate(
prev_b_embedding, x.shape[-2:], mode='bilinear', align_corners=True)
x = x + prev_b_embedding
A = self._net(x)
n, c, h, w = A.shape
... | """
Args:
x (torch.Tensor) : feature block; shape - n, c, h, w
b_prev (torch.Tensor) : previous bin centers normed; shape - n, prev_nbins, h, w
Returns:
tuple(torch.Tensor,torch.Tensor) : new bin centers unbounded; shape - n, nbins, h, w. Two outputs ... | 114 | 482 | 479 | 961 | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... |
29,759 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/metric_depth/zoedepth/models/layers/dist_layers.py | 29,30 | 1,122 | log_binom | 31,36 | 30,36 | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | n = n + eps
k = k + eps
return n * torch.log(n) - k * torch.log(k) - (n-k) * torch.log(n-k+eps)
| """ log(nCk) using stirling approximation """
n = n + eps
k = k + eps
return n * torch.log(n) - k * torch.log(k) - (n-k) * torch.log(n-k+eps)
| 22 | 1,622 | 63 | 1,685 | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | |
29,760 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/metric_depth/zoedepth/models/layers/dist_layers.py | 100,101 | 72,122 | forward | ConditionalLogBinomial | 110,122 | 101,122 | class ConditionalLogBinomial(nn.Module):
def __init__(self, in_features, condition_dim, n_classes=256, bottleneck_factor=2, p_eps=1e-4, max_temp=50, min_temp=1e-7, act=torch.softmax):
"""Conditional Log Binomial distribution
Args:
in_features (int): number of input channels in main feat... | class ConditionalLogBinomial(nn.Module):
def __init__(self, in_features, condition_dim, n_classes=256, bottleneck_factor=2, p_eps=1e-4, max_temp=50, min_temp=1e-7, act=torch.softmax):
"""Conditional Log Binomial distribution
Args:
in_features (int): number of input channels in main feat... | pt = self.mlp(torch.concat((x, cond), dim=1))
p, t = pt[:, :2, ...], pt[:, 2:, ...]
p = p + self.p_eps
p = p[:, 0, ...] / (p[:, 0, ...] + p[:, 1, ...])
t = t + self.p_eps
t = t[:, 0, ...] / (t[:, 0, ...] + t[:, 1, ...])
t = t.unsqueeze(1)
t = (self.max_t... | """Forward pass
Args:
x (torch.Tensor - NCHW): Main feature
cond (torch.Tensor - NCHW): condition feature
Returns:
torch.Tensor: Output log binomial distribution
"""
pt = self.mlp(torch.concat((x, cond), dim=1))
p, t = pt[:, :2, ...],... | 65 | 553 | 201 | 754 | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... |
29,761 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/metric_depth/zoedepth/models/layers/dist_layers.py | 51,52 | 36,72 | forward | LogBinomial | 62,72 | 52,72 | class LogBinomial(nn.Module):
def __init__(self, n_classes=256, act=torch.softmax):
"""Compute log binomial distribution for n_classes
Args:
n_classes (int, optional): number of output classes. Defaults to 256.
"""
super().__init__()
self.K = n_classes
se... | class LogBinomial(nn.Module):
def __init__(self, n_classes=256, act=torch.softmax):
"""Compute log binomial distribution for n_classes
Args:
n_classes (int, optional): number of output classes. Defaults to 256.
"""
super().__init__()
self.K = n_classes
se... | if x.ndim == 3:
x = x.unsqueeze(1) # make it nchw
one_minus_x = torch.clamp(1 - x, eps, 1)
x = torch.clamp(x, eps, 1)
y = log_binom(self.K_minus_1, self.k_idx) + self.k_idx * \
torch.log(x) + (self.K - 1 - self.k_idx) * torch.log(one_minus_x)
return self... | """Compute log binomial distribution for x
Args:
x (torch.Tensor - NCHW): probabilities
t (float, torch.Tensor - NCHW, optional): Temperature of distribution. Defaults to 1..
eps (float, optional): Small number for numerical stability. Defaults to 1e-4.
Retu... | 43 | 339 | 166 | 505 | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... |
29,762 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/metric_depth/zoedepth/models/layers/localbins_layers.py | 137,138 | 121,170 | forward | LinearSplitter | 142,170 | 138,170 | class LinearSplitter(nn.Module):
def __init__(self, in_features, prev_nbins, split_factor=2, mlp_dim=128, min_depth=1e-3, max_depth=10):
super().__init__()
self.prev_nbins = prev_nbins
self.split_factor = split_factor
self.min_depth = min_depth
self.max_depth = max_depth
... | class LinearSplitter(nn.Module):
def __init__(self, in_features, prev_nbins, split_factor=2, mlp_dim=128, min_depth=1e-3, max_depth=10):
super().__init__()
self.prev_nbins = prev_nbins
self.split_factor = split_factor
self.min_depth = min_depth
self.max_depth = max_depth
... | if prev_b_embedding is not None:
if interpolate:
prev_b_embedding = nn.functional.interpolate(prev_b_embedding, x.shape[-2:], mode='bilinear', align_corners=True)
x = x + prev_b_embedding
S = self._net(x)
eps = 1e-3
S = S + eps
n, c, h, w =... | """
x : feature block; shape - n, c, h, w
b_prev : previous bin widths normed; shape - n, prev_nbins, h, w
"""
if prev_b_embedding is not None:
if interpolate:
prev_b_embedding = nn.functional.interpolate(prev_b_embedding, x.shape[-2:], mode='bilinear'... | 163 | 304 | 598 | 902 | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... |
29,763 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/metric_depth/zoedepth/models/layers/localbins_layers.py | 116,117 | 99,121 | forward | Projector | 117,121 | 117,121 | class Projector(nn.Module):
def __init__(self, in_features, out_features, mlp_dim=128):
"""Projector MLP
Args:
in_features (int): input channels
out_features (int): output channels
mlp_dim (int, optional): hidden dimension. Defaults to 128.
"""
su... | class Projector(nn.Module):
def __init__(self, in_features, out_features, mlp_dim=128):
"""Projector MLP
Args:
in_features (int): input channels
out_features (int): output channels
mlp_dim (int, optional): hidden dimension. Defaults to 128.
"""
su... | return self._net(x)
| return self._net(x)
| 2 | 207 | 16 | 223 | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... |
29,764 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/metric_depth/zoedepth/models/layers/localbins_layers.py | 52,53 | 29,71 | forward | SeedBinRegressor | 56,71 | 53,71 | class SeedBinRegressor(nn.Module):
def __init__(self, in_features, n_bins=16, mlp_dim=256, min_depth=1e-3, max_depth=10):
"""Bin center regressor network. Bin centers are bounded on (min_depth, max_depth) interval.
Args:
in_features (int): input channels
n_bins (int, optiona... | class SeedBinRegressor(nn.Module):
def __init__(self, in_features, n_bins=16, mlp_dim=256, min_depth=1e-3, max_depth=10):
"""Bin center regressor network. Bin centers are bounded on (min_depth, max_depth) interval.
Args:
in_features (int): input channels
n_bins (int, optiona... | B = self._net(x)
eps = 1e-3
B = B + eps
B_widths_normed = B / B.sum(dim=1, keepdim=True)
B_widths = (self.max_depth - self.min_depth) * \
B_widths_normed # .shape NCHW
# pad has the form (left, right, top, bottom, front, back)
B_widths = nn.functional... | """
Returns tensor of bin_width vectors (centers). One vector b for every pixel
"""
B = self._net(x)
eps = 1e-3
B = B + eps
B_widths_normed = B / B.sum(dim=1, keepdim=True)
B_widths = (self.max_depth - self.min_depth) * \
B_widths_normed # .sh... | 72 | 384 | 263 | 647 | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... |
29,765 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/metric_depth/zoedepth/models/layers/localbins_layers.py | 91,92 | 71,99 | forward | SeedBinRegressorUnnormed | 95,99 | 92,99 | class SeedBinRegressorUnnormed(nn.Module):
def __init__(self, in_features, n_bins=16, mlp_dim=256, min_depth=1e-3, max_depth=10):
"""Bin center regressor network. Bin centers are unbounded
Args:
in_features (int): input channels
n_bins (int, optional): Number of bin centers.... | class SeedBinRegressorUnnormed(nn.Module):
def __init__(self, in_features, n_bins=16, mlp_dim=256, min_depth=1e-3, max_depth=10):
"""Bin center regressor network. Bin centers are unbounded
Args:
in_features (int): input channels
n_bins (int, optional): Number of bin centers.... | B_centers = self._net(x)
return B_centers, B_centers
| """
Returns tensor of bin_width vectors (centers). One vector b for every pixel
"""
B_centers = self._net(x)
return B_centers, B_centers
| 6 | 353 | 31 | 384 | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... |
29,766 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/metric_depth/zoedepth/models/layers/patch_transformer.py | 71,72 | 29,92 | forward | PatchTransformerEncoder | 80,92 | 72,92 | class PatchTransformerEncoder(nn.Module):
def __init__(self, in_channels, patch_size=10, embedding_dim=128, num_heads=4, use_class_token=False):
"""ViT-like transformer block
Args:
in_channels (int): Input channels
patch_size (int, optional): patch size. Defaults to 10.
... | class PatchTransformerEncoder(nn.Module):
def __init__(self, in_channels, patch_size=10, embedding_dim=128, num_heads=4, use_class_token=False):
"""ViT-like transformer block
Args:
in_channels (int): Input channels
patch_size (int, optional): patch size. Defaults to 10.
... | embeddings = self.embedding_convPxP(x).flatten(
2) # .shape = n,c,s = n, embedding_dim, s
if self.use_class_token:
# extra special token at start ?
embeddings = nn.functional.pad(embeddings, (1, 0))
# change to S,N,E format required by transformer
... | """Forward pass
Args:
x (torch.Tensor - NCHW): Input feature tensor
Returns:
torch.Tensor - SNE: Transformer output embeddings. S - sequence length (=HW/patch_size^2), N - batch size, E - embedding dim
"""
embeddings = self.embedding_convPxP(x).flatten(
... | 63 | 743 | 204 | 947 | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... |
29,767 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/metric_depth/zoedepth/models/model_io.py | 27,28 | 1,93 | load_state_dict | 34,54 | 28,54 | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | state_dict = state_dict.get('model', state_dict)
# if model is a DataParallel model, then state_dict keys are prefixed with 'module.'
do_prefix = isinstance(
model, (torch.nn.DataParallel, torch.nn.parallel.DistributedDataParallel))
state = {}
for k, v in state_dict.items():
if k.st... | """Load state_dict into model, handling DataParallel and DistributedDataParallel. Also checks for "model" key in state_dict.
DataParallel prefixes state_dict keys with 'module.' when saving.
If the model is not a DataParallel model but the state_dict is, then prefixes are removed.
If the model is a Dat... | 58 | 889 | 207 | 1,096 | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | |
29,768 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/metric_depth/zoedepth/trainers/builder.py | 28,29 | 1,49 | get_trainer | 41,49 | 29,49 | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | assert "trainer" in config and config.trainer is not None and config.trainer != '', "Trainer not specified. Config: {0}".format(
config)
try:
Trainer = getattr(import_module(
f"zoedepth.trainers.{config.trainer}_trainer"), 'Trainer')
except ModuleNotFoundError as e:
raise... | """Builds and returns a trainer based on the config.
Args:
config (dict): the config dict (typically constructed using utils.config.get_config)
config.trainer (str): the name of the trainer to use. The module named "{config.trainer}_trainer" must exist in trainers root module
Raises:
... | 38 | 517 | 132 | 649 | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | |
29,770 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/metric_depth/zoedepth/trainers/loss.py | 221,222 | 183,259 | forward | DiscreteNLLLoss | 222,259 | 222,259 | class DiscreteNLLLoss(nn.Module):
"""Cross entropy loss"""
def __init__(self, min_depth=1e-3, max_depth=10, depth_bins=64):
super(DiscreteNLLLoss, self).__init__()
self.name = 'CrossEntropy'
self.ignore_index = -(depth_bins + 1)
# self._loss_func = nn.NLLLoss(ignore_index=self.ig... | class DiscreteNLLLoss(nn.Module):
"""Cross entropy loss"""
def __init__(self, min_depth=1e-3, max_depth=10, depth_bins=64):
super(DiscreteNLLLoss, self).__init__()
self.name = 'CrossEntropy'
self.ignore_index = -(depth_bins + 1)
# self._loss_func = nn.NLLLoss(ignore_index=self.ig... | input = extract_key(input, KEY_OUTPUT)
# assert torch.all(input <= 0), "Input should be negative"
if input.shape[-1] != target.shape[-1] and interpolate:
input = nn.functional.interpolate(
input, target.shape[-2:], mode='bilinear', align_corners=True)
int... | input = extract_key(input, KEY_OUTPUT)
# assert torch.all(input <= 0), "Input should be negative"
if input.shape[-1] != target.shape[-1] and interpolate:
input = nn.functional.interpolate(
input, target.shape[-2:], mode='bilinear', align_corners=True)
int... | 114 | 439 | 378 | 817 | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... |
29,771 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/metric_depth/zoedepth/trainers/loss.py | 116,117 | 110,137 | forward | GradL1Loss | 117,137 | 117,137 | class GradL1Loss(nn.Module):
"""Gradient loss"""
def __init__(self):
super(GradL1Loss, self).__init__()
self.name = 'GradL1'
def forward(self, input, target, mask=None, interpolate=True, return_interpolated=False):
FILL_FUNC_BODY | class GradL1Loss(nn.Module):
"""Gradient loss"""
def __init__(self):
super(GradL1Loss, self).__init__()
self.name = 'GradL1'
def forward(self, input, target, mask=None, interpolate=True, return_interpolated=False):
FILL_FUNC_BODY | input = extract_key(input, KEY_OUTPUT)
if input.shape[-1] != target.shape[-1] and interpolate:
input = nn.functional.interpolate(
input, target.shape[-2:], mode='bilinear', align_corners=True)
intr_input = input
else:
intr_input = input
... | input = extract_key(input, KEY_OUTPUT)
if input.shape[-1] != target.shape[-1] and interpolate:
input = nn.functional.interpolate(
input, target.shape[-2:], mode='bilinear', align_corners=True)
intr_input = input
else:
intr_input = input
... | 52 | 93 | 247 | 340 | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... |
29,772 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/metric_depth/zoedepth/trainers/loss.py | 144,145 | 137,183 | _create_ord_label | OrdinalRegressionLoss | 145,168 | 145,168 | class OrdinalRegressionLoss(object):
def __init__(self, ord_num, beta, discretization="SID"):
self.ord_num = ord_num
self.beta = beta
self.discretization = discretization
def _create_ord_label(self, gt):
FILL_FUNC_BODY def __call__(self, prob, gt):
"""
:param prob: o... | class OrdinalRegressionLoss(object):
def __init__(self, ord_num, beta, discretization="SID"):
self.ord_num = ord_num
self.beta = beta
self.discretization = discretization
def _create_ord_label(self, gt):
FILL_FUNC_BODY def __call__(self, prob, gt):
"""
:param prob: o... | N,one, H, W = gt.shape
# print("gt shape:", gt.shape)
ord_c0 = torch.ones(N, self.ord_num, H, W).to(gt.device)
if self.discretization == "SID":
label = self.ord_num * torch.log(gt) / np.log(self.beta)
else:
label = self.ord_num * (gt - 1.0) / (self.beta -... | N,one, H, W = gt.shape
# print("gt shape:", gt.shape)
ord_c0 = torch.ones(N, self.ord_num, H, W).to(gt.device)
if self.discretization == "SID":
label = self.ord_num * torch.log(gt) / np.log(self.beta)
else:
label = self.ord_num * (gt - 1.0) / (self.beta -... | 115 | 288 | 407 | 695 | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... |
29,773 | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything | /home/hieuvd/dung_repo/raw/stars_02/LiheYoung_Depth-Anything/Depth-Anything/metric_depth/zoedepth/trainers/loss.py | 49,50 | 42,96 | forward | SILogLoss | 50,96 | 50,96 | class SILogLoss(nn.Module):
"""SILog loss (pixel-wise)"""
def __init__(self, beta=0.15):
super(SILogLoss, self).__init__()
self.name = 'SILog'
self.beta = beta
def forward(self, input, target, mask=None, interpolate=True, return_interpolated=False):
FILL_FUNC_BODY | class SILogLoss(nn.Module):
"""SILog loss (pixel-wise)"""
def __init__(self, beta=0.15):
super(SILogLoss, self).__init__()
self.name = 'SILog'
self.beta = beta
def forward(self, input, target, mask=None, interpolate=True, return_interpolated=False):
FILL_FUNC_BODY | input = extract_key(input, KEY_OUTPUT)
if input.shape[-1] != target.shape[-1] and interpolate:
input = nn.functional.interpolate(
input, target.shape[-2:], mode='bilinear', align_corners=True)
intr_input = input
else:
intr_input = input
... | input = extract_key(input, KEY_OUTPUT)
if input.shape[-1] != target.shape[-1] and interpolate:
input = nn.functional.interpolate(
input, target.shape[-2:], mode='bilinear', align_corners=True)
intr_input = input
else:
intr_input = input
... | 138 | 114 | 547 | 661 | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... | # MIT License
# Copyright (c) 2022 Intelligent Systems Lab Org
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, m... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.