Jon*_*han 11 python machine-learning deep-learning keras tensorflow
假设我有以下参数的网络:
现在,我知道损失是按以下方式计算的:二进制交叉熵应用于图像中关于每个类的每个像素.基本上,每个像素将有5个损耗值
这一步后会发生什么?
当我训练我的网络时,它只为一个纪元打印一个损失值.在生成单个值时需要进行多种级别的损失累积,以及在文档/代码中它的发生方式根本不明确.
axis=-1
.那么这是所有类的所有像素的平均值还是所有类的平均值,还是两者都是?以不同的方式说明:不同类别的损失如何组合以产生图像的单一损失值?
这完全没有在文档中解释,对于对keras进行多类预测的人来说非常有用,无论网络类型如何.这是keras代码开始的链接,其中一个首先通过了损失函数.
我能找到最接近解释的是
loss:String(目标函数的名称)或目标函数.看到损失.如果模型具有多个输出,则可以通过传递字典或损失列表在每个输出上使用不同的损失.然后,模型将最小化的损失值将是所有单个损失的总和
来自keras.那么这是否意味着图像中每个类的损失只是总和?
此处的示例代码供有人试用.这是从Kaggle借来的基本实现,并针对多标签预测进行了修改:
# Build U-Net model
num_classes = 5
IMG_DIM = 256
IMG_CHAN = 3
weights = {0: 1, 1: 1, 2: 1, 3: 1, 4: 1000} #chose an extreme value just to check for any reaction
inputs = Input((IMG_DIM, IMG_DIM, IMG_CHAN))
s = Lambda(lambda x: x / 255) (inputs)
c1 = Conv2D(8, (3, 3), activation='relu', padding='same') (s)
c1 = Conv2D(8, (3, 3), activation='relu', padding='same') (c1)
p1 = MaxPooling2D((2, 2)) (c1)
c2 = Conv2D(16, (3, 3), activation='relu', padding='same') (p1)
c2 = Conv2D(16, (3, 3), activation='relu', padding='same') (c2)
p2 = MaxPooling2D((2, 2)) (c2)
c3 = Conv2D(32, (3, 3), activation='relu', padding='same') (p2)
c3 = Conv2D(32, (3, 3), activation='relu', padding='same') (c3)
p3 = MaxPooling2D((2, 2)) (c3)
c4 = Conv2D(64, (3, 3), activation='relu', padding='same') (p3)
c4 = Conv2D(64, (3, 3), activation='relu', padding='same') (c4)
p4 = MaxPooling2D(pool_size=(2, 2)) (c4)
c5 = Conv2D(128, (3, 3), activation='relu', padding='same') (p4)
c5 = Conv2D(128, (3, 3), activation='relu', padding='same') (c5)
u6 = Conv2DTranspose(64, (2, 2), strides=(2, 2), padding='same') (c5)
u6 = concatenate([u6, c4])
c6 = Conv2D(64, (3, 3), activation='relu', padding='same') (u6)
c6 = Conv2D(64, (3, 3), activation='relu', padding='same') (c6)
u7 = Conv2DTranspose(32, (2, 2), strides=(2, 2), padding='same') (c6)
u7 = concatenate([u7, c3])
c7 = Conv2D(32, (3, 3), activation='relu', padding='same') (u7)
c7 = Conv2D(32, (3, 3), activation='relu', padding='same') (c7)
u8 = Conv2DTranspose(16, (2, 2), strides=(2, 2), padding='same') (c7)
u8 = concatenate([u8, c2])
c8 = Conv2D(16, (3, 3), activation='relu', padding='same') (u8)
c8 = Conv2D(16, (3, 3), activation='relu', padding='same') (c8)
u9 = Conv2DTranspose(8, (2, 2), strides=(2, 2), padding='same') (c8)
u9 = concatenate([u9, c1], axis=3)
c9 = Conv2D(8, (3, 3), activation='relu', padding='same') (u9)
c9 = Conv2D(8, (3, 3), activation='relu', padding='same') (c9)
outputs = Conv2D(num_classes, (1, 1), activation='sigmoid') (c9)
model = Model(inputs=[inputs], outputs=[outputs])
model.compile(optimizer='adam', loss=weighted_loss(weights), metrics=[mean_iou])
def weighted_loss(weightsList):
def lossFunc(true, pred):
axis = -1 #if channels last
#axis= 1 #if channels first
classSelectors = K.argmax(true, axis=axis)
classSelectors = [K.equal(tf.cast(i, tf.int64), tf.cast(classSelectors, tf.int64)) for i in range(len(weightsList))]
classSelectors = [K.cast(x, K.floatx()) for x in classSelectors]
weights = [sel * w for sel,w in zip(classSelectors, weightsList)]
weightMultiplier = weights[0]
for i in range(1, len(weights)):
weightMultiplier = weightMultiplier + weights[i]
loss = BCE_loss(true, pred) - (1+dice_coef(true, pred))
loss = loss * weightMultiplier
return loss
return lossFunc
model.summary()
Run Code Online (Sandbox Code Playgroud)
实际的BCE-DICE损失功能可以在这里找到.
问题的动机:基于上述代码,20个时期后网络的总验证损失约为1%; 然而,前4个班级的联盟得分平均交叉点各自超过95%,但最后一个班级则为23%.清楚地表明第五节课表现不佳.但是,这种损失的准确性并没有在损失中得到反映.因此,这意味着样本的个人损失正在以一种完全抵消我们在第五类中看到的巨大损失的方式进行组合.因此,当每个样品的损失在批次中合并时,它仍然非常低.我不确定如何调和这些信息.
虽然我已经在相关答案中提到了这个答案的一部分,但让我们一步一步地检查源代码,了解更多细节,以找到具体的答案。
首先,让我们前馈(!):有一个叫于weighted_loss
函数,它接受y_true
,y_pred
,sample_weight
并mask
作为输入:
weighted_loss = weighted_losses[i]
# ...
output_loss = weighted_loss(y_true, y_pred, sample_weight, mask)
Run Code Online (Sandbox Code Playgroud)
weighted_loss
实际上是一个列表的元素,其中包含传递给fit
方法的所有(增强的)损失函数:
weighted_losses = [
weighted_masked_objective(fn) for fn in loss_functions]
Run Code Online (Sandbox Code Playgroud)
我提到的“增强”一词在这里很重要。这是因为,正如你在上面看到的,实际的损失函数被另一个被调用的函数包裹,weighted_masked_objective
它的定义如下:
def weighted_masked_objective(fn):
"""Adds support for masking and sample-weighting to an objective function.
It transforms an objective function `fn(y_true, y_pred)`
into a sample-weighted, cost-masked objective function
`fn(y_true, y_pred, weights, mask)`.
# Arguments
fn: The objective function to wrap,
with signature `fn(y_true, y_pred)`.
# Returns
A function with signature `fn(y_true, y_pred, weights, mask)`.
"""
if fn is None:
return None
def weighted(y_true, y_pred, weights, mask=None):
"""Wrapper function.
# Arguments
y_true: `y_true` argument of `fn`.
y_pred: `y_pred` argument of `fn`.
weights: Weights tensor.
mask: Mask tensor.
# Returns
Scalar tensor.
"""
# score_array has ndim >= 2
score_array = fn(y_true, y_pred)
if mask is not None:
# Cast the mask to floatX to avoid float64 upcasting in Theano
mask = K.cast(mask, K.floatx())
# mask should have the same shape as score_array
score_array *= mask
# the loss per batch should be proportional
# to the number of unmasked samples.
score_array /= K.mean(mask)
# apply sample weighting
if weights is not None:
# reduce score_array to same ndim as weight array
ndim = K.ndim(score_array)
weight_ndim = K.ndim(weights)
score_array = K.mean(score_array,
axis=list(range(weight_ndim, ndim)))
score_array *= weights
score_array /= K.mean(K.cast(K.not_equal(weights, 0), K.floatx()))
return K.mean(score_array)
return weighted
Run Code Online (Sandbox Code Playgroud)
所以,有一个嵌套函数,weighted
即实际调用真正的损失函数fn
的线score_array = fn(y_true, y_pred)
。现在,具体而言,在 OP 提供的示例的情况下,fn
(即损失函数)是binary_crossentropy
。因此我们需要看一下binary_crossentropy()
Keras中的定义:
def binary_crossentropy(y_true, y_pred):
return K.mean(K.binary_crossentropy(y_true, y_pred), axis=-1)
Run Code Online (Sandbox Code Playgroud)
反过来,调用后端函数K.binary_crossentropy()
。如果使用 Tensorflow 作为后端,其定义K.binary_crossentropy()
如下:
def binary_crossentropy(target, output, from_logits=False):
"""Binary crossentropy between an output tensor and a target tensor.
# Arguments
target: A tensor with the same shape as `output`.
output: A tensor.
from_logits: Whether `output` is expected to be a logits tensor.
By default, we consider that `output`
encodes a probability distribution.
# Returns
A tensor.
"""
# Note: tf.nn.sigmoid_cross_entropy_with_logits
# expects logits, Keras expects probabilities.
if not from_logits:
# transform back to logits
_epsilon = _to_tensor(epsilon(), output.dtype.base_dtype)
output = tf.clip_by_value(output, _epsilon, 1 - _epsilon)
output = tf.log(output / (1 - output))
return tf.nn.sigmoid_cross_entropy_with_logits(labels=target,
logits=output)
Run Code Online (Sandbox Code Playgroud)
的tf.nn.sigmoid_cross_entropy_with_logits
回报:
形状
logits
与组件逻辑损失相同的张量。
现在,让我们反向传播(!):考虑到上面的注释, 的输出形状K.binray_crossentropy
将与y_pred
(或y_true
)相同。正如 OP 所述,y_true
形状为(batch_size, img_dim, img_dim, num_classes)
. 因此,将K.mean(..., axis=-1)
应用于形状为 的张量,(batch_size, img_dim, img_dim, num_classes)
从而产生形状为 的输出张量(batch_size, img_dim, img_dim)
。所以所有类的损失值都是为图像中的每个像素取平均值。因此,上面提到的score_array
inweighted
函数的形状将是(batch_size, img_dim, img_dim)
。还有一步:weighted
函数中的 return 语句再次取平均值,即return K.mean(score_array)
。那么它是如何计算均值的呢?如果您查看mean
后端函数的定义,您会发现该axis
参数None
默认为:
def mean(x, axis=None, keepdims=False):
"""Mean of a tensor, alongside the specified axis.
# Arguments
x: A tensor or variable.
axis: A list of integer. Axes to compute the mean.
keepdims: A boolean, whether to keep the dimensions or not.
If `keepdims` is `False`, the rank of the tensor is reduced
by 1 for each entry in `axis`. If `keepdims` is `True`,
the reduced dimensions are retained with length 1.
# Returns
A tensor with the mean of elements of `x`.
"""
if x.dtype.base_dtype == tf.bool:
x = tf.cast(x, floatx())
return tf.reduce_mean(x, axis, keepdims)
Run Code Online (Sandbox Code Playgroud)
它调用tf.reduce_mean()
给定axis=None
参数的 ,取输入张量所有轴的平均值并返回一个值。因此,(batch_size, img_dim, img_dim)
计算整个形状张量的平均值,这意味着对批次中的所有标签及其所有像素取平均值,并作为表示损失值的单个标量值返回。然后,这个损失值由 Keras 上报并用于优化。
奖励:如果我们的模型有多个输出层,因此使用多个损失函数怎么办?
记住我在这个答案中提到的第一段代码:
weighted_loss = weighted_losses[i]
# ...
output_loss = weighted_loss(y_true, y_pred, sample_weight, mask)
Run Code Online (Sandbox Code Playgroud)
如您所见,有一个i
变量用于索引数组。您可能猜对了:它实际上是循环的一部分,该循环使用其指定的损失函数计算每个输出层的损失值,然后取所有这些损失值的(加权)总和来计算总损失:
# Compute total loss.
total_loss = None
with K.name_scope('loss'):
for i in range(len(self.outputs)):
if i in skip_target_indices:
continue
y_true = self.targets[i]
y_pred = self.outputs[i]
weighted_loss = weighted_losses[i]
sample_weight = sample_weights[i]
mask = masks[i]
loss_weight = loss_weights_list[i]
with K.name_scope(self.output_names[i] + '_loss'):
output_loss = weighted_loss(y_true, y_pred,
sample_weight, mask)
if len(self.outputs) > 1:
self.metrics_tensors.append(output_loss)
self.metrics_names.append(self.output_names[i] + '_loss')
if total_loss is None:
total_loss = loss_weight * output_loss
else:
total_loss += loss_weight * output_loss
if total_loss is None:
if not self.losses:
raise ValueError('The model cannot be compiled '
'because it has no loss to optimize.')
else:
total_loss = 0.
# Add regularization penalties
# and other layer-specific losses.
for loss_tensor in self.losses:
total_loss += loss_tensor
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1471 次 |
最近记录: |