votes up 1

operands could not be broadcast together with shapes (param0)

Package:
dask
github stars 8734
Exception Class:
ValueError

Raise code

for sizes in zip_longest(*map(reversed, shapes), fillvalue=-1):
        if np.isnan(sizes).any():
            dim = np.nan
        else:
            dim = 0 if 0 in sizes else np.max(sizes)
        if any(i not in [-1, 0, 1, dim] and not np.isnan(i) for i in sizes):
            raise ValueError(
                "operands could not be broadcast together with "
                "shapes {0}".format(" ".join(map(str, shapes)))
            )
        out.append(dim)
    return tuple(reversed(out))


def elemwise

Ways to fix

votes up 1 votes down

This exception is raised due to the input shapes that cannot be successfully broadcast together.

What do we mean by "input shapes that cannot be successfully broadcast together"?

Simply speaking broadcasting is just an an operation that stretches or duplicates a smaller array to be the same shape as the bigger array so that other operations can be done on the given arrays.

Two shapes are called broadcastable if the following conditions are met.

  1. they are equal, or
  2. one of them is 1

The functions that this exception is raised at determines the output shape from broadcasting arrays. It takes the shapes of two arrays and returns the output broadcasted shape. If the shapes are not broadcastable this specific exception gets thrown.

Here is a sample code to reproduce the exception.

from dask.array.core import broadcast_shapes
shape = broadcast_shapes((6,2), (6, 4))
print(shape)

---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-14-68da43b24179> in <module>()  1 from dask.array.core import (  2 broadcast_shapes) ----> 3 shape = broadcast_shapes((6,2), (6, 4))  4 print(shape) 
/usr/local/lib/python3.7/dist-packages/dask/array/core.py in broadcast_shapes(*shapes)  3823 raise ValueError(  3824 "operands could not be broadcast together with " -> 3825 "shapes {0}".format(" ".join(map(str, shapes)))  3826 )  3827 out.append(dim) 
ValueError: operands could not be broadcast together with shapes (6, 2) (6, 4)

Fixed version of the code:

Notice that the second value is set to 1 to make the shapes broadcastable.

from dask.array.core import broadcast_shapes
shape = broadcast_shapes((6,1), (6, 4))
print(shape)

(6, 4)

Dec 31, 2021 kellemnegasi answer
kellemnegasi 22.6k

Add a possible fix

Please authorize to post fix