我对sparse_softmax_cross_entropy
TensorFlow 中的成本函数有疑问。
我想在语义分割上下文中使用它,其中我使用自动编码器架构,该架构使用典型的卷积操作对图像进行下采样以创建特征向量。这个向量比上采样(使用conv2d_transpose
和一个一个的卷积来创建输出图像。因此,我的输入由形状为 的单通道图像组成(1,128,128,1)
,其中第一个索引表示批量大小,最后一个索引表示通道数。图像的像素当前是0
或1
。所以每个像素都映射到一个类。自动编码器的输出图像遵循相同的规则。因此,我不能使用任何预定义的成本函数,而不是MSE
前面提到的一个。
网络与MSE
. 但我无法让它与sparse_softmax_cross_entropy
. 在这种情况下,这似乎是正确的成本函数,但我对logits
. 官方文档说 logits 应该有 shape (d_i,...,d_n,num_classes)
。我试图忽略该num_classes
部分,但这会导致一个错误,指出只[0,1)
允许间隔。当然,我需要指定将允许间隔变为的类数,[0,2)
因为排他上限显然是num_classes
.
有人可以解释如何将我的输出图像转换为所需的 logits 吗?
成本函数的当前代码是:
self._loss_op = tf.reduce_mean((tf.nn.sparse_softmax_cross_entropy_with_logits(labels=tf.squeeze(self._target_placeholder, [3]), logits=self._model, name="Loss")))
挤压删除标签输入的最后一个维度,为 的标签创建形状[1 128 128]
。这会导致以下异常:
tensorflow.python.framework.errors_impl.InvalidArgumentError: Received a label value of 1 which is outside the valid range of [0, 1).
编辑:
根据要求,这是一个在全卷积网络的上下文中验证成本函数行为的最小示例:
constructor
剪断:
def __init__(self, img_channels=1, img_width=128, img_height=128):
...
self._loss_op = None
self._learning_rate_placeholder = tf.placeholder(tf.float32, [], 'lr')
self._input_placeholder = tf.placeholder(tf.float32, [None, img_width, img_height, img_channels], 'x')
self._target_placeholder = tf.placeholder(tf.float32, [None, img_width, img_height, img_channels], 'y')
self._model = self.build_model()
self.init_optimizer()
build_model()
剪断:
def build_model(self):
with tf.variable_scope('conv1', reuse=tf.AUTO_REUSE):
#not necessary
x = tf.reshape(self._input_placeholder, [-1, self._img_width, self._img_height, self._img_channels])
conv1 = tf.layers.conv2d(x, 32, 5, activation=tf.nn.relu)
conv1 = tf.layers.max_pooling2d(conv1, 2, 2)
with tf.variable_scope('conv2', reuse=tf.AUTO_REUSE):
conv2 = tf.layers.conv2d(conv1, 64, 3, activation=tf.nn.relu)
conv2 = tf.layers.max_pooling2d(conv2, 2, 2)
with tf.variable_scope('conv3_red', reuse=tf.AUTO_REUSE):
conv3 = tf.layers.conv2d(conv2, 1024, 30, strides=1, activation=tf.nn.relu)
with tf.variable_scope('conv4_red', reuse=tf.AUTO_REUSE):
conv4 = tf.layers.conv2d(conv3, 64, 1, strides=1, activation=tf.nn.relu)
with tf.variable_scope('conv5_up', reuse=tf.AUTO_REUSE):
conv5 = tf.layers.conv2d_transpose(conv4, 32, (128, 128), strides=1, activation=tf.nn.relu)
with tf.variable_scope('conv6_1x1', reuse=tf.AUTO_REUSE):
conv6 = tf.layers.conv2d(conv5, 1, 1, strides=1, activation=tf.nn.relu)
return conv6
init_optimizer()
剪断:
def init_optimizer(self):
self._loss_op = tf.reduce_mean((tf.nn.sparse_softmax_cross_entropy_with_logits(labels=tf.squeeze(self._target_placeholder, [3]), logits=self._model, name="Loss")))
optimizer = tf.train.AdamOptimizer(learning_rate=self._learning_rate_placeholder)
self._train_op = optimizer.minimize(self._loss_op)