Last Updated on 2022-08-08 by Clay
Problem
Today, when I tracing some source code of model inference, I encountered the problem cannot be executed. The error message as follows:
IndexError: boolean index did not match indexed array along dimension 0; dimension is 485 but corresponding boolean dimension is 488
The most intuitive understanding of this error message is that the corresponding array dimensions are inconsistent.
We understand the point, then we solve the problem.
Problem Reproduce
If you want to make the same problem, you can use a value-array to correspond another boolean-array.
# coding: utf-8
import numpy as np
def main():
nums = np.array([1, 2, 3, 4, 5])
bools = np.array([True, False, True])
print(nums[bools])
if __name__ == "__main__":
main()
Output:
Traceback (most recent call last):
File "test.py", line 13, in <module>
main()
File "test.py", line 9, in main
print(nums[bools])
IndexError: boolean index did not match indexed array along dimension 0; dimension is 5 but corresponding boolean dimension is 3
After execution we get an error message similar to the title of the article. Obviously, this is caused by the different lengths.
So the solutions to this problem is:
- Print out the shape of array
- Adjust two array to the same length
For example, the code like the following will work fine:
# coding: utf-8
import numpy as np
def main():
nums = np.array([1, 2, 3, 4, 5])
bools = np.array([True, False, True, True, False])
print(nums[bools])
if __name__ == "__main__":
main()
Output:
[1 3 4]
References
- https://cumsum.wordpress.com/2021/03/07/numpy-indexerror-boolean-index-did-not-match-indexed-array-along-dimension-xx-dimension-is-x-but-corresponding-boolean-dimension-is-y/
- https://stackoverflow.com/questions/72060723/i-am-having-a-userwarning-unknown-classes-when-using-multilabelbinarizer