ValueError:layer sequential的输入0与层不兼容:输入形状的轴1应在Prediciton中具有值1

2024-04-19 11:11:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经建立并训练了我的CNN模型,我想对它进行测试。我在预测新数据时出错了。任何帮助都将不胜感激。 这段代码使用model.predict()给出预测。 错误是:

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

代码是:

import tensorflow as tf
from tensorflow import keras
import numpy as np
import cv2
import os
model_location =r'new_elephant_detection.h5' l
model=load_model(model_location) 
image_location=r''file_list=os.listdir(image_location) 
for f in file_list: 
f_path=os.path.join(image_location, f)  
img=cv2.imread(f_path) 
img=cv2.cvtColor(img, cv2.COLOR_BGR2RGB) 
img=cv2.resize(img, (128,128))
img=img/127.5-1   
img=np.expand_dims(img, axis=0)
prediction =model.predict (img, batch_size=1, verbose=0)
pred=np.argmax(prediction)
print ('for file ', f_path, ' the index of the predicted class is ', 
pred, ' with a probability of ', prediction[0][pred]  )

模型附于此:

import cv2
import numpy as np
from tensorflow.keras.utils import to_categorical
from sklearn.preprocessing import LabelBinarizer
from sklearn.model_selection import train_test_split
from skimage import io
import matplotlib.pyplot as plt
from pylab import *
img_rows, img_cols = 112, 112

images = []
labels = []

for category in Data_Dir:
  folder_path = os.path.join(Dataset,  category)
  for img in os.listdir(folder_path):
      img_path = os.path.join(folder_path, img)
      img=cv2.imread(img_path)

      try:
          grayscale_img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
          
          resized_img=cv2.resize(grayscale_img,(img_rows,img_cols))
          images.append(resized_img)
          labels.append(category)
          plt.subplot(121), imshow(img)
          plt.title('RGB format')
          plt.imshow(grayscale_img)
          plt.title('grayscale format')
          plt.show()
          

      except Exception as e:
          print('Exception:',e)

images=np.array(images)/255.0
images=np.reshape(images,(images.shape[0],img_rows,img_cols,1))

lb = LabelBinarizer()
labels = lb.fit_transform(labels)
labels = to_categorical(labels)
labels = np.array(labels)

(train_X, test_X, tarin_y, test_y) = train_test_split(images, labels, test_size=0.25,random_state=0)

from keras.models import Sequential
from keras.layers import Dense,Activation,Flatten,Dropout
from keras.layers import Conv2D,MaxPooling2D

num_classes = 2
batch_size = 32

model=Sequential()

model.add(Conv2D(64,(3,3),input_shape=(img_rows,img_cols,1)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2,2)))

model.add(Conv2D(128,(3,3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2,2)))

model.add(Flatten())
model.add(Dropout(0.5))
model.add(Dense(64,activation='relu'))
model.add(Dense(num_classes,activation='softmax'))

print(model.summary())

Tags: pathfromimportaddimglabelsmodelos
1条回答
网友
1楼 · 发布于 2024-04-19 11:11:33

当在代码中使用model.predict时,图像具有(128,128,3)形状,并且在axis=0上带有np.expand_dims,最终的输入形状变成(1,128,128,3)。但是在您的模型定义中input_shape应该是(112,112,1)(只有一个通道),因此消息:

...incompatible with the layer: expected axis -1 of input shape to have value 1 but received input with shape (1, 128, 128, 3)

为了确认模型能够预测值,可以执行的一个测试是使用cv2.COLOR_BGR2GRAY将颜色空间从RGB更改为灰度,并将图像大小调整为(112,112)

...
img=cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img=cv2.resize(img, (112,112))
img=img/127.5-1
img=np.expand_dims(img, axis=[0,3]) # expand to BATCH and CHANNEL axes
img.shape # (1, 112, 112, 1)
...

相关问题 更多 >