babysor/MockingBird · error · ValueError

has 'real' and 'imag' keys: {}

Error message

has 'real' and 'imag' keys: {}

What it means

to_torch_tensor converts dict inputs to ComplexTensor, but only if the dict has both 'real' and 'imag' keys. A dict missing either key raises ValueError listing the actual keys present.

Source

Thrown at models/ppg_extractor/nets_utils.py:350

        )

    """
    # If numpy, change to torch tensor
    if isinstance(x, np.ndarray):
        if x.dtype.kind == 'c':
            # Dynamically importing because torch_complex requires python3
            from torch_complex.tensor import ComplexTensor
            return ComplexTensor(x)
        else:
            return torch.from_numpy(x)

    # If {'real': ..., 'imag': ...}, convert to ComplexTensor
    elif isinstance(x, dict):
        # Dynamically importing because torch_complex requires python3
        from torch_complex.tensor import ComplexTensor

        if 'real' not in x or 'imag' not in x:
            raise ValueError("has 'real' and 'imag' keys: {}".format(list(x)))
        # Relative importing because of using python3 syntax
        return ComplexTensor(x['real'], x['imag'])

    # If torch.Tensor, as it is
    elif isinstance(x, torch.Tensor):
        return x

    else:
        error = ("x must be numpy.ndarray, torch.Tensor or a dict like "
                 "{{'real': torch.Tensor, 'imag': torch.Tensor}}, "
                 "but got {}".format(type(x)))
        try:
            from torch_complex.tensor import ComplexTensor
        except Exception:
            # If PY2
            raise ValueError(error)
        else:
            # If PY3

View on GitHub (pinned to 28dc5e14f1)

Solutions

  1. Rename keys to 'real' and 'imag' before calling
  2. Pass torch.Tensor or numpy array directly if the data is real-valued
  3. Inspect x.keys() in the error message to see what you actually passed

Example fix

# before
x = {'re': a, 'im': b}
t = to_torch_tensor(x)

# after
x = {'real': a, 'imag': b}
t = to_torch_tensor(x)
Defensive patterns

Strategy: type-guard

Validate before calling

if isinstance(x, dict):
    assert {'real', 'imag'} <= set(x.keys()), f'keys: {list(x)}'

Type guard

def is_complex_dict(x) -> bool:
    return isinstance(x, dict) and 'real' in x and 'imag' in x

Prevention

When it happens

Trigger: Passing a dict to to_torch_tensor whose keys are not exactly containing 'real' and 'imag', e.g. {'re': ..., 'im': ...} or a features dict with other metadata keys.

Common situations: Loading numpy complex features saved as dicts with different key names; feeding a generic feature dict where a complex tensor was expected.

Related errors


AI-assisted analysis of babysor/MockingBird@28dc5e14f1 (2026-08-27). Data as JSON: /api/errors/010d637640c8bde2. Report an issue: GitHub.