在keras中使用CRF进行二进制分割时的形状错误

Shape error when using CRF for binary segmentation in keras

我正在尝试将 CRF 层应用于我的网络以进行二进制分割,但它会导致错误 ValueError: Shapes (?, 1, 1) and (?, 336, 1) are not compatible

我想输出一个形状为 (batch_size, 224, 336, 1) 的张量。根据错误,引入 CRF 后 img_height 似乎已丢失。

下面是一些描述模型的示例代码。没有最后的 CRF 它工作得很好。

import keras
from keras.layers import UpSampling2D, Conv2D, Activation, MaxPooling2D
from keras_contrib.layers import CRF

img_width, img_height = 336, 224
kernel_size = 7

input=keras.engine.topology.Input(shape=(img_height, img_width, 3))

e=Conv2D(32,(kernel_size,kernel_size),padding='same')(input)
e1=Activation('relu')(e)
e=MaxPooling2D(pool_size=(2, 2))(e1)

e=Conv2D(64,(kernel_size,kernel_size),padding='same')(e)
e2=Activation('relu')(e)
e=MaxPooling2D(pool_size=(2, 2))(e2)

#Decoder layers
d=UpSampling2D()(e)
d=Conv2D(64,(kernel_size,kernel_size),padding='same')(d)
d=Activation('relu')(d)

d=UpSampling2D()(d)
d=Conv2D(32,(kernel_size,kernel_size),padding='same')(d)
d=Activation('relu')(d)

d=Conv2D(1,(1,1),padding='valid')(d)
d=Activation('sigmoid')(d)

out=CRF(1, sparse_target=True)(d) 

autoencoder = Model(inputs=input, outputs=out)

将 CRF 添加到我的分割网络的正确方法是什么?

事实证明,keras_contrib.layers.CRF 仅适用于顺序数据,不适用于空间数据。要使用空间数据,densecrf library works. It appears that it cannot be used during training, only for post-processing. I used a tutorial to implement this, which can be found here: http://warmspringwinds.github.io/tensorflow/tf-slim/2016/12/18/image-segmentation-with-tensorflow-using-cnns-and-conditional-random-fields/