Keras-TF model.predict()给了我错误的结果

时间:2019-10-03 01:48:06

标签: python tensorflow keras

我刚刚训练了CNN模型,该模型具有以下图层详细信息:

model = Sequential()
model.add(Conv2D(100, (3, 3), input_shape=(100, 100, 1), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(120, (5, 5), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(140, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(rate=0.5))
model.add(Flatten())
model.add(Dense(200, activation='relu'))
model.add(Dropout(rate=0.5))
model.add(Dense(100, activation='relu'))
model.add(Dropout(rate=0.5))
model.add(Dense(num_classes, activation='softmax'))
model.compile(Adam(lr=0.001), loss='categorical_crossentropy', metrics=['accuracy'])

我的模型在喀拉拉邦验证/测试结果上的准确度大约为 95.xxx%

当我导入h5文件以测试图像的预测时,我做了:

def grayscale(img):
  img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  return img

def equalize(img):
  img = cv2.equalizeHist(img)
  return img

def preprocessing(img):
  gray = grayscale(img)
  eq = equalize(gray)
  return eq / 255

image = cv2.imread("sample.jpg")
print("Loading model...")
model = load_model("model.h5")
classes = pd.read_csv('dataset.csv', header=0, usecols=['BananaOrNot']).values

image = preprocessing(image)
image = image.reshape(100, 100, 1)
image = np.expand_dims(image, axis=0)
y_prob = model.predict(image)
class_idx = y_prob.argmax(axis=-1)[0]
print(classes[class_idx][0]) # it produced wrong result (should be 'not banana', got 'banana')

我用样本空白图像进行了测试,尽管可以确定不是香蕉,但预测仍给出了香蕉的结果。在这个非常简单的测试用例中怎么会出错?还是我的model.predict(img)输入图片有问题?

1 个答案:

答案 0 :(得分:0)

由于数据集中没有名为非香蕉的课程,因此它仅提供您在网络中训练过的课程。

为了在模型上具有该行为,您应该在模型上设置类 e.g:Background ,并使用一定数量的 Background 标记图像对其进行训练。否则,即使输出图像为空白图像,它也会使输出向量中最可能的一个结果成为最可能的类。

OR

您可以与本地化一起训练分类模型,并且分类仅在本地化的对象中发生,并且您的问题可能会得到纠正。