简体   繁体   English

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

[英]Keras-TF model.predict() gave me wrong result

I just trained my CNN model which has the layer details below:我刚刚训练了我的 CNN model,它的层详细信息如下:

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'])

My model has about 95.xxx% accuracy on keras validating/testing result.我的 model 在 keras 验证/测试结果上的准确率约为95.xxx%

And when I imported the h5 file to test the prediction of an image, I did:当我导入 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')

I tested with a sample blank white image, and the prediction gave me Banana result, even though it should be Not banana for sure.我用一个空白的白色图像样本进行了测试,预测给了我香蕉结果,即使它肯定应该不是香蕉 How could it be wrong in this very simple test case?在这个非常简单的测试用例中怎么可能出错? Or is there anything wrong with my model.predict(img) input image?或者我的model.predict(img)输入图像有什么问题吗?

Since there is no class named Not banana in your dataset, it gives only the classes that you've trained in your network.由于您的数据集中没有名为Notbanana的 class,因此它仅提供您在网络中训练的类。

In order to have that behavior on your model, you should set a class e.g: Background on your model and train it with certain amount of Background labeled images.为了在您的 model 上具有该行为,您应该设置一个 class例如:您的 model 上的背景并使用一定数量的背景标记图像对其进行训练。 Otherwise it would give the result that most probable one in your output vector i.e the most probable class even if it's a blank image.否则,它会给出 output 向量中最可能的结果,最可能的 class 即使它是空白图像。

OR或者

You can train a classification model along with the localization and classification only occurs in localized objects and your problem may be corrected.您可以训练分类 model 以及仅在本地化对象中发生的定位和分类,您的问题可能会得到纠正。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM