API Keras predict_classes() 的功能替代解决方案

Functional API Keras alternate solution for predict_classes()

请参考 for my previous question for background information. As per suggested by Nassim Ben。我使用函数 API 训练了双路径架构模型。现在我觉得卡住了,因为我需要预测每个像素的 class。这是相同的代码:

    imgs = io.imread(test_img).astype('float').reshape(5,240,240)
    plist = []

 # create patches from an entire slice
            for img in imgs[:-1]:
                if np.max(img) != 0:
                    img /= np.max(img)
                p = extract_patches_2d(img, (33,33))
                plist.append(p)
            patches = np.array(zip(np.array(plist[0]), np.array(plist[1]), np.array(plist[2]), np.array(plist[3])))

    # predict classes of each pixel based on model
            full_pred = self.model_comp.predict_classes(patches)
            fp1 = full_pred.reshape(208,208)

但是根据github-link predict_classes()是不可用的。所以我的问题是我可以尝试其他选择吗?

事实上,predict_classes 不适用于功能模型,因为在某些情况下使用它可能没有意义。 但是,存在 "one liner" 解决方案:

y_classes = keras.utils.np_utils.probas_to_classes(self.model_comp.predict(patches))

这在keras 1.2.2中有效,不确定keras 2.0,我在源代码中找不到该函数。但这并没有什么不好的,你的模型输出了属于每个 class 的概率向量。该函数所做的只是获取 argmax 并输出对应于最高概率的 class。

希望对您有所帮助。

Nassim 的回答很好,但我想与您分享我在类似任务中的经验:

  1. 切勿使用 predict_proba Keras 作为版本。 你可以找到原因。
  2. 大多数用于将预测转化为 classes 的方法都没有考虑到您的数据统计信息。在图像分割的情况下——通常检测对象比检测背景更重要。出于这个原因,我建议您对每个 class 使用从 precision-recall 曲线获得的阈值。在这种情况下 - 您需要设置一个 precision == recall 的阈值(或者它尽可能接近)。获得阈值后 - 您需要为 class 预测编写自定义函数。