Tensorflow 使用和不使用自定义循环的Keras回归自定义损失返回值
当在Keras模型中定义自定义损失时,在线来源似乎表明损失应返回一个值数组(批次中每个样本的损失)。像这样的Tensorflow 使用和不使用自定义循环的Keras回归自定义损失返回值,tensorflow,machine-learning,keras,neural-network,Tensorflow,Machine Learning,Keras,Neural Network,当在Keras模型中定义自定义损失时,在线来源似乎表明损失应返回一个值数组(批次中每个样本的损失)。像这样的 def custom_loss_function(y_true, y_pred): squared_difference = tf.square(y_true - y_pred) return tf.reduce_mean(squared_difference, axis=-1) model.compile(optimizer='adam', loss=custom_los
def custom_loss_function(y_true, y_pred):
squared_difference = tf.square(y_true - y_pred)
return tf.reduce_mean(squared_difference, axis=-1)
model.compile(optimizer='adam', loss=custom_loss_function)
在上面的示例中,我不知道模型何时或是否使用tf.reduce\u sum()
或tf.reduce\u mean()
在另一种情况下,当我们想要用自定义函数实现自定义训练循环时,根据Keras文档遵循的模板如下
for epoch in range(epochs):
for step, (x_batch_train, y_batch_train) in enumerate(train_dataset):
with tf.GradientTape() as tape:
y_batch_pred = model(x_batch_train, training=True)
loss_value = custom_loss_function(y_batch_train, y_batch_pred)
grads = tape.gradient(loss_value, model.trainable_weights)
optimizer.apply_gradients(zip(grads, model.trainable_weights))
根据这本书,如果我理解正确,我们应该取批次梯度的平均值。因此,上述损失值应为每批的单个值
但是,该示例将适用于以下两种变体:
tf.减少每个样本的损失数组的平均值(平方差,轴=-1)
tf.减少批次的平均值(平方差)#平均损失
apply_gradients
是否按顺序对每个值应用小的更改?这是错误的,虽然它的工作
没有自定义循环和有自定义循环的正确方法是什么?好问题。在我看来,TensorFlow/Keras API中没有很好地记录这一点。默认情况下,如果不提供标量
损耗值
,TensorFlow将提供(并且更新不是顺序的)。本质上,这相当于沿批次轴将损失相加
目前,TensorFlow API中的损失包括一个
reduce
参数(例如),该参数允许指定如何沿批次轴聚合损失。y\u batch\u train和y\u batch\u pred具有哪些维度?是numpy阵列吗?这可能是;这里的答案对你有帮助吗?@今天它帮助了一点——肯定是重叠的问题