模型的预测不起作用。 (面部表情 Kaggle)InvalidArgumentError:计算的输出大小将为负数:-1

问题描述 投票:0回答:1

首先,我对 Python 和 ML 非常陌生, 这意味着我不明白写的很多东西,但是 这个想法是从 Kaggle 中获取经过训练的模型并预测我的测试照片上的表情, 当它起作用时,然后尝试更深入地理解代码。 但我在这里很糟糕...

import tensorflow as tf
import cv2
import os
import matplotlib.pyplot as plt
import numpy as np
from tensorflow import keras
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Dense, Dropout, Flatten,BatchNormalization
from keras.preprocessing.image import load_img
from keras.preprocessing.image import img_to_array
from keras.preprocessing.image import ImageDataGenerator

file_name = 'kaggle_model.h5'
model_path = os.path.join('checkpoint',file_name)

final_model = tf.keras.models.load_model(model_path)
label_to_text = {0:'anger', 1:'disgust', 2:'fear', 3:'happiness', 4:'sadness', 5:'surprise', 6:'neutral'}
from tensorflow.keras.preprocessing import image
img_path='test2.jpg'
test_image=image.load_img(img_path,target_size=(48,48),color_mode='grayscale')
test_image=image.img_to_array(test_image)
print(test_image.shape)
plt.imshow(test_image)
plt.show()
test_image=np.expand_dims(test_image,0)
predicted_class = final_model.predict(test_image).argmax()
print(f'predicted lable is{label_to_text[predicted_class]}')

输出:

InvalidArgumentError:  Computed output size would be negative: -1 [input_size: 1, effective_filter_size: 3, stride: 1]
     [[node sequential/conv2d/Relu (defined at \AppData\Local\Temp\ipykernel_4280\3302287779.py:3) ]] [Op:__inference_predict_function_4813]

Function call stack:
predict_function

堆栈中有几个帖子存在相同的问题,但我无法在此基础上找出解决方案。非常感谢!

如果我尝试重塑图像,例如

test_image=test_image.reshape(1,48,48,1)

然后我遇到了另一个问题

ValueError: Input 0 of layer sequential is incompatible with the layer: expected axis -1 of input shape to have value 3 but received input with shape (None, 1, 48, 48, 1)

还有这个

test_image=test_image.reshape(48,48,1)
给出

InvalidArgumentError:  input depth must be evenly divisible by filter depth: 1 vs 3
     [[node sequential/conv2d/Relu (defined at \AppData\Local\Temp\ipykernel_4280\1071859005.py:1) ]] [Op:__inference_predict_function_6387]
python tensorflow keras conv-neural-network kaggle
1个回答
0
投票

从错误日志中可以明显看出一些形状错误,这使我们回到了 CNN、过滤器/内核和相关主题的基础知识,您可以在这个很酷的博客中探索更多相关主题。

来到代码修复部分,让我们一一查看它们并找到需要修正的地方。

1。 InvalidArgumentError:这里指定的张量形状小于滤波器,因此需要校正图像的数值表示。

2。 ValueError - 你可以参考这个 StackOverflow thread。但是,请附上相关片段。

下面的例子是对 Conv2D 的澄清

input_layer= 层.InputLayer(input_shape=(2,2,1)) conv1 = Layers.Conv2D(3,(2,2)) X= np.ones((2,2)) X =X.reshape(1,X.shape[0],X.shape1,1) # X 的形状是 4D, (1, 2, 2, 1) conv1(input_layer(X)) TL;DR

现在我们来详细说明一下上面的代码

第 1 行 input_layer 定义为 3D 形状,但在第 4 行 X 被重塑为 4D 形状,但与形状根本不匹配。 然而,为了将任何输入 X 馈送到 input_layer 或 Conv2D 必须 通过 4D 形状。

3. InvalidArgumentError :这可以通过将输入形状设为 4D 来解决。

© www.soinside.com 2019 - 2024. All rights reserved.