python - ValueError:层顺序的输入 0 与层不兼容:输入形状的预期轴 -1 在 Prediciton 中具有值 1
问题描述
我已经建立并训练了我的 CNN 模型,我想对其进行测试。当我预测新数据时出现错误。任何帮助,将不胜感激。此代码使用model.predict()
来给出预测。错误是:
ValueError:层顺序的输入 0 与层不兼容:输入形状的预期轴 -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)
您可以进行一项测试以确认模型能够预测一个值,即RGB
使用将颜色空间从灰度更改为灰度cv2.COLOR_BGR2GRAY
,并将图像大小调整为(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)
...
推荐阅读
- reactjs - [Swiper][Gatsby] 当有 3 张或更多幻灯片时,缩略图滑块有多个活动幻灯片
- javascript - 如何在没有 onChange 事件的情况下做出反应
- c# - 保持应用程序特定字段与数据库同步
- c++ - 如何使用英特尔内在函数移动数组的元素
- typescript - TypeScript 类定义
- javascript - 使用 Typescript 和 React Hooks 反应 HOC
- jasmine - 如何等待服务的结果?
- javascript - VueJS bcrypt 实现
- javascript - 评估数组平均值的问题
- python - 我在绘制球体和曲线时遇到问题