python - ValueError at/image/Tensor Tensor ("activation_5/Softmax:0", shape=(?, 4), dtype=float32) 不是这个图的元素

标签 python django machine-learning tensorflow keras

我正在构建一个图像处理分类器,此代码是一个 API,用于预测整个代码正在运行的图像的图像类,除了这一行 (pred = model.predict_classes(test_image)) 此 API 是在 Django 框架中制作的,并且我正在使用 python 2.7

如果我像往常一样运行这段代码(没有创建 API),那么它运行完美

def classify_image(request):
if request.method == 'POST' and request.FILES['test_image']:

    fs = FileSystemStorage()
    fs.save(request.FILES['test_image'].name, request.FILES['test_image'])


    test_image = cv2.imread('media/'+request.FILES['test_image'].name)

    if test_image is not None:
        test_image = cv2.resize(test_image, (128, 128))
        test_image = np.array(test_image)
        test_image = test_image.astype('float32')
        test_image /= 255
        print(test_image.shape)
    else:
        print('image didnt load')

    test_image = np.expand_dims(test_image, axis=0)
    print(test_image)
    print(test_image.shape)

    pred = model.predict_classes(test_image)
    print(pred)

return JsonResponse(pred, safe=False)

最佳答案

您的 test_image 和 tensorflow 模型的输入不匹配。

# Your image shape is (, , 3)
test_image = cv2.imread('media/'+request.FILES['test_image'].name)

if test_image is not None:
    test_image = cv2.resize(test_image, (128, 128))
    test_image = np.array(test_image)
    test_image = test_image.astype('float32')
    test_image /= 255
    print(test_image.shape)
else:
    print('image didnt load')

# Your image shape is (, , 4)
test_image = np.expand_dims(test_image, axis=0)
print(test_image)
print(test_image.shape)

pred = model.predict_classes(test_image)

以上只是假设。如果你想调试,我想你应该打印你的图像大小并与你的模型定义的第一个布局进行比较。并检查大小(宽度、高度、深度)是否匹配

关于python - ValueError at/image/Tensor Tensor ("activation_5/Softmax:0", shape=(?, 4), dtype=float32) 不是这个图的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47295025/

相关文章:

python - 类型错误 : destroy() takes 0 positional arguments but 1 was given

python - pandas 方式将一天中的时间(有效 datetime.time)转换为浮点变量

python - 更改配置后收到意外的日志消息

django - 获取外部数据并在 django admin 中填充表单

machine-learning - Keras/机器学习 : Any pros and cons of flattening input data vs having a higher dimensional input?

python - 什么时候应该将一列作为索引添加到 pandas 中的数据框

python - 如何在没有数据库的情况下制作自定义表单 - DJANGO

json - 在python中将pymongo查询集序列化为json

python - Sklearn - 发现输入变量的样本数量不一致 : [16512, 4128]

python - 我需要一个简洁的数据结构建议来存储非常大的数据集(在 Python 中训练朴素贝叶斯)