-
-
Notifications
You must be signed in to change notification settings - Fork 12.1k
Description
Describe the issue:
Broadcast rules seem to indicate you can add dimensions of length one basically anywhere in an array shape. In particular, for adding dimensions to the end of the shape, the following work fine
import numpy as np
test = np.array([2, 3])
print(test[:, None])
print(np.expand_dims(test, axis=1)and each approach gives an array that looks like [[2], [3]], as expected. I wanted to do this with broadcast_to for more generic shapes, and it causes errors
Reproduce the code example:
import numpy as np
test = np.array([2, 3])
np.broadcast_to(test, (2, 1))Error message:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/path/to/mamba/mambaforge/lib/python3.11/site-packages/numpy/lib/_stride_tricks_impl.py", line 410, in broadcast_to
return _broadcast_to(array, shape, subok=subok, readonly=True)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/path/to/mamba/mambaforge/lib/python3.11/site-packages/numpy/lib/_stride_tricks_impl.py", line 349, in _broadcast_to
it = np.nditer(
^^^^^^^^^^
ValueError: operands could not be broadcast together with remapped shapes [original->remapped]: (2,) and requested shape (2,1)Python and NumPy Versions:
2.2.0
3.11.9 | packaged by conda-forge | (main, Apr 19 2024, 18:36:13) [GCC 12.3.0]
Runtime Environment:
[{'numpy_version': '2.2.0',
'python': '3.11.9 | packaged by conda-forge | (main, Apr 19 2024, 18:36:13) '
'[GCC 12.3.0]',
'uname': uname_result(system='Linux', node='Luthien', release='5.15.167.4-microsoft-standard-WSL2', version='#1 SMP Tue Nov 5 00:21:55 UTC 2024', machine='x86_64')},
{'simd_extensions': {'baseline': ['SSE', 'SSE2', 'SSE3'],
'found': ['SSSE3',
'SSE41',
'POPCNT',
'SSE42',
'AVX',
'F16C',
'FMA3',
'AVX2'],
'not_found': ['AVX512F',
'AVX512CD',
'AVX512_KNL',
'AVX512_KNM',
'AVX512_SKX',
'AVX512_CLX',
'AVX512_CNL',
'AVX512_ICL',
'AVX512_SPR']}},
{'architecture': 'Zen',
'filepath': /path/to/mamba/mambaforge/lib/libopenblasp-r0.3.27.so',
'internal_api': 'openblas',
'num_threads': 6,
'prefix': 'libopenblas',
'threading_layer': 'pthreads',
'user_api': 'blas',
'version': '0.3.27'}]
Context for the issue:
I wanted to multiply an array across its first one or two dimensions, broadcasting out along the other dimensions as usual, but automatic broadcasting wants the same number of dimensions in each array before multiplying. I could manage this with transpositions, but broadcast_to should be able to natively handle this.