v923z / micropython-ulab

a numpy-like fast vector module for micropython, circuitpython, and their derivatives
https://micropython-ulab.readthedocs.io/en/latest
MIT License
432 stars 117 forks source link

[BUG] Numpy array slicing produces scalar. #696

Closed kwagyeman closed 3 days ago

kwagyeman commented 3 days ago

I think I found a bug with slicing arrays:

from ulab import numpy as np

# Example bounding_boxes array
bounding_boxes = np.array([
    [0, 0, 0, 0, 0, 0.1, 0.2, 0.7, 0.3],
    [0, 0, 0, 0, 0, 0.3, 0.4, 0.3, 0.1],
    [0, 0, 0, 0, 0, 0.6, 0.1, 0.3, 0.2]
])

TINY_YOLO_V2_CLASSES = 5

class_scores_raw = bounding_boxes[:, TINY_YOLO_V2_CLASSES:]

def softmax(x):
    max_x = np.max(x, axis=1)
    e_x = np.exp(x - max_x.reshape((x.shape[0], 1)))
    sum_e_x = np.sum(e_x, axis=1)
    return e_x / sum_e_x.reshape((x.shape[0], 1))

bb_classes = np.argmax(softmax(class_scores_raw), axis=1)

print(bb_classes)

Works and outputs array([2, 1, 0], dtype=int16).

Now if I modify the array to be:

from ulab import numpy as np

# Example bounding_boxes array
bounding_boxes = np.array([
    [0, 0, 0, 0, 0, 0.1],
])

TINY_YOLO_V2_CLASSES = 5

class_scores_raw = bounding_boxes[:, TINY_YOLO_V2_CLASSES:]

def softmax(x):
    max_x = np.max(x, axis=1)
    e_x = np.exp(x - max_x.reshape((x.shape[0], 1)))
    sum_e_x = np.sum(e_x, axis=1)
    return e_x / sum_e_x.reshape((x.shape[0], 1))

bb_classes = np.argmax(softmax(class_scores_raw), axis=1)

print(bb_classes)

You get:

Traceback (most recent call last):
  File "<stdin>", line 18, in <module>
  File "<stdin>", line 14, in softmax
AttributeError: 'float' object has no attribute 'reshape'

This is because bounding_boxes[:, TINY_YOLO_V2_CLASSES:] produced a float in this case instead of a numpy array with size 1x1.

I think this is a bug? As slices, even if they produce an array with one value, should still be numpy arrays.

kwagyeman commented 3 days ago

Yeah, actually, it's not:

bounding_boxes[:, TINY_YOLO_V2_CLASSES:]

This produces: array([[0.1]], dtype=float32)

kwagyeman commented 3 days ago

Okay, actually, the issue is the lack of keepdims=True.