如何修复TypeError: unhashable type: 'numpy.ndarray'错误?
解决TypeError: unhashable type: 'numpy.ndarray'错误
错误原因
np.argmax(predict_x, axis=1)返回的是一维numpy数组(哪怕只有一个预测结果,格式也是类似array([3])的数组),而字典dic的键是整数类型。numpy数组属于不可哈希类型,无法直接作为字典的键,因此触发该错误。
修复方案
从classes_x这个一维数组中提取出单个整数元素即可,三种常用方式任选其一:
- 通过索引取值:
classes_x[0] - 转换为Python原生整数:
int(classes_x) - 使用numpy数组的
.item()方法:classes_x.item()
修改后的完整代码
import numpy as np import cv2 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[0]] output.append(character) # storing the result in a list plate_number = ''.join(output) return plate_number print(show_results())
内容的提问来源于stack exchange,提问作者Akshaya K Ravikumar
相关产品推荐
相关产品推荐

