我已经建立并训练了我的CNN模型,我想测试它。当我预测新数据时,我得到了一个错误。任何帮助都会很感激。这段代码使用model.predict()
给出预测。错误是:
ValueError: layer sequential的输入0与layer不兼容:期望输入形状的轴-1值为1,但接收到的输入形状为(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())
当在代码中使用model.predict
时,图像具有形状(128,128,3)
,并且np.expand_dims
超过axis=0
,最终输入形状变为(1,128,128,3)
。但是在您的模型定义中,input_shape
被期望为(112,112,1)
(只有一个通道),因此消息:
…与层不兼容:期望输入形状的轴-1值为1,但接收到的输入形状为(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)
...