How to fix unhashable type nd.array error

Viewed 49

I am running this piece of code:

def fix_dimension(img):
    new_img = np.zeros((28, 28, 3))
    for i in range(3):
        new_img[:, :, i] = img
    return new_img


def show_results():
    dic = {}
    characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    for i, c in enumerate(characters):
        dic[i] = c

    output = []
    for i, ch in enumerate(char):  # iterating over the characters
        img_ = cv2.resize(ch, (28, 28), interpolation=cv2.INTER_AREA)
        img = fix_dimension(img_)
        img = img.reshape(1, 28, 28, 3)  # preparing image for the model
        # predicted = model.predict_classes(img, verbose=0) #predicting the class
        predict_x = model.predict(img)
        classes_x = np.argmax(predict_x, axis=1)
        character = dic[classes_x]
        output.append(character)  # storing the result in a list

    plate_number = ''.join(output)
    return plate_number


print(show_results())

And I am getting the following error:

TypeError Traceback (most recent call last) 
Untitled-2.ipynb Cell 23 in <cell line: 28>() 25 plate_number = ''.join(output) 26 return plate_number ---> 28 print(show_results()) Untitled-2.ipynb Cell 23 in show_results() 20 predict_x=model.predict(img) 21 classes_x=np.argmax(predict_x,axis=1) ---> 22 character = dic[classes_x] 23 output.append(character) #storing the result in a list 25 plate_number = ''.join(output)
TypeError: unhashable type: 'numpy.ndarray'
1 Answers

These lines are getting you in trouble:

...
predict_x = model.predict(img)
classes_x = np.argmax(predict_x, axis=1)
character = dic[classes_x]  # causes the `TypeError`
...

You are trying to get an item from your dic dictionary by passing a non-hashable type -- a np.ndarray -- to the getter as the key.

It seems that the predict_x array has more than one dimension. And the argmax function returns an array (not a scalar) when called with the axis parameter like this. Therefore classes_x is an array of integers, not an integer.

Related