TensorDictBase.var#
- TensorDictBase.var(dim: int | Tuple[int] | Literal['feature'] = NO_DEFAULT, keepdim: bool = NO_DEFAULT, *, correction: int = 1, reduce: bool | None = None, key_transform: Callable[[NestedKey], NestedKey] | None = None) Self | Tensor#
Returns the variance of every leaf, over all its elements or along batch dimensions.
- Parameters:
dim (int, tuple of int or str, optional) – the batch dimensions to reduce. A negative
dimcounts from the end of the batch dimensions."feature"reduces the feature dimensions of each leaf instead, and the result keeps the batch size. Defaults toNone, which reduces every element of each leaf, and the result has an empty batch size.keepdim (bool, optional) – if
True, the reduced batch dimensions are kept with size 1. Not allowed withdim="feature". Defaults toFalse.
- Keyword Arguments:
correction (int, optional) – the difference between the sample size and the degrees of freedom. Defaults to
1, Bessel’s correction.reduce (bool, optional) – if
True, reduces all the leaves together and returns a single tensor. Withoutdim, the result is a scalar. With an intdim, the leaves are concatenated alongdimfirst, so they must have the same number of dimensions. Withdim="feature", the result has the batch size as its shape. With feature dimensions, a negativedimcounts from the end of each leaf. Starting with TensorDict 0.17, the default will change to counting it from the end of the batch dimensions, as withreduce=False. Defaults toFalse.key_transform (Callable, optional) – a function applied to the name of every entry of the result, at every level of nesting, such as
lambda key: f"var_{key}". Ignored whenreduce=True. Defaults toNone.
- Returns:
A new tensordict, or a tensor if
reduce=True.
Note
With
dim="feature"and the defaultcorrection, a leaf without feature dimensions gives NaN, and torch warns that the degrees of freedom are<= 0.Examples
>>> import torch >>> from tensordict import TensorDict >>> _ = torch.manual_seed(0) >>> td = TensorDict( ... a=torch.randn(3, 4, 5), ... b=TensorDict(c=torch.randn(3, 4, 5, 6), batch_size=(3, 4, 5)), ... batch_size=(3, 4), ... ) >>> td.var(dim=0).batch_size torch.Size([4]) >>> td.var(dim=0)["b", "c"].shape torch.Size([4, 5, 6]) >>> td.var()["a"].shape torch.Size([]) >>> td.var(dim="feature")["a"].shape torch.Size([3, 4]) >>> td.var(reduce=True) tensor(1.0535) >>> list(td.var(key_transform=lambda key: f"var_{key}").keys(True, True)) ['var_a', ('var_b', 'var_c')]
With
reduce=Trueand an intdim, the leaves are concatenated alongdimbefore the reduction:>>> td = TensorDict(a=torch.ones(3, 4), b=torch.ones(3, 4), batch_size=(3, 4)) >>> td.var(dim=0, reduce=True) tensor([0., 0., 0., 0.]) >>> td.var(dim="feature", reduce=True) tensor([[0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 0.]])
Every tensordict class and every tensorclass has this method. For the other methods, see Methods by task.